#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Move settings and docs out of the modal into their own pages (#7792)
Anthony Stirling77b325cf1e23
diff --git a/.github/workflows/Saas-Dev-Deploy.yml b/.github/workflows/Saas-Dev-Deploy.ymlindex 2492fc0479..9134a5f1e9 100644--- a/.github/workflows/Saas-Dev-Deploy.yml+++ b/.github/workflows/Saas-Dev-Deploy.yml@@ -93,6 +93,7 @@ jobs:VERSION_TAG=v2-alphaSTIRLING_FLAVOR=saasVITE_BUILD_MODE=development+ VITE_INCLUDE_PORTAL=trueVITE_SUPABASE_URL=${{ steps.config.outputs.supabase_url }}VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=${{ secrets.SAAS_SUPABASE_PUBLISHABLE_KEY }}platforms: linux/amd64diff --git a/.github/workflows/sync-portal-docs.yml b/.github/workflows/sync-portal-docs.ymlindex a6073b3f1f..23b45e22a0 100644--- a/.github/workflows/sync-portal-docs.yml+++ b/.github/workflows/sync-portal-docs.yml@@ -85,12 +85,12 @@ jobs:body: |Auto-generated by ${{ steps.setup-bot.outputs.app-slug }}[bot].- Regenerates `frontend/editor/src/portal/generated/docsManifest.json`+ Regenerates `frontend/editor/src/core/generated/docsManifest.json`from the Stirling docs repo via `npm run docs:sync`.labels: |Documentationgithub-actionsFront End- add-paths: frontend/editor/src/portal/generated/docsManifest.json+ add-paths: frontend/editor/src/core/generated/docsManifest.jsondelete-branch: truesign-commits: truediff --git a/docker/frontend/Dockerfile b/docker/frontend/Dockerfileindex 67e35f82c5..fee78ec38a 100644--- a/docker/frontend/Dockerfile+++ b/docker/frontend/Dockerfile@@ -17,6 +17,10 @@ RUN node editor/scripts/generate-icons.js# Defaults match prior behaviour. Supabase values are client-publishable build args.ARG STIRLING_FLAVOR=proprietaryARG VITE_BUILD_MODE=production+# Include the processor (admin portal) route/chunk. SaaS ships it, so its+# deploy sets this true; without it /processor and the processor's settings+# sections are absent from the built app.+ARG VITE_INCLUDE_PORTAL=falseARG VITE_SUPABASE_URL=""# pragma: allowlist secretARG VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=""diff --git a/frontend/.oxfmtrc.json b/frontend/.oxfmtrc.jsonindex cb801651b8..7a8f433c56 100644--- a/frontend/.oxfmtrc.json+++ b/frontend/.oxfmtrc.json@@ -15,7 +15,7 @@"editor/public/og-metadata.json","editor/public/og-metadata.saas.json","editor/src/core/data/ogImageMap.json",- "editor/src/portal/generated/docsManifest.json",+ "editor/src/core/generated/docsManifest.json","editor/public/pdfjs*/","editor/public/js/thirdParty/","editor/public/css/cookieconsent.css",diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 49ceb554a6..3326bc02a2 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -727,6 +727,9 @@ manualLinks = "Manual downloads: click the links and place the files into the tenoLanguages = "No tessdata languages found in the configured directory."permissionNotice = "The tessdata path is not writable. Downloads will be opened in the browser; please save the .traineddata files manually into the tessdata folder."+[admin.settings.ai]+description = "Connect Stirling to the Python AI engine, choose its models, and set the guardrails it runs under."+[admin.settings.ai.documents]description = "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved."title = "Documents & RAG"@@ -766,6 +769,7 @@ description = "Number of most-relevant chunks retrieved per search."label = "Top K"[admin.settings.ai.general]+connection = "Connection"description = "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart."title = "AI Engine"@@ -892,7 +896,8 @@ clickToUpgrade = "Click to view plan details"[admin.settings.connections]connect = "Connect"-description = "Configure external authentication providers like OAuth2 and SAML."+connectedServicesDescription = "Services this server is wired up to. Sign-in providers live under Sign-in & security."+description = "Mail, Telegram, Drive, and uploading from a phone."disconnect = "Disconnect"disconnected = "Provider disconnected successfully"disconnectError = "Failed to disconnect provider"@@ -1014,6 +1019,8 @@ configuration = "Database Configuration"confirmCodeLabel = "Enter the confirmation code to proceed"confirmImport = "Confirm import"confirmImportTitle = "Confirm database import"+connection = "Connection"+connectionDescription = "Point Stirling at an external database instead of the embedded one."createBackup = "Create backup"created = "Created"delete = "Delete"@@ -1022,7 +1029,7 @@ deleteConfirmAction = "Delete backup"deleteFailed = "Failed to delete backup"deleteSuccess = "Backup deleted"deleteTitle = "Delete backup"-description = "Configure custom database connection settings for enterprise deployments."+description = "Connect a custom database, and back up or restore the one in use."download = "Download"downloadFailed = "Failed to download backup"embedded = "Embedded H2"@@ -1115,12 +1122,12 @@ description = "Configure optional features and functionality."title = "Features"[admin.settings.features.serverCertificate]-description = "Configure server-side certificate generation for \"Sign with Stirling-PDF\" functionality"-label = "Server Certificate"+description = "Generate the certificate that backs the \"Sign with Stirling-PDF\" signing feature."+label = "Certificate Signing"[admin.settings.features.serverCertificate.enabled]-description = "Enable server-side certificate for \"Sign with Stirling-PDF\" option"-label = "Enable Server Certificate"+description = "Offer \"Sign with Stirling-PDF\" using a certificate this server generates"+label = "Enable Certificate Signing"[admin.settings.features.serverCertificate.organizationName]description = "Organization name for generated certificates"@@ -1154,7 +1161,8 @@ placeholder = "/data/inbox"remove = "Remove folder root"[admin.settings.general]-description = "Configure system-wide application settings including branding and default behavior."+branding = "Branding & appearance"+description = "How this server runs: branding, storage, the tools it exposes, and the paths it may touch."system = "System"title = "System Settings"ui = "User Interface"@@ -1274,7 +1282,8 @@ description = "Restrict update notifications to admin users only"label = "Show Updates to Admins Only"[admin.settings.legal]-description = "Configure links to legal documents and policies."+description = "Legal documents, the login agreement, analytics and search visibility."+documentsDescription = "Links users are shown for terms, privacy, cookies and the impressum."title = "Legal Documents"[admin.settings.legal.accessibilityStatement]@@ -1437,8 +1446,8 @@ description = "JWT claim matched against a Stirling username (e.g. sub, email, plabel = "Username claim"[admin.settings.plan.noData]-message = "Plans data is not available at the moment."-title = "No data available"+message = "This server could not reach the licence service. Retry, or check the licence key."+title = "No plan data"[admin.settings.premium]description = "Configure your premium or enterprise license key."@@ -1494,7 +1503,7 @@ title = "Premium Features Distributed"[admin.settings.privacy]analytics = "Analytics & Tracking"-description = "Configure privacy and data collection settings."+description = "What this server reports about itself, and to whom."searchEngine = "Search Engine Visibility"title = "Privacy"@@ -1528,8 +1537,7 @@ label = "Audit Logging"showDetails = "Show audit level details"[admin.settings.security.audit.advancedOptions]-description = "The following options increase processing time and memory usage. Enable only if truly needed."-title = "Advanced Options"+cost = "Now increasing processing time and memory usage on every operation."[admin.settings.security.audit.captureFileHash]description = "Extract SHA-256 hash of uploaded PDF files for integrity verification. Independent of audit level."@@ -1677,7 +1685,7 @@ description = "Time before failed login attempts are reset"label = "Login Reset Time (minutes)"[admin.settings.security.ssoNotice]-message = "OAuth2 and SAML2 authentication providers have been moved to the Connections menu for easier management."+message = "OAuth2 and SAML2 authentication providers live under Single sign-on, next to this section."title = "Looking for SSO/SAML settings?"[admin.settings.security.xFrameOptions]@@ -1939,8 +1947,8 @@ disabledMessage = "Enable audit logging in your application configuration to traenterpriseRequired = "Enterprise License Required"enterpriseRequiredMessage = "The audit logging system is an enterprise feature. Please upgrade to an enterprise license to access audit logs and analytics."goToSettings = "Go to Audit Settings"-notAvailable = "Audit system not available"-notAvailableMessage = "The audit system is not configured or not available."+notAvailable = "Audit logging is off"+notAvailableMessage = "Turn it on in Sign-in & security to start recording activity."[audit.charts]byType = "Events by Type"@@ -3630,7 +3638,9 @@ tags = "squish,small,tiny"[config]plan = "Plan"+planDescription = "Your plan, credits and spend limit, and the invoices behind them."team = "Team"+teamDescription = "Who shares this workspace, and invitations still waiting on an answer."[config.account.overview]confirmDelete = "Delete My Account"@@ -3722,7 +3732,6 @@ description = "Model Context Protocol (MCP) lets AI assistants like Claude use yguestInfo = "Guest users can't connect MCP clients. Create an account to use the MCP server and let your AI assistant run Stirling PDF tools on your behalf."navLabel = "MCP Server"tip = "Every action your assistant runs is performed as your account and counts toward your usage, just like using Stirling PDF directly."-title = "MCP Server"viewApiKeys = "View API keys"[config.mcp.copy]@@ -7129,9 +7138,6 @@ pdfa-1 = "PDF/A-1b"pdfa-2b = "PDF/A-2b"pdfa-3b = "PDF/A-3b"-[portal]-comingSoon = "Coming soon"-[portal.accountLink.card]billingNote = "Unattended processing bills against your org wallet."eyebrow = "Account link"@@ -8310,11 +8316,6 @@ afternoon = "Good afternoon"evening = "Good evening"morning = "Good morning"-[portal.infrastructure]-sectionsAriaLabel = "Infrastructure sections"-subtitle = "API credentials and the audit trail for your Stirling workspace."-title = "Infrastructure"-[portal.infrastructure.apiKeys]createKey = "Create key"heading = "API keys"@@ -8594,14 +8595,6 @@ off = "Off"active = "Active"revoked = "Revoked"-[portal.infrastructure.tabs]-apiKeys = "API Keys"-audit = "Audit Logs"-deployments = "Deployments"-models = "Models"-security = "Security"-storage = "Storage"-[portal.integrations]availableHeading = "Available"comingSoonHeading = "Coming soon"@@ -9616,9 +9609,6 @@ title = "Enterprise trial"subtitle = "Anything from your policy runs and your team's editors that needs your attention."title = "Review"-[portal.settings.groups]-admin = "Admin"-[portal.settings.sections]account-link = "Account link"@@ -10149,6 +10139,8 @@ config = "Config"files = "Files"[quickNav]+account = "Account"+docs = "Documentation"editor = "Editor"home = "Stirling"invite = "Invite"@@ -10679,12 +10671,15 @@ expired = "Your session has expired. Please refresh the page and try again."[settings]backToSections = "All settings"-close = "Close"title = "Settings"+[settings.about]+description = "Tours, legal documents and the licences of everything bundled with this build."+title = "About"+[settings.ai]documents = "Documents & RAG"-general = "General"+general = "AI Engine"limits = "Limits & Performance"models = "Models & Providers"title = "AI"@@ -10695,12 +10690,13 @@ database = "Database"endpoints = "Endpoints"features = "Features"folderAccess = "Folder Access"+integrations = "Integrations"mcp = "MCP Server"storageSharing = "File Storage & Sharing"systemSettings = "System Settings"-title = "Configuration"[settings.connection]+description = "Work locally on this machine or connect the app to a Stirling server."localDescription = "You are using the local backend without an account. Some tools requiring cloud processing or a self-hosted server are unavailable."logout = "Log Out"server = "Server"@@ -10715,13 +10711,12 @@ selfhosted = "Self-Hosted"[settings.developer]apiKeys = "API Keys"+apiKeysDescription = "Personal keys for calling the Stirling API from scripts and integrations."title = "Developer"[settings.general]autoUnzip = "Auto-unzip API responses"-autoUnzipDescription = "Automatically extract files from ZIP responses"autoUnzipFileLimit = "Auto-unzip file limit"-autoUnzipFileLimitDescription = "Maximum number of files to extract from ZIP"autoUnzipFileLimitTooltip = "Only unzip if the ZIP contains this many files or fewer. Set higher to extract larger ZIPs."autoUnzipTooltip = "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows."defaultPdfEditor = "Default PDF editor"@@ -10814,6 +10809,7 @@ fitPage = "Fit page"fitWidth = "Fit width"[settings.help]+description = "Guided walkthroughs of the editor and the admin area."label = "Tours"title = "Help"@@ -10846,6 +10842,7 @@ mac = "Include ⌘ (Command), ⌥ (Option), or another modifier in your shortcutwindows = "Include Ctrl, Alt, or another modifier in your shortcut."[settings.legal]+description = "Terms, privacy policy and your cookie preferences."label = "Legal"title = "Legal"@@ -10873,10 +10870,16 @@ module = "Module"version = "Version"[settings.licensingAnalytics]-audit = "Audit"+audit = "Audit log"+auditDescription = "Who did what on this server, and how long that record is kept."plan = "Plan"-title = "Licensing & Analytics"+planDescription = "Your licence, seats and what the current plan unlocks."+usage = "Usage Analytics"usageAnalytics = "Usage Analytics"+usageDescription = "How the server is being used: operations, volume and trends over time."++[settings.monitoring]+title = "Monitoring"[settings.planBilling]currentPlan = "Current Plan"@@ -10933,11 +10936,15 @@ subtitle = "Upgrade to Team for:"title = "Upgrade Your Plan"[settings.policiesPrivacy]-legal = "Legal"+legal = "Legal documents"privacy = "Privacy"-title = "Policies & Privacy"+title = "Legal & privacy"[settings.preferences]+appearance = "Appearance"+description = "How the editor looks and behaves for you, and your account."+downloads = "Downloads"+editorDefaults = "Editor defaults"title = "Preferences"[settings.security]@@ -10960,10 +10967,14 @@ success = "Password updated successfully. Please sign in again."update = "Update password"[settings.securityAuth]-connections = "Connections"-security = "Security"+connections = "Single sign-on"+security = "Sign-in & security"telegram = "Telegram"-title = "Security & Authentication"+title = "Security & sign-in"++[settings.server]+system = "System"+title = "Server"[settings.signOut]confirm = "Are you sure you want to sign out?"@@ -11885,8 +11896,8 @@ title = "URL To PDF"aboutUsageAnalytics = "About Usage Analytics"configureSettings = "Configure Analytics Settings"error = "Error loading usage statistics"-noData = "No data available"-noDataMessage = "No usage statistics are currently available."+noData = "No usage yet"+noDataMessage = "Endpoint activity appears here once people start running tools."usageAnalyticsExplanation = "Usage analytics track endpoint requests and tool usage patterns. Combined with the Audit Logging dashboard, you get complete visibility into system activity, performance, and security events."viewAuditLogs = "View Audit Logs"@@ -12748,7 +12759,6 @@ noMembersFound = "No members found"role = "Role"searchMembers = "Search members..."team = "Team"-title = "People"unlockAccount = "Unlock Account"unlockUserError = "Failed to unlock user account"unlockUserSuccess = "User account unlocked successfully"@@ -12902,7 +12912,6 @@ system = "System"teamActions = "Team actions"teamName = "Team Name"teamNotFound = "Team not found"-title = "Teams"totalMembers = "Total Members"viewTeam = "View Team"diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.jsonindex 87c05a8d2d..eb0fab1c63 100644--- a/frontend/editor/public/og-metadata.json+++ b/frontend/editor/public/og-metadata.json@@ -515,6 +515,11 @@"title": "Admin Ai Limits Settings - Stirling PDF","description": "The Free Adobe Acrobat alternative (10M+ Downloads)"},+ "/settings/adminAi": {+ "image": "/og_images/home.png",+ "title": "Admin Ai Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },"/settings/help": {"image": "/og_images/home.png","title": "Help Settings - Stirling PDF",@@ -535,6 +540,11 @@"title": "Frontend Third Party Licenses Settings - Stirling PDF","description": "The Free Adobe Acrobat alternative (10M+ Downloads)"},+ "/settings/about": {+ "image": "/og_images/home.png",+ "title": "About Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },"/settings/payg": {"image": "/og_images/home.png","title": "Payg Settings - Stirling PDF",@@ -544,6 +554,26 @@"image": "/og_images/home.png","title": "Account Link Settings - Stirling PDF","description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/users": {+ "image": "/og_images/home.png",+ "title": "Users Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/billing": {+ "image": "/og_images/home.png",+ "title": "Billing Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/audit": {+ "image": "/og_images/home.png",+ "title": "Audit Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/storage": {+ "image": "/og_images/home.png",+ "title": "Storage Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"}},"byPath": {@@ -702,11 +732,17 @@"/settings/adminAiModels": "/settings/adminAiModels","/settings/adminAiDocuments": "/settings/adminAiDocuments","/settings/adminAiLimits": "/settings/adminAiLimits",+ "/settings/adminAi": "/settings/adminAi","/settings/help": "/settings/help","/settings/legal": "/settings/legal","/settings/backendThirdPartyLicenses": "/settings/backendThirdPartyLicenses","/settings/frontendThirdPartyLicenses": "/settings/frontendThirdPartyLicenses",+ "/settings/about": "/settings/about","/settings/payg": "/settings/payg",- "/settings/account-link": "/settings/account-link"+ "/settings/account-link": "/settings/account-link",+ "/settings/users": "/settings/users",+ "/settings/billing": "/settings/billing",+ "/settings/audit": "/settings/audit",+ "/settings/storage": "/settings/storage"}}diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.jsonindex d73b8bab55..a682f8f522 100644--- a/frontend/editor/public/og-metadata.saas.json+++ b/frontend/editor/public/og-metadata.saas.json@@ -517,6 +517,11 @@"title": "Admin Ai Limits Settings - Stirling PDF","description": "The Free Adobe Acrobat alternative (10M+ Downloads)"},+ "/settings/adminAi": {+ "image": "/og_images/home.png",+ "title": "Admin Ai Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },"/settings/help": {"image": "/og_images/home.png","title": "Help Settings - Stirling PDF",@@ -537,6 +542,11 @@"title": "Frontend Third Party Licenses Settings - Stirling PDF","description": "The Free Adobe Acrobat alternative (10M+ Downloads)"},+ "/settings/about": {+ "image": "/og_images/home.png",+ "title": "About Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },"/settings/payg": {"image": "/og_images/home.png","title": "Payg Settings - Stirling PDF",@@ -547,6 +557,26 @@"title": "Account Link Settings - Stirling PDF","description": "The Free Adobe Acrobat alternative (10M+ Downloads)"},+ "/settings/users": {+ "image": "/og_images/home.png",+ "title": "Users Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/billing": {+ "image": "/og_images/home.png",+ "title": "Billing Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/audit": {+ "image": "/og_images/home.png",+ "title": "Audit Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },+ "/settings/storage": {+ "image": "/og_images/home.png",+ "title": "Storage Settings - Stirling PDF",+ "description": "The Free Adobe Acrobat alternative (10M+ Downloads)"+ },"/signup": {"image": "/og_images/home.png","title": "Sign Up - Stirling PDF",@@ -715,12 +745,18 @@"/settings/adminAiModels": "/settings/adminAiModels","/settings/adminAiDocuments": "/settings/adminAiDocuments","/settings/adminAiLimits": "/settings/adminAiLimits",+ "/settings/adminAi": "/settings/adminAi","/settings/help": "/settings/help","/settings/legal": "/settings/legal","/settings/backendThirdPartyLicenses": "/settings/backendThirdPartyLicenses","/settings/frontendThirdPartyLicenses": "/settings/frontendThirdPartyLicenses",+ "/settings/about": "/settings/about","/settings/payg": "/settings/payg","/settings/account-link": "/settings/account-link",+ "/settings/users": "/settings/users",+ "/settings/billing": "/settings/billing",+ "/settings/audit": "/settings/audit",+ "/settings/storage": "/settings/storage","/signup": "/signup","/processor": "/processor"}diff --git a/frontend/editor/scripts/sync-portal-docs.mts b/frontend/editor/scripts/sync-portal-docs.mtsindex 96f616eb46..33e935d789 100644--- a/frontend/editor/scripts/sync-portal-docs.mts+++ b/frontend/editor/scripts/sync-portal-docs.mts@@ -3,7 +3,7 @@** Fetches the docs repo tarball, extracts `docs/**` in-process (no external tar* binary, no per-file GitHub rate limits), shapes it with the pure transforms in- * src/portal/docs/manifest/transform.ts, and writes the committed manifest that+ * src/core/docs/manifest/transform.ts, and writes the committed manifest that* the portal docs view renders. Re-run with `npm run docs:sync`.** Env: DOCS_REPO, DOCS_REF, DOCS_ROOT override the defaults below.@@ -18,7 +18,7 @@ import {buildManifest,type CategoryMap,type RawDoc,-} from "../src/portal/docs/manifest/transform.ts";+} from "../src/core/docs/manifest/transform.ts";const REPO = process.env.DOCS_REPO ?? "Stirling-Tools/Stirling-Tools.github.io";const REF = process.env.DOCS_REF ?? "main";@@ -26,7 +26,7 @@ const ROOT = process.env.DOCS_ROOT ?? "docs";const SITE = "https://docs.stirlingpdf.com";const HERE = dirname(fileURLToPath(import.meta.url));-const OUT = resolve(HERE, "../src/portal/generated/docsManifest.json");+const OUT = resolve(HERE, "../src/core/generated/docsManifest.json");/* ── Minimal tar reader (ustar + pax/GNU long names) ─────────────────────── */diff --git a/frontend/editor/src/cloud/components/shared/config/cloudConfigNavSections.tsx b/frontend/editor/src/cloud/components/shared/config/cloudConfigNavSections.tsxindex 6890fd4fa7..a01cd26779 100644--- a/frontend/editor/src/cloud/components/shared/config/cloudConfigNavSections.tsx+++ b/frontend/editor/src/cloud/components/shared/config/cloudConfigNavSections.tsx@@ -21,16 +21,30 @@ export function createCloudPlanNavItem(t: Translate): ConfigNavItem {return {key: "plan",label: t("config.plan", "Plan"),+ description: t(+ "config.planDescription",+ "Your plan, credits and spend limit, and the invoices behind them.",+ ),icon: "credit-card",component: <Plan />,};}-/** The Team nav item — shared SaaS team management (invite/rename/members). */+/**+ * The workspace roster — shared SaaS team management (invite/rename/members).+ *+ * Same key, name and route as the processor's roster, which supersedes this one+ * for anyone with processor access: gaining that access must not rename the+ * section or move it to a different URL under the reader.+ */export function createCloudTeamNavItem(t: Translate): ConfigNavItem {return {- key: "teams",- label: t("config.team", "Team"),+ key: "users",+ label: t("portal.nav.users", "Users"),+ description: t(+ "config.teamDescription",+ "Who shares this workspace, and invitations still waiting on an answer.",+ ),icon: "groups-rounded",component: <TeamSection />,};diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.cssindex 54f4113f8f..6da431e385 100644--- a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css+++ b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css@@ -23,10 +23,8 @@}/* Backdrop locks the page and centres the modal. z-index matches- Z_INDEX_OVER_SETTINGS_MODAL (styles/zIndex.ts) — must sit above the- AppConfigModal's 1300 (Z_INDEX_OVER_FULLSCREEN_SURFACE). The config modal- also hides itself while we're open (appConfig:overlay event), so this is- belt-and-braces for the brief overlap during open/close transitions. */+ Z_INDEX_OVER_SETTINGS_MODAL (styles/zIndex.ts), above the settings page and+ anything it opens. */.upm-backdrop {position: fixed;inset: 0;diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsxindex 512d722bcf..87a0964c78 100644--- a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsx+++ b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.tsx@@ -16,7 +16,7 @@* <p>Cap state is held locally — nothing reaches the backend until the user* commits in step 2. A user who cancels mid-modal leaves no side effects.*/-import React, { Suspense, useEffect, useState } from "react";+import React, { Suspense, useState } from "react";import { createPortal } from "react-dom";import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";@@ -30,18 +30,6 @@ import "./UpgradeModal.css";// oxlint-disable-next-line no-restricted-importsimport SpendCapControl from "./SpendCapControl";-/**- * Tell the AppConfigModal (or any other full-screen surface listening) that an- * upgrade overlay is opening/closing so it can hide itself rather than stack- * under us. Same window-event pattern the config modal already uses for- * appConfig:navigate / appConfig:notice.- */-function dispatchOverlay(open: boolean) {- window.dispatchEvent(- new CustomEvent("appConfig:overlay", { detail: { open } }),- );-}-// Lazy-loaded so the @stripe/stripe-js bundle only downloads when the user// reaches step 2. See StripeCheckoutPanel.tsx for the full pattern + the// chunk-graph reasoning.@@ -114,15 +102,6 @@ export default function UpgradeModal({const [capUsd, setCapUsd] = useState<number>(500);const [noCap, setNoCap] = useState<boolean>(false);- // The config modal hides itself while we're open (it listens for this event)- // so the upgrade flow visually REPLACES it instead of stacking inside it.- // Cleanup fires open=false on unmount too, so the config modal can't get- // stuck hidden if we unmount without a clean close.- useEffect(() => {- dispatchOverlay(open);- return () => dispatchOverlay(false);- }, [open]);-if (!open) {return null;}diff --git a/frontend/editor/src/core/App.tsx b/frontend/editor/src/core/App.tsxindex c51c1fb85d..2c1ebd5a70 100644--- a/frontend/editor/src/core/App.tsx+++ b/frontend/editor/src/core/App.tsx@@ -6,7 +6,7 @@ import { AppLayout } from "@app/components/AppLayout";import { LoadingFallback } from "@app/components/shared/LoadingFallback";import { ThemeProvider } from "@app/components/shared/ThemeProvider";import { PreferencesProvider } from "@app/contexts/PreferencesContext";-import HomePage from "@app/pages/HomePage";+import { AppRoot } from "@app/components/layout/AppRoot";import Onboarding from "@app/components/onboarding/Onboarding";const MobileScannerPage = lazy(() => import("@app/pages/MobileScannerPage"));@@ -62,7 +62,7 @@ export default function App() {element={<AppProviders><AppLayout>- <HomePage />+ <AppRoot /><Onboarding /></AppLayout></AppProviders>diff --git a/frontend/editor/src/portal/views/DeveloperDocs.css b/frontend/editor/src/core/components/docs/DeveloperDocs.csssimilarity index 100%rename from frontend/editor/src/portal/views/DeveloperDocs.cssrename to frontend/editor/src/core/components/docs/DeveloperDocs.cssdiff --git a/frontend/editor/src/portal/views/DeveloperDocs.stories.tsx b/frontend/editor/src/core/components/docs/DeveloperDocs.stories.tsxsimilarity index 91%rename from frontend/editor/src/portal/views/DeveloperDocs.stories.tsxrename to frontend/editor/src/core/components/docs/DeveloperDocs.stories.tsxindex 70a2549e27..b3593b0d67 100644--- a/frontend/editor/src/portal/views/DeveloperDocs.stories.tsx+++ b/frontend/editor/src/core/components/docs/DeveloperDocs.stories.tsx@@ -1,5 +1,5 @@import type { Meta, StoryObj } from "@storybook/react-vite";-import { DeveloperDocs } from "@portal/views/DeveloperDocs";+import { DeveloperDocs } from "@app/components/docs/DeveloperDocs";// Renders the real docs manifest (generated by scripts/sync-portal-docs.mts), so// this story is a live view of the auto-built Documentation browser. The viewdiff --git a/frontend/editor/src/portal/views/DeveloperDocs.test.tsx b/frontend/editor/src/core/components/docs/DeveloperDocs.test.tsxsimilarity index 97%rename from frontend/editor/src/portal/views/DeveloperDocs.test.tsxrename to frontend/editor/src/core/components/docs/DeveloperDocs.test.tsxindex 354c6359c6..48a346fe6a 100644--- a/frontend/editor/src/portal/views/DeveloperDocs.test.tsx+++ b/frontend/editor/src/core/components/docs/DeveloperDocs.test.tsx@@ -13,7 +13,7 @@ vi.mock("react-i18next", () => ({}),}));-import { DeveloperDocs } from "@portal/views/DeveloperDocs";+import { DeveloperDocs } from "@app/components/docs/DeveloperDocs";const renderDocs = (ui: ReactElement) =>render(diff --git a/frontend/editor/src/portal/views/DeveloperDocs.tsx b/frontend/editor/src/core/components/docs/DeveloperDocs.tsxsimilarity index 88%rename from frontend/editor/src/portal/views/DeveloperDocs.tsxrename to frontend/editor/src/core/components/docs/DeveloperDocs.tsxindex d32666e1dd..c512216c59 100644--- a/frontend/editor/src/portal/views/DeveloperDocs.tsx+++ b/frontend/editor/src/core/components/docs/DeveloperDocs.tsx@@ -2,17 +2,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { useLocation, useNavigate } from "react-router-dom";import { Button, EmptyState } from "@app/ui";-import { DocsNav } from "@portal/components/docs/DocsNav";-import { DocsSection } from "@portal/components/docs/DocsSection";-import { DocsToc } from "@portal/components/docs/DocsToc";-import { MarkdownDoc } from "@portal/components/docs/MarkdownDoc";-import { extractHeadings } from "@portal/docs/headings";-import {- firstDocId,- loadDoc,- loadDocsNav,-} from "@portal/docs/manifest/registry";-import "@portal/views/DeveloperDocs.css";+import { DocsNav } from "@app/components/docs/DocsNav";+import { DocsSection } from "@app/components/docs/DocsSection";+import { DocsToc } from "@app/components/docs/DocsToc";+import { MarkdownDoc } from "@app/components/docs/MarkdownDoc";+import { extractHeadings } from "@app/docs/headings";+import { firstDocId, loadDoc, loadDocsNav } from "@app/docs/manifest/registry";+import "@app/components/docs/DeveloperDocs.css";/*** Developer Docs — a markdown browser over the docs manifest generated from thediff --git a/frontend/editor/src/portal/components/docs/DocsNav.tsx b/frontend/editor/src/core/components/docs/DocsNav.tsxsimilarity index 98%rename from frontend/editor/src/portal/components/docs/DocsNav.tsxrename to frontend/editor/src/core/components/docs/DocsNav.tsxindex 2f6258fca9..e2910f32da 100644--- a/frontend/editor/src/portal/components/docs/DocsNav.tsx+++ b/frontend/editor/src/core/components/docs/DocsNav.tsx@@ -1,7 +1,7 @@import { useEffect, useMemo, useRef, useState } from "react";import { Button, Skeleton, StatusBadge } from "@app/ui";import { useTranslation } from "react-i18next";-import type { DocsNavSection } from "@portal/api/docs";+import type { DocsNavSection } from "@app/docs/manifest/transform";/*** Left-hand documentation nav: a hierarchical accordion. Section ids encode theirdiff --git a/frontend/editor/src/core/components/docs/DocsPage.css b/frontend/editor/src/core/components/docs/DocsPage.cssnew file mode 100644index 0000000000..4377f0158d--- /dev/null+++ b/frontend/editor/src/core/components/docs/DocsPage.css@@ -0,0 +1,37 @@+/* The docs view sizes itself to its container; on a page that container is the+ frame's content area rather than the portal shell's scroll column. */+.docs-page {+ height: 100%;+ min-height: 0;+ background: var(--c-surface);+ color: var(--c-text-muted);+ font-family: var(--font-sans);+}++/* The view was authored inside the portal's scoped reset, so it assumes these+ rather than setting them per component. Kept at bare-element weight with+ :where() so component classes still win, and scoped to this page so nothing+ leaks into the editor that hosts the route. */+:where(.docs-page) *,+:where(.docs-page) *::before,+:where(.docs-page) *::after {+ box-sizing: border-box;+}++:where(.docs-page) button {+ font: inherit;+ color: inherit;+ background: none;+ border: none;+ padding: 0;+ cursor: pointer;+}++:where(.docs-page) a {+ color: var(--c-accent-text);+ text-decoration: none;+}++:where(.docs-page) a:hover {+ text-decoration: underline;+}diff --git a/frontend/editor/src/core/components/docs/DocsPage.tsx b/frontend/editor/src/core/components/docs/DocsPage.tsxnew file mode 100644index 0000000000..b68659fb9d--- /dev/null+++ b/frontend/editor/src/core/components/docs/DocsPage.tsx@@ -0,0 +1,31 @@+import { Suspense, lazy } from "react";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";+import { useOtherAppSwitch } from "@app/hooks/useOtherAppSwitch";+import "@app/components/docs/DocsPage.css";++// Its own chunk: the generated docs manifest is bundled JSON.+const DeveloperDocs = lazy(async () => {+ const m = await import("@app/components/docs/DeveloperDocs");+ return { default: m.DeveloperDocs };+});++/**+ * The documentation browser as a top-level page beside the editor and the+ * processor. Every build ships it: the docs describe the product, not the+ * processor, so gating them on that build flag hid them from the editions most+ * likely to need them.+ */+export default function DocsPage() {+ // The rail sits outside every app, so each page tells it what only the+ // signed-in session knows. Null in builds with no processor to switch to.+ const otherApp = useOtherAppSwitch();+ return (+ <div className="docs-page">+ <QuickNavHostBridge portalAccess={Boolean(otherApp)} />+ <Suspense fallback={<LoadingFallback />}>+ <DeveloperDocs />+ </Suspense>+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/docs/DocsSection.tsx b/frontend/editor/src/core/components/docs/DocsSection.tsxsimilarity index 100%rename from frontend/editor/src/portal/components/docs/DocsSection.tsxrename to frontend/editor/src/core/components/docs/DocsSection.tsxdiff --git a/frontend/editor/src/portal/components/docs/DocsToc.tsx b/frontend/editor/src/core/components/docs/DocsToc.tsxsimilarity index 97%rename from frontend/editor/src/portal/components/docs/DocsToc.tsxrename to frontend/editor/src/core/components/docs/DocsToc.tsxindex 1f6ee6ebad..d3ce2a909b 100644--- a/frontend/editor/src/portal/components/docs/DocsToc.tsx+++ b/frontend/editor/src/core/components/docs/DocsToc.tsx@@ -1,6 +1,6 @@import { useEffect, useState, type RefObject } from "react";import { useTranslation } from "react-i18next";-import type { Heading } from "@portal/docs/headings";+import type { Heading } from "@app/docs/headings";/*** "On this page" table of contents. Lists the current doc's H2/H3 headings,diff --git a/frontend/editor/src/portal/components/docs/MarkdownDoc.tsx b/frontend/editor/src/core/components/docs/MarkdownDoc.tsxsimilarity index 98%rename from frontend/editor/src/portal/components/docs/MarkdownDoc.tsxrename to frontend/editor/src/core/components/docs/MarkdownDoc.tsxindex faf3339478..212993e8a4 100644--- a/frontend/editor/src/portal/components/docs/MarkdownDoc.tsx+++ b/frontend/editor/src/core/components/docs/MarkdownDoc.tsx@@ -5,7 +5,7 @@ import ReactMarkdown, {} from "react-markdown";import remarkGfm from "remark-gfm";import { Button } from "@app/ui";-import { makeSlugger } from "@portal/docs/headings";+import { makeSlugger } from "@app/docs/headings";/** Flatten a heading's React children to plain text for its anchor id. */function childText(node: ReactNode): string {diff --git a/frontend/editor/src/core/components/layout/AppRoot.tsx b/frontend/editor/src/core/components/layout/AppRoot.tsxnew file mode 100644index 0000000000..b39fd349cd--- /dev/null+++ b/frontend/editor/src/core/components/layout/AppRoot.tsx@@ -0,0 +1,39 @@+import { Suspense, lazy } from "react";+import { useLocation } from "react-router-dom";+import HomePage from "@app/pages/HomePage";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import { stripBasePath } from "@app/constants/app";+import { DOCS_PATH, HAS_DOCS } from "@app/routes/docsRoute";++// Their own chunks: the settings tree (admin sections, account, licence flows)+// and the docs manifest are both large, and most sessions open neither.+const SettingsPage = lazy(() => import("@app/pages/SettingsPage"));+const DocsPage = lazy(() => import("@app/components/docs/DocsPage"));++/**+ * What the editor's route-set renders: the workbench, or one of the pages that+ * sit beside it. A switch rather than sibling routes so all of them inherit the+ * one auth/backend gate the host route already applies.+ */+export function AppRoot() {+ const { pathname } = useLocation();+ const path = stripBasePath(pathname);++ if (path.startsWith("/settings")) {+ return (+ <Suspense fallback={<LoadingFallback />}>+ <SettingsPage />+ </Suspense>+ );+ }++ if (HAS_DOCS && path.startsWith(DOCS_PATH)) {+ return (+ <Suspense fallback={<LoadingFallback />}>+ <DocsPage />+ </Suspense>+ );+ }++ return <HomePage />;+}diff --git a/frontend/editor/src/core/components/onboarding/adminStepsConfig.ts b/frontend/editor/src/core/components/onboarding/adminStepsConfig.tsindex cff95cb63c..b128568270 100644--- a/frontend/editor/src/core/components/onboarding/adminStepsConfig.ts+++ b/frontend/editor/src/core/components/onboarding/adminStepsConfig.ts@@ -76,16 +76,14 @@ const NAV = {],adminGeneral: ['[data-tour="admin-adminGeneral-nav"]',- '[data-tour="admin-adminFeatures-nav"]',- '[data-tour="admin-adminEndpoints-nav"]','[data-tour="settings-content-area"]',],- adminDatabase: [- '[data-tour="admin-adminDatabase-nav"]',+ adminAdvanced: [+ '[data-tour="admin-adminAdvanced-nav"]','[data-tour="settings-content-area"]',],- adminConnections: [- '[data-tour="admin-adminConnections-nav"]',+ adminSecurity: [+ '[data-tour="admin-adminSecurity-nav"]','[data-tour="settings-content-area"]',],adminTools: [@@ -148,25 +146,25 @@ const ADMIN_STEP_SPECS: AdminStepSpec[] = [},{step: AdminTourStep.DATABASE_SECTION,- selector: '[data-tour="admin-adminDatabase-nav"]',+ selector: '[data-tour="admin-adminAdvanced-nav"]',contentKey: "adminOnboarding.databaseSection",contentDefault:"For advanced production environments, we have settings to allow <strong>external database hookups</strong> so you can integrate with your existing infrastructure.",position: "right",- section: "adminDatabase",- glow: [...NAV.adminDatabase],- highlightedSelectors: [...NAV.adminDatabase],+ section: "adminAdvanced",+ glow: [...NAV.adminAdvanced],+ highlightedSelectors: [...NAV.adminAdvanced],},{step: AdminTourStep.CONNECTIONS_SECTION,- selector: '[data-tour="admin-adminConnections-nav"]',+ selector: '[data-tour="admin-adminSecurity-nav"]',contentKey: "adminOnboarding.connectionsSection",contentDefault:"The <strong>Connections</strong> section supports various login methods including custom SSO and SAML providers like Google and GitHub, plus email integrations for notifications and communications.",position: "right",- section: "adminConnections",- glow: [...NAV.adminConnections],- highlightedSelectors: [...NAV.adminConnections],+ section: "adminSecurity",+ glow: [...NAV.adminSecurity],+ highlightedSelectors: [...NAV.adminSecurity],scrollToAfter: "adminAudit",},{@@ -182,12 +180,12 @@ const ADMIN_STEP_SPECS: AdminStepSpec[] = [},{step: AdminTourStep.WRAP_UP,- selector: '[data-tour="admin-help-nav"]',+ selector: '[data-tour="admin-about-nav"]',contentKey: "adminOnboarding.wrapUp",contentDefault:- "That's the admin tour! You've seen the enterprise features that make Stirling PDF a powerful, customisable solution for organisations. You can replay it anytime — just open <strong>Settings</strong> and find it here in the <strong>Tours</strong> section under Help.",+ "That's the admin tour! You've seen the enterprise features that make Stirling PDF a powerful, customisable solution for organisations. You can replay it anytime — just open <strong>Settings</strong> and find it here under <strong>About</strong>.",position: "right",- section: "help",+ section: "about",waitForSelectorOnEnter: true,},];diff --git a/frontend/editor/src/core/components/settings/mergeSettingsGroups.ts b/frontend/editor/src/core/components/settings/mergeSettingsGroups.tsnew file mode 100644index 0000000000..c5b2109312--- /dev/null+++ b/frontend/editor/src/core/components/settings/mergeSettingsGroups.ts@@ -0,0 +1,40 @@+import type { ConfigNavSection } from "@app/components/shared/config/types";++/**+ * Folds another layer's settings groups into the build's own. Groups with a+ * matching `id` merge - the incoming items lead by default, since they usually+ * replace the ones listed in `superseded` and should hold their place, unless+ * the group asks to `append` - and unmatched groups slot in after Workspace (or+ * after the first group when there is none), so the order stays readable+ * whichever layer contributed what.+ */+export function mergeSettingsGroups(+ base: ConfigNavSection[],+ extra: ConfigNavSection[],+ superseded: readonly string[],+): ConfigNavSection[] {+ const drop = new Set<string>(superseded);+ const merged = base+ .map((section) => ({+ ...section,+ items: section.items.filter((item) => !drop.has(item.key)),+ }))+ .filter((section) => section.items.length > 0);++ for (const group of extra) {+ const target = group.id+ ? merged.find((section) => section.id === group.id)+ : undefined;+ if (target) {+ target.items =+ group.mergeAt === "append"+ ? [...target.items, ...group.items]+ : [...group.items, ...target.items];+ continue;+ }+ const workspace = merged.findIndex((section) => section.id === "workspace");+ const at = workspace >= 0 ? workspace + 1 : Math.min(1, merged.length);+ merged.splice(at, 0, group);+ }+ return merged;+}diff --git a/frontend/editor/src/core/components/settings/settingsNavTypes.ts b/frontend/editor/src/core/components/settings/settingsNavTypes.tsnew file mode 100644index 0000000000..114ce5756b--- /dev/null+++ b/frontend/editor/src/core/components/settings/settingsNavTypes.ts@@ -0,0 +1,28 @@+import type { ReactNode } from "react";+import type {+ ConfigNavSection,+ NavKey,+} from "@app/components/shared/config/types";++/**+ * What the settings page needs to draw itself. Lives apart from the hook that+ * builds it so a flavor's own builder can be typed against this without pulling+ * another flavor's section components into its build graph.+ */+export interface SettingsNav {+ sections: ConfigNavSection[];+ /** Flavor-owned overlays the page mounts (SaaS puts its sign-out confirm here). */+ overlay?: ReactNode;+ /**+ * Old section key -> the section that replaced it, for builds where one+ * surface supersedes another. Bookmarks and search results for the retired+ * key land on its replacement instead of an empty page.+ */+ aliases?: Partial<Record<string, NavKey>>;+ /**+ * Sections are still arriving. Set while a permission lookup is in flight,+ * so a deep link to a section that has not been added yet waits instead of+ * being redirected away as unknown.+ */+ pending?: boolean;+}diff --git a/frontend/editor/src/core/components/settings/useActiveHeading.ts b/frontend/editor/src/core/components/settings/useActiveHeading.tsnew file mode 100644index 0000000000..d551a1a5ce--- /dev/null+++ b/frontend/editor/src/core/components/settings/useActiveHeading.ts@@ -0,0 +1,101 @@+import { useCallback, useEffect, useRef, useState } from "react";+import type { SectionHeading } from "@app/components/settings/useSectionHeadings";++/** Where in the scroll container a card counts as the one being read. */+const ACTIVE_LINE = 120;+/** Long enough for a smooth scroll to land before the spy takes over again. */+const SETTLE_MS = 900;++function writeHash(id: string): void {+ if (window.location.hash.slice(1) === id) return;+ window.history.replaceState(+ window.history.state,+ "",+ `${window.location.pathname}${window.location.search}#${id}`,+ );+}++/**+ * Which card the reader is on, mirrored into the URL as `#slug`.+ *+ * Returns a `focus` for jumping to one. The hash is written with replaceState,+ * not the router, so scrolling cannot feed the deep-link effect that scrolls.+ */+export function useActiveHeading(+ container: HTMLElement | null,+ headings: SectionHeading[],+): { active: string | null; focus: (id: string) => void } {+ const [active, setActive] = useState<string | null>(null);+ // A click scrolls smoothly; without this the spy reads the frames on the way+ // and overwrites the slug the reader just asked for.+ const settleUntil = useRef(0);++ const focus = useCallback((id: string) => {+ const el = document.getElementById(id);+ if (!el) return;+ // Unfold first, or there is nothing to scroll to: the anchor is either a+ // folded card's own toggle, or a control inside its hidden panel.+ if (el.getAttribute("aria-expanded") === "false") {+ el.click();+ } else {+ el.closest(".settings-card__panel[hidden]")+ ?.parentElement?.querySelector<HTMLButtonElement>(+ ".settings-card__toggle",+ )+ ?.click();+ }+ settleUntil.current = Date.now() + SETTLE_MS;+ setActive(id);+ writeHash(id);+ el.scrollIntoView({ behavior: "smooth", block: "start" });+ el.classList.add("settings-focus-target");+ window.setTimeout(() => el.classList.remove("settings-focus-target"), 1800);+ }, []);++ useEffect(() => {+ if (!container || headings.length === 0) {+ setActive(null);+ return;+ }++ let frame = 0;+ const read = () => {+ frame = 0;+ if (Date.now() < settleUntil.current) return;+ const line = container.getBoundingClientRect().top + ACTIVE_LINE;+ let current = headings[0]?.id ?? null;+ for (const h of headings) {+ const el = document.getElementById(h.id);+ if (el && el.getBoundingClientRect().top <= line) current = h.id;+ }+ // At the very bottom the last card wins, or it can never become active.+ // Only when there is something to scroll: a section shorter than the+ // viewport is permanently "at the bottom", which made every one of them+ // open deep-linked to its last card.+ const scrollable = container.scrollHeight > container.clientHeight + 4;+ if (+ scrollable &&+ container.scrollTop + container.clientHeight >=+ container.scrollHeight - 4+ ) {+ current = headings[headings.length - 1]?.id ?? current;+ }+ setActive(current);+ if (current) writeHash(current);+ };++ const onScroll = () => {+ if (frame) return;+ frame = window.requestAnimationFrame(read);+ };++ read();+ container.addEventListener("scroll", onScroll, { passive: true });+ return () => {+ container.removeEventListener("scroll", onScroll);+ if (frame) window.cancelAnimationFrame(frame);+ };+ }, [container, headings]);++ return { active, focus };+}diff --git a/frontend/editor/src/core/components/settings/useSectionHeadings.ts b/frontend/editor/src/core/components/settings/useSectionHeadings.tsnew file mode 100644index 0000000000..34121837ac--- /dev/null+++ b/frontend/editor/src/core/components/settings/useSectionHeadings.ts@@ -0,0 +1,55 @@+import { useEffect, useState } from "react";++export interface SectionHeading {+ id: string;+ label: string;+}++/**+ * The cards the open settings section rendered, read back off the page.+ *+ * Taken from the DOM rather than a hand-kept list so it cannot drift: a page+ * that adds, removes or conditionally hides a card is reflected without anyone+ * remembering to update a registry. Sections load asynchronously, so this+ * re-reads on mutation until the page settles.+ */+export function useSectionHeadings(+ activeKey: string | undefined,+ container: HTMLElement | null,+): SectionHeading[] {+ const [headings, setHeadings] = useState<SectionHeading[]>([]);++ useEffect(() => {+ if (!container || !activeKey) {+ setHeadings([]);+ return;+ }+ const read = () => {+ // SettingsCard carries the id on its toggle button; pages that still+ // draw their own heading carry it on the h2.+ const found = [+ ...container.querySelectorAll<HTMLElement>(+ ".settings-card__toggle[id], h2[id]",+ ),+ ].map((el) => ({+ id: el.id,+ label:+ el.querySelector(".settings-card__title")?.textContent?.trim() ??+ el.textContent?.trim() ??+ el.id,+ }));+ setHeadings((prev) =>+ prev.length === found.length &&+ prev.every((p, i) => p.id === found[i].id && p.label === found[i].label)+ ? prev+ : found,+ );+ };+ read();+ const observer = new MutationObserver(read);+ observer.observe(container, { childList: true, subtree: true });+ return () => observer.disconnect();+ }, [activeKey, container]);++ return headings;+}diff --git a/frontend/editor/src/core/components/settings/useSettingsNav.tsx b/frontend/editor/src/core/components/settings/useSettingsNav.tsxnew file mode 100644index 0000000000..d460baa836--- /dev/null+++ b/frontend/editor/src/core/components/settings/useSettingsNav.tsx@@ -0,0 +1,26 @@+import { useConfigNavSections } from "@app/components/shared/config/configNavSections";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import type { SettingsNav } from "@app/components/settings/settingsNavTypes";+import { BASE_SECTION_ALIASES } from "@app/data/settingsAliases";++export type { SettingsNav };++/**+ * The settings sections this build ships, already gated by the signed-in+ * user's config. A per-flavor seam: SaaS shadows it to build from its own+ * (non-hook) nav factory, so the page itself stays flavor-agnostic.+ *+ * @param onLeave closes settings — the Help tours need the page out of the way+ * before they can run.+ */+export function useSettingsNav(onLeave: () => void): SettingsNav {+ const { config } = useAppConfig();+ const sections = useConfigNavSections(+ config?.isAdmin ?? false,+ config?.runningEE ?? false,+ config?.enableLogin ?? false,+ onLeave,+ config?.showSettingsWhenNoLogin ?? true,+ );+ return { sections, aliases: BASE_SECTION_ALIASES };+}diff --git a/frontend/editor/src/core/components/shared/AppConfigModal.tsx b/frontend/editor/src/core/components/shared/AppConfigModal.tsxdeleted file mode 100644index c5adef038d..0000000000--- a/frontend/editor/src/core/components/shared/AppConfigModal.tsx+++ /dev/null@@ -1,514 +0,0 @@-import React, {- useMemo,- useState,- useEffect,- useCallback,- useRef,-} from "react";-import { Badge, Modal, Text, Tooltip, Group } from "@mantine/core";-import { ActionIcon } from "@app/ui/ActionIcon";-import { SettingsMobileBackButton } from "@app/components/shared/config/SettingsMobileBackButton";-import { SettingsMobileNavHeader } from "@app/components/shared/config/SettingsMobileNavHeader";-import { SettingsNavChevron } from "@app/components/shared/config/SettingsNavChevron";-import { useNavigate, useLocation } from "react-router-dom";-import { useTranslation } from "react-i18next";-import LocalIcon from "@app/components/shared/LocalIcon";-import { useConfigNavSections } from "@app/components/shared/config/configNavSections";-import {- NavKey,- VALID_NAV_KEYS,- type ConfigNavSection,-} from "@app/components/shared/config/types";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import { COOKIE_CONSENT_SCROLL_SHARD } from "@app/hooks/useCookieConsent";-import "@app/components/shared/AppConfigModal.css";-import { useIsMobile } from "@app/hooks/useIsMobile";-import {- Z_INDEX_CONFIG_MODAL,- Z_INDEX_OVER_CONFIG_MODAL,-} from "@app/styles/zIndex";-import { useLicenseAlert } from "@app/hooks/useLicenseAlert";-import {- UnsavedChangesProvider,- useUnsavedChanges,-} from "@app/contexts/UnsavedChangesContext";-import { stripBasePath, withBasePath } from "@app/constants/app";--interface AppConfigModalProps {- opened: boolean;- onClose: () => void;- /**- * Mirror the active section to /settings/<key> URLs (deep links, history- * unwind on close). Hosts mounted away from the editor's /settings route —- * the admin portal — turn this off and the modal keeps its section purely in- * state.- */- urlSync?: boolean;- /** Section to land on when opening. Only honoured when urlSync is off (URL- * deep links win otherwise). */- initialSection?: NavKey | null;- /** Row anchor to focus when opening on a non-URL host. */- initialFocus?: string | null;- /** Host-specific sections appended after the build's registry sections. */- extraSections?: ConfigNavSection[];- /** Registry section keys to drop, for hosts a section can't run in. */- hiddenSectionKeys?: NavKey[];-}--// Extract section from URL path (e.g., /settings/people -> people)-const getSectionFromPath = (pathname: string): NavKey | null => {- const match = pathname.match(/\/settings\/([^/]+)/);- if (match && match[1]) {- const section = match[1] as NavKey;- return VALID_NAV_KEYS.includes(section as NavKey) ? section : null;- }- return null;-};--const AppConfigModalInner: React.FC<AppConfigModalProps> = ({- opened,- onClose,- urlSync = true,- initialSection,- initialFocus,- extraSections,- hiddenSectionKeys,-}) => {- const { t } = useTranslation();- // Initialize from the URL so a deep link (`/settings/people`) lands on the- // right tab without a one-frame "general" flicker.- const [active, setActive] = useState<NavKey>(- () =>- (urlSync ? getSectionFromPath(window.location.pathname) : null) ??- initialSection ??- "general",- );- const isMobile = useIsMobile();- const [mobilePane, setMobilePane] = useState<"nav" | "content">("nav");- const navigate = useNavigate();- const location = useLocation();- const { config } = useAppConfig();- const licenseAlert = useLicenseAlert();- const { confirmIfDirty } = useUnsavedChanges();- const closeButtonRef = useRef<HTMLButtonElement>(null);-- // Sync active state with URL path. Runs on open, on external URL changes,- // and on the redirect path below - NOT on intra-modal tab clicks, because- // those update the URL via `history.replaceState` directly and never push- // a new React Router location.- useEffect(() => {- if (!urlSync) return;- const section = getSectionFromPath(location.pathname);- if (opened && section) {- setActive(section);- } else if (- opened &&- location.pathname.startsWith("/settings") &&- !section- ) {- // If at /settings without a section, redirect to general- navigate("/settings/general", { replace: true });- }- }, [location.pathname, opened, navigate, urlSync]);-- // Non-URL hosts land the modal on the section they asked for.- useEffect(() => {- if (opened && !urlSync && initialSection) {- setActive(initialSection);- }- }, [opened, urlSync, initialSection]);-- useEffect(() => {- if (opened) {- // Keep search closed initially by moving autofocus away from the searchable Select input.- closeButtonRef.current?.focus();- }- }, [opened]);-- useEffect(() => {- if (!opened) return;- const target = urlSync- ? getSectionFromPath(window.location.pathname)- : initialSection;- setMobilePane(target ? "content" : "nav");- }, [opened, urlSync, initialSection]);-- // Switch tab without forcing every `useLocation()` subscriber (HomePage and- // its FileSidebar/Workbench/RightSidebar/FileManager tree) to re-render.- //- // First entry into /settings/* still goes through React Router so HomePage's- // location-watching effect opens the modal and pushes a real history entry -- // so the back button can close us. Subsequent tab clicks bypass React Router- // and mutate the URL bar via `history.replaceState`. The browser sees the- // URL update (deep-link / refresh still work) but React Router never fires a- // location change, so the layer behind the Mantine overlay never repaints- // and the backdrop-filter blur stops flashing.- const switchSection = useCallback(- (key: NavKey) => {- setActive(key);- if (!urlSync) return;- const alreadyInSettings = stripBasePath(- window.location.pathname,- ).startsWith("/settings");- if (alreadyInSettings) {- window.history.replaceState(- window.history.state,- "",- withBasePath(`/settings/${key}`),- );- } else {- navigate(`/settings/${key}`);- }- },- [navigate, urlSync],- );-- // Deep-link: /settings/{section}?focus={anchor} scrolls to and briefly- // highlights the matching control (used by the global super search to jump- // straight to an individual setting row).- useEffect(() => {- if (!opened) return;- const focus = urlSync- ? new URLSearchParams(location.search).get("focus")- : initialFocus;- if (!focus) return;- let raf = 0;- // Wait for the (possibly just-switched) section to render before scrolling.- const timer = window.setTimeout(() => {- raf = window.requestAnimationFrame(() => {- const el = document.getElementById(focus);- if (!el) return;- el.scrollIntoView({ behavior: "smooth", block: "center" });- el.classList.add("settings-focus-target");- window.setTimeout(- () => el.classList.remove("settings-focus-target"),- 1800,- );- });- }, 150);- return () => {- window.clearTimeout(timer);- if (raf) window.cancelAnimationFrame(raf);- };- }, [opened, active, initialFocus, location.search, urlSync]);-- // Backwards-compat: external `appConfig:navigate` events route through the- // same switchSection path so they get the no-flash treatment too.- useEffect(() => {- const handler = (ev: Event) => {- const detail = (ev as CustomEvent).detail as { key?: NavKey } | undefined;- if (detail?.key) {- switchSection(detail.key);- }- };- window.addEventListener("appConfig:navigate", handler as EventListener);- return () =>- window.removeEventListener(- "appConfig:navigate",- handler as EventListener,- );- }, [switchSection]);-- const colors = useMemo(- () => ({- navBg: "var(--c-bg-raised)",- sectionTitle: "var(--c-text-subtle)",- navItem: "var(--modal-nav-item)",- navItemActive: "var(--c-accent-fg)",- navItemActiveBg: "var(--c-primary-subtle)",- contentBg: "var(--c-surface)",- headerBorder: "var(--c-border-subtle)",- }),- [],- );-- // Get isAdmin and runningEE from app config- const isAdmin = config?.isAdmin ?? false;- const runningEE = config?.runningEE ?? false;- const loginEnabled = config?.enableLogin ?? false;-- /** Resolves false when a dirty-state confirm kept the modal open. */- const handleClose = useCallback(async () => {- const canProceed = await confirmIfDirty();- if (!canProceed) return false;- onClose();- return true;- }, [confirmIfDirty, onClose]);-- // Synchronous wrapper for contexts (e.g. tour buttons) that need () => void- const handleCloseSync = useCallback(() => {- void handleClose();- }, [handleClose]);-- // Cmd/Ctrl+K: hand over to the global super search. The bar's own shortcut- // is inert while a dialog traps focus, so the modal closes itself (through- // the same dirty-check as any other close) and asks the bar to take focus.- // Settings results deep-link straight back into this modal.- useEffect(() => {- if (!opened) return;- const onKey = (e: KeyboardEvent) => {- const combo = (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey;- if (!combo || e.code !== "KeyK") return;- e.preventDefault();- void handleClose().then((closed) => {- if (closed) window.dispatchEvent(new Event("superSearch:focus"));- });- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [opened, handleClose]);-- // Left navigation structure and icons- const registrySections = useConfigNavSections(- isAdmin,- runningEE,- loginEnabled,- handleCloseSync,- config?.showSettingsWhenNoLogin ?? true,- );- const configNavSections = useMemo(() => {- const base = hiddenSectionKeys?.length- ? registrySections- .map((s) => ({- ...s,- items: s.items.filter((i) => !hiddenSectionKeys.includes(i.key)),- }))- .filter((s) => s.items.length > 0)- : registrySections;- return extraSections?.length ? [...base, ...extraSections] : base;- }, [registrySections, extraSections, hiddenSectionKeys]);-- const activeLabel = useMemo(() => {- for (const section of configNavSections) {- const found = section.items.find((i) => i.key === active);- if (found) return found.label;- }- return "";- }, [configNavSections, active]);-- const activeComponent = useMemo(() => {- for (const section of configNavSections) {- const found = section.items.find((i) => i.key === active);- if (found) return found.component;- }- return null;- }, [configNavSections, active]);-- const handleNavigation = useCallback(- async (key: NavKey) => {- const canProceed = await confirmIfDirty();- if (!canProceed) return;- switchSection(key);- setMobilePane("content");- },- [confirmIfDirty, switchSection],- );-- const handleMobileBack = useCallback(async () => {- const canProceed = await confirmIfDirty();- if (!canProceed) return;- setMobilePane("nav");- }, [confirmIfDirty]);-- return (- <Modal- opened={opened}- onClose={handleClose}- title={null}- size={isMobile ? "100%" : 1100}- centered- radius="lg"- withCloseButton={false}- zIndex={Z_INDEX_CONFIG_MODAL}- overlayProps={{ opacity: 0.35, blur: 2 }}- padding={0}- fullScreen={isMobile}- styles={{ content: { overflowY: "hidden", overscrollBehavior: "none" } }}- removeScrollProps={{ shards: [COOKIE_CONSENT_SCROLL_SHARD] }}- >- <div className="modal-container" data-tour="settings-modal">- {/* Left navigation */}- <div- className={`modal-nav ${isMobile ? "mobile" : ""}`}- style={{- background: colors.navBg,- ...(isMobile- ? { display: mobilePane === "nav" ? undefined : "none" }- : { borderRight: `1px solid ${colors.headerBorder}` }),- }}- >- <SettingsMobileNavHeader- show={isMobile}- onClose={handleClose}- background={colors.navBg}- borderColor={colors.headerBorder}- />- <div className="modal-nav-scroll">- {configNavSections.map((section) => (- <div key={section.title} className="modal-nav-section">- <Text- size="xs"- fw={600}- c={colors.sectionTitle}- style={{ textTransform: "uppercase", letterSpacing: 0.4 }}- >- {section.title}- </Text>- <div className="modal-nav-section-items">- {section.items.map((item) => {- const isActive = active === item.key;- const isDisabled = item.disabled ?? false;- const color = isActive- ? colors.navItemActive- : colors.navItem;- const iconSize = 18;- const showPlanWarning =- item.key === "adminPlan" &&- licenseAlert.active &&- licenseAlert.audience === "admin";-- const navItemContent = (- <div- key={item.key}- onClick={() => {- if (!isDisabled) {- handleNavigation(item.key);- }- }}- className={`modal-nav-item ${isActive ? "active" : ""} ${isMobile ? "mobile" : ""}`}- style={{- background: isActive- ? colors.navItemActiveBg- : "transparent",- opacity: isDisabled ? 0.6 : 1,- cursor: isDisabled ? "not-allowed" : "pointer",- }}- data-tour={`admin-${item.key}-nav`}- >- <LocalIcon- icon={item.icon}- width={iconSize}- height={iconSize}- style={{ color, flexShrink: 0 }}- />- <Group- gap={4}- align="center"- wrap="nowrap"- style={{ minWidth: 0, flex: 1 }}- >- <Text- size="sm"- fw={500}- truncate- style={{ color, minWidth: 0, flex: 1 }}- title={item.label}- >- {item.label}- </Text>- {item.badge && (- <Badge- size="xs"- variant="light"- color={item.badgeColor ?? "orange"}- className="modal-nav-item-badge"- style={{ flexShrink: 0 }}- >- {item.badge}- </Badge>- )}- {showPlanWarning && (- <LocalIcon- icon="warning-rounded"- width={14}- height={14}- style={{- color: "var(--mantine-color-orange-7)",- }}- />- )}- </Group>- <SettingsNavChevron show={isMobile} />- </div>- );-- return isDisabled && item.disabledTooltip ? (- <Tooltip- key={item.key}- label={item.disabledTooltip}- position="right"- withArrow- zIndex={Z_INDEX_OVER_CONFIG_MODAL}- >- {navItemContent}- </Tooltip>- ) : (- <React.Fragment key={item.key}>- {navItemContent}- </React.Fragment>- );- })}- </div>- </div>- ))}- </div>- </div>-- {/* Right content */}- <div- className="modal-content"- data-tour="settings-content-area"- style={- isMobile && mobilePane !== "content"- ? { display: "none" }- : undefined- }- >- <div className="modal-content-scroll">- {/* Sticky header with section title and small close button */}- <div- className="modal-header"- style={{- background: colors.contentBg,- borderBottom: `1px solid ${colors.headerBorder}`,- }}- >- <Group gap="xs" wrap="nowrap" style={{ minWidth: 0 }}>- <SettingsMobileBackButton- show={isMobile}- onClick={() => void handleMobileBack()}- />- <Text fw={700} size="lg" truncate>- {activeLabel}- </Text>- </Group>- <Group gap="xs" wrap="nowrap">- <ActionIcon- ref={closeButtonRef}- variant="tertiary"- onClick={handleClose}- aria-label={t("settings.close", "Close")}- data-autofocus- >- <LocalIcon icon="close-rounded" width={18} height={18} />- </ActionIcon>- </Group>- </div>- <div className="modal-body">{activeComponent}</div>- </div>- </div>- </div>- </Modal>- );-};--// Wrapper component that provides the UnsavedChangesContext-const AppConfigModal: React.FC<AppConfigModalProps> = (props) => {- return (- <UnsavedChangesProvider>- <AppConfigModalInner {...props} />- </UnsavedChangesProvider>- );-};--export default AppConfigModal;diff --git a/frontend/editor/src/core/components/shared/AppConfigModalLazy.tsx b/frontend/editor/src/core/components/shared/AppConfigModalLazy.tsxdeleted file mode 100644index 572e18bf88..0000000000--- a/frontend/editor/src/core/components/shared/AppConfigModalLazy.tsx+++ /dev/null@@ -1,59 +0,0 @@-import { Suspense, lazy, useEffect, useState } from "react";-import type {- ConfigNavSection,- NavKey,-} from "@app/components/shared/config/types";--// AppConfigModal pulls in the entire settings UI tree (admin sections,-// account, supabase auth flows, etc.). We defer loading until the user first-// opens the modal, then keep it mounted so the close animation runs.-const AppConfigModal = lazy(- () => import("@app/components/shared/AppConfigModal"),-);--interface AppConfigModalLazyProps {- opened: boolean;- onClose: () => void;- /** See AppConfigModal — off for hosts outside the /settings route. */- urlSync?: boolean;- /** Section to land on when opening (non-URL hosts). */- initialSection?: NavKey | null;- /** Row anchor to highlight when opening (non-URL hosts). */- initialFocus?: string | null;- /** Host-specific sections appended after the build's registry sections. */- extraSections?: ConfigNavSection[];- /** Registry section keys to drop, for hosts a section can't run in. */- hiddenSectionKeys?: NavKey[];-}--export default function AppConfigModalLazy({- opened,- onClose,- urlSync,- initialSection,- initialFocus,- extraSections,- hiddenSectionKeys,-}: AppConfigModalLazyProps) {- const [shouldMount, setShouldMount] = useState(false);-- useEffect(() => {- if (opened) setShouldMount(true);- }, [opened]);-- return (- <Suspense fallback={null}>- {shouldMount && (- <AppConfigModal- opened={opened}- onClose={onClose}- urlSync={urlSync}- initialSection={initialSection}- initialFocus={initialFocus}- extraSections={extraSections}- hiddenSectionKeys={hiddenSectionKeys}- />- )}- </Suspense>- );-}diff --git a/frontend/editor/src/core/components/shared/EditableSecretField.tsx b/frontend/editor/src/core/components/shared/EditableSecretField.tsxindex cce50f90a0..a340b2e554 100644--- a/frontend/editor/src/core/components/shared/EditableSecretField.tsx+++ b/frontend/editor/src/core/components/shared/EditableSecretField.tsx@@ -2,6 +2,7 @@ import { useId, useState, useRef, useEffect } from "react";import { PasswordInput, Group, Tooltip, TextInput } from "@mantine/core";import { useTranslation } from "react-i18next";import { ActionIcon } from "@app/ui/ActionIcon";+import { InfoTooltip } from "@app/ui/InfoTooltip";import LocalIcon from "@app/components/shared/LocalIcon";interface EditableSecretFieldProps {@@ -66,29 +67,18 @@ export default function EditableSecretField({return (<div>- {label && (- <label- htmlFor={fieldId}- style={{- display: "block",- marginBottom: 4,- fontWeight: 500,- fontSize: "0.875rem",- }}- >- {label}- </label>- )}- {description && (- <p- style={{- margin: "4px 0 12px 0",- fontSize: "0.75rem",- color: "var(--c-text-muted)",- }}- >- {description}- </p>+ {(label || description) && (+ <Group gap={4} mb={4} wrap="nowrap">+ {label && (+ <label+ htmlFor={fieldId}+ style={{ fontWeight: 500, fontSize: "0.875rem" }}+ >+ {label}+ </label>+ )}+ {description && <InfoTooltip label={description} />}+ </Group>)}{isMasked && !isEditing ? (diff --git a/frontend/editor/src/core/components/shared/config/SettingsCard.css b/frontend/editor/src/core/components/shared/config/SettingsCard.cssnew file mode 100644index 0000000000..b6736b0e67--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsCard.css@@ -0,0 +1,66 @@+.settings-card {+ display: flex;+ flex-direction: column;+ gap: var(--space-2, 0.5rem);+}++.settings-card__heading {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ margin: 0;+}++.settings-card__toggle {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ /* Only as wide as its text, so the (i) and badge sit next to the title+ rather than being pushed to the far edge. */+ width: auto;+ padding: 0.25rem 0;+ border: 0;+ background: none;+ color: var(--c-text);+ font-size: 0.9375rem;+ font-weight: var(--font-weight-semibold, 600);+ text-align: start;+ cursor: pointer;+ /* Permanent, not just during the focus pulse: an anchored jump would land+ the heading under the sticky search bar otherwise. */+ scroll-margin-top: 1rem;+}++.settings-card__toggle:focus-visible {+ outline: 0.125rem solid var(--c-primary);+ outline-offset: 0.125rem;+ border-radius: var(--radius-sm, 4px);+}++.settings-card__chevron {+ flex-shrink: 0;+ color: var(--c-text-subtle);+ transition: transform var(--motion-fast, 120ms);+}++.settings-card__toggle[aria-expanded="false"] .settings-card__chevron {+ transform: rotate(-90deg);+}++.settings-card__panel {+ display: flex;+ flex-direction: column;+ gap: var(--space-3, 0.75rem);+}++/* `display` on the rule above outranks the UA's [hidden] rule, so a collapsed+ card would keep showing its contents without this. */+.settings-card__panel[hidden] {+ display: none;+}++@media (prefers-reduced-motion: reduce) {+ .settings-card__chevron {+ transition: none;+ }+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsCard.tsx b/frontend/editor/src/core/components/shared/config/SettingsCard.tsxnew file mode 100644index 0000000000..d44eae778c--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsCard.tsx@@ -0,0 +1,71 @@+import { useState, type ReactNode } from "react";+import LocalIcon from "@app/components/shared/LocalIcon";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import "@app/components/shared/config/SettingsCard.css";++export interface SettingsCardProps {+ /** The card's `#slug`, and the id the nav's card list jumps to. */+ id: string;+ title: string;+ /** Shown behind an (i) rather than as a standing line, so the page stays scannable. */+ description?: ReactNode;+ /** A tier or maturity marker the retired nav row used to carry. */+ badge?: ReactNode;+ /** Long or rarely-touched cards start shut; the rest open. */+ defaultCollapsed?: boolean;+ /** Hold off mounting children until first opened, for expensive content. */+ lazy?: boolean;+ children: ReactNode;+}++/**+ * One card on a settings page: an anchored heading you can fold away.+ *+ * The heading is a real button rather than a styled div so the whole row is+ * keyboard-reachable, and the id sits on the button so an anchor jump lands on+ * the control that opens the card rather than on hidden content.+ */+export function SettingsCard({+ id,+ title,+ description,+ badge,+ defaultCollapsed = false,+ lazy = false,+ children,+}: SettingsCardProps) {+ const [open, setOpen] = useState(!defaultCollapsed);+ const [everOpened, setEverOpened] = useState(!defaultCollapsed);++ return (+ <section className="settings-card" data-open={open || undefined}>+ <h2 className="settings-card__heading">+ <button+ type="button"+ id={id}+ className="settings-card__toggle"+ aria-expanded={open}+ aria-controls={`${id}-panel`}+ onClick={() => {+ setOpen((wasOpen) => !wasOpen);+ setEverOpened(true);+ }}+ >+ <LocalIcon+ icon="expand-more-rounded"+ width={16}+ height={16}+ className="settings-card__chevron"+ />+ <span className="settings-card__title">{title}</span>+ </button>+ {badge}+ {/* Outside the toggle: InfoTooltip is a button, and buttons do not nest. */}+ {description && <InfoTooltip label={description} position="right" />}+ </h2>+ <div id={`${id}-panel`} className="settings-card__panel" hidden={!open}>+ {lazy && !everOpened ? null : children}+ </div>+ </section>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsEmptyState.css b/frontend/editor/src/core/components/shared/config/SettingsEmptyState.cssnew file mode 100644index 0000000000..ab0159f0fb--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsEmptyState.css@@ -0,0 +1,30 @@+.settings-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.35rem;+ padding: 2rem 1rem;+ text-align: center;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-md, 8px);+ background: var(--c-surface);+}++.settings-empty__icon {+ color: var(--c-text-subtle);+ opacity: 0.6;+}++.settings-empty__title {+ margin: 0;+ font-size: 0.9rem;+ font-weight: 600;+ color: var(--c-text-muted);+}++.settings-empty__body {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--c-text-subtle);+ max-width: 32rem;+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsEmptyState.test.tsx b/frontend/editor/src/core/components/shared/config/SettingsEmptyState.test.tsxnew file mode 100644index 0000000000..0b5c1fac99--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsEmptyState.test.tsx@@ -0,0 +1,18 @@+import { describe, expect, test } from "vitest";+import { render, screen } from "@testing-library/react";+import { SettingsEmptyState } from "@app/components/shared/config/SettingsEmptyState";++describe("SettingsEmptyState", () => {+ test("states the situation without claiming anything is wrong", () => {+ render(+ <SettingsEmptyState title="No usage yet">+ Endpoint activity appears here once people start running tools.+ </SettingsEmptyState>,+ );++ expect(screen.getByText("No usage yet")).toBeTruthy();+ // Not an alert: an empty audit log on a fresh install is the normal state.+ expect(document.querySelector('[role="alert"]')).toBeNull();+ expect(document.querySelector(".settings-empty")).toBeTruthy();+ });+});diff --git a/frontend/editor/src/core/components/shared/config/SettingsEmptyState.tsx b/frontend/editor/src/core/components/shared/config/SettingsEmptyState.tsxnew file mode 100644index 0000000000..cd7e4bb814--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsEmptyState.tsx@@ -0,0 +1,33 @@+import type { ReactNode } from "react";+import LocalIcon from "@app/components/shared/LocalIcon";+import "@app/components/shared/config/SettingsEmptyState.css";++export interface SettingsEmptyStateProps {+ title: ReactNode;+ children: ReactNode;+ /** Defaults to an outline box; pass one that suits the section. */+ icon?: string;+}++/**+ * Nothing to show yet. Deliberately not a warning: an empty audit log or an+ * unused endpoint list is the normal state of a fresh install.+ */+export function SettingsEmptyState({+ title,+ children,+ icon = "inbox",+}: SettingsEmptyStateProps) {+ return (+ <div className="settings-empty">+ <LocalIcon+ icon={icon}+ width={28}+ height={28}+ className="settings-empty__icon"+ />+ <p className="settings-empty__title">{title}</p>+ <p className="settings-empty__body">{children}</p>+ </div>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsFieldLabel.css b/frontend/editor/src/core/components/shared/config/SettingsFieldLabel.cssnew file mode 100644index 0000000000..e5e80984e8--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsFieldLabel.css@@ -0,0 +1,5 @@+.settings-field-label {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsFieldLabel.tsx b/frontend/editor/src/core/components/shared/config/SettingsFieldLabel.tsxnew file mode 100644index 0000000000..48629cbeef--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsFieldLabel.tsx@@ -0,0 +1,25 @@+import type { ReactNode } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import "@app/components/shared/config/SettingsFieldLabel.css";++export interface SettingsFieldLabelProps {+ /** Guidance for the field, revealed on hover or focus. */+ info: ReactNode;+ children: ReactNode;+}++/**+ * A settings field's label with its help text behind an (i), so a page of+ * fields stays scannable instead of a sentence deep per control.+ */+export function SettingsFieldLabel({+ info,+ children,+}: SettingsFieldLabelProps) {+ return (+ <span className="settings-field-label">+ {children}+ <InfoTooltip label={info} />+ </span>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsMobileNavHeader.stories.tsx b/frontend/editor/src/core/components/shared/config/SettingsMobileNavHeader.stories.tsxdeleted file mode 100644index a4ade4801b..0000000000--- a/frontend/editor/src/core/components/shared/config/SettingsMobileNavHeader.stories.tsx+++ /dev/null@@ -1,23 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { SettingsMobileNavHeader } from "@app/components/shared/config/SettingsMobileNavHeader";-import "@app/components/shared/AppConfigModal.css";--const meta = {- title: "Shared/Config/SettingsMobileNavHeader",- component: SettingsMobileNavHeader,- parameters: { layout: "padded" },- args: {- show: true,- onClose: () => {},- background: "var(--c-bg-raised)",- borderColor: "var(--c-border-subtle)",- },-} satisfies Meta<typeof SettingsMobileNavHeader>;-export default meta;-type Story = StoryObj<typeof meta>;--export const Default: Story = {};--export const Hidden: Story = {- args: { show: false },-};diff --git a/frontend/editor/src/core/components/shared/config/SettingsMobileNavHeader.tsx b/frontend/editor/src/core/components/shared/config/SettingsMobileNavHeader.tsxdeleted file mode 100644index bfeea13861..0000000000--- a/frontend/editor/src/core/components/shared/config/SettingsMobileNavHeader.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { Text } from "@mantine/core";-import { useTranslation } from "react-i18next";-import { ActionIcon } from "@app/ui/ActionIcon";-import LocalIcon from "@app/components/shared/LocalIcon";--interface SettingsMobileNavHeaderProps {- /** Mobile shows nav and content as separate panes, so the nav needs its own header. */- show: boolean;- onClose: () => void;- background: string;- borderColor: string;-}--/** Header for the settings nav pane: the modal title plus a close button. */-export function SettingsMobileNavHeader({- show,- onClose,- background,- borderColor,-}: SettingsMobileNavHeaderProps) {- const { t } = useTranslation();-- if (!show) return null;-- return (- <div- className="modal-header modal-nav-header"- style={{ background, borderBottom: `1px solid ${borderColor}` }}- >- <Text fw={700} size="lg">- {t("settings.title", "Settings")}- </Text>- <ActionIcon- variant="tertiary"- onClick={onClose}- aria-label={t("settings.close", "Close")}- >- <LocalIcon icon="close-rounded" width={18} height={18} />- </ActionIcon>- </div>- );-}--export default SettingsMobileNavHeader;diff --git a/frontend/editor/src/core/components/shared/config/SettingsNavChevron.stories.tsx b/frontend/editor/src/core/components/shared/config/SettingsNavChevron.stories.tsxindex f9ede21f49..15ffce6a3d 100644--- a/frontend/editor/src/core/components/shared/config/SettingsNavChevron.stories.tsx+++ b/frontend/editor/src/core/components/shared/config/SettingsNavChevron.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { SettingsNavChevron } from "@app/components/shared/config/SettingsNavChevron";-import "@app/components/shared/AppConfigModal.css";+import "@app/components/shared/config/settingsSections.css";const meta = {title: "Shared/Config/SettingsNavChevron",diff --git a/frontend/editor/src/core/components/shared/config/SettingsToggleRow.css b/frontend/editor/src/core/components/shared/config/SettingsToggleRow.cssnew file mode 100644index 0000000000..da1fe65b77--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsToggleRow.css@@ -0,0 +1,44 @@+.settings-toggle {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.settings-toggle__row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+}++.settings-toggle__label {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ min-width: 0;+ font-size: 0.875rem;+ font-weight: 500;+ color: var(--c-text);+}++/* Long labels wrap instead of shoving the switch off the row. */+.settings-toggle__title {+ min-width: 0;+}++.settings-toggle__control {+ flex-shrink: 0;+}++.settings-toggle__note {+ margin: 0;+ font-size: 0.75rem;+ color: var(--c-text-subtle);+}++/* Only on once the switch is on, so the cost is stated when it applies. */+.settings-toggle__warning {+ margin: 0;+ font-size: 0.75rem;+ color: var(--color-amber-dark, var(--c-text-subtle));+}diff --git a/frontend/editor/src/core/components/shared/config/SettingsToggleRow.tsx b/frontend/editor/src/core/components/shared/config/SettingsToggleRow.tsxnew file mode 100644index 0000000000..4b0bd967f4--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/SettingsToggleRow.tsx@@ -0,0 +1,67 @@+import type { ReactNode } from "react";+import { Switch, type SwitchProps } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import "@app/components/shared/config/SettingsToggleRow.css";++export interface SettingsToggleRowProps {+ label: ReactNode;+ /** Help text, shown behind the (i) that follows the label. */+ info?: ReactNode;+ /** Saved, but the server applies it on restart. */+ pending?: boolean;+ checked: boolean;+ onChange: (checked: boolean) => void;+ disabled?: boolean;+ /** The read-only cursor treatment from useLoginRequired. */+ styles?: SwitchProps["styles"];+ /** An unmet prerequisite, shown under the label. */+ note?: ReactNode;+ /** A consequence of switching this on, shown only once it is on. */+ warnWhenOn?: ReactNode;+ /** Controls this toggle reveals when it is on. */+ children?: ReactNode;+}++/**+ * One on/off setting: label left, switch hard right.+ *+ * Every settings toggle routes through this, so the side, label weight and+ * badge order cannot drift again. Row spacing is the parent Stack's job.+ */+export function SettingsToggleRow({+ label,+ info,+ pending = false,+ checked,+ onChange,+ disabled = false,+ styles,+ note,+ warnWhenOn,+ children,+}: SettingsToggleRowProps) {+ return (+ <div className="settings-toggle">+ <div className="settings-toggle__row">+ <span className="settings-toggle__label">+ <span className="settings-toggle__title">{label}</span>+ <PendingBadge show={pending} />+ {info && <InfoTooltip label={info} />}+ </span>+ <Switch+ className="settings-toggle__control"+ checked={checked}+ onChange={(event) => onChange(event.currentTarget.checked)}+ disabled={disabled}+ styles={styles}+ />+ </div>+ {note && <p className="settings-toggle__note">{note}</p>}+ {warnWhenOn && checked && (+ <p className="settings-toggle__warning">{warnWhenOn}</p>+ )}+ {children}+ </div>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/TierBadge.tsx b/frontend/editor/src/core/components/shared/config/TierBadge.tsxnew file mode 100644index 0000000000..a5ce1944b4--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/TierBadge.tsx@@ -0,0 +1,33 @@+import { Badge } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { useNavigate } from "react-router-dom";++export interface TierBadgeProps {+ /** The licence tier this card needs. */+ tier: "PRO" | "ENTERPRISE";+}++/**+ * The licence marker on a settings card's heading. A span, because it sits+ * inside the h2 - on its own row inside the card it cost a line each.+ */+export function TierBadge({ tier }: TierBadgeProps) {+ const { t } = useTranslation();+ const navigate = useNavigate();++ return (+ <Badge+ component="span"+ color="grape"+ size="sm"+ style={{ cursor: "pointer" }}+ onClick={() => navigate("/settings/adminPlan")}+ title={t(+ "admin.settings.badge.clickToUpgrade",+ "Click to view plan details",+ )}+ >+ {tier}+ </Badge>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configNavSections.tsx b/frontend/editor/src/core/components/shared/config/configNavSections.tsxindex 1fd16de4d4..226edab12d 100644--- a/frontend/editor/src/core/components/shared/config/configNavSections.tsx+++ b/frontend/editor/src/core/components/shared/config/configNavSections.tsx@@ -1,13 +1,10 @@import React from "react";import { useTranslation } from "react-i18next";-import HotkeysSection from "@app/components/shared/config/configSections/HotkeysSection";+import type { TFunction } from "i18next";+import PreferencesSection from "@app/components/shared/config/configSections/preferences/PreferencesSection";import GeneralSection from "@app/components/shared/config/configSections/GeneralSection";-import HelpSection from "@app/components/shared/config/configSections/HelpSection";-import LegalSection from "@app/components/shared/config/configSections/LegalSection";-import {- BackendThirdPartyLicensesSection,- FrontendThirdPartyLicensesSection,-} from "@app/components/shared/config/configSections/ThirdPartyLicensesSection";+import HotkeysSection from "@app/components/shared/config/configSections/HotkeysSection";+import AboutSection from "@app/components/shared/config/configSections/AboutSection";import type {ConfigNavItem,ConfigNavSection,@@ -38,91 +35,74 @@ export const useConfigNavSections = (const sections: ConfigNavSection[] = [{+ id: "preferences",title: t("settings.preferences.title", "Preferences"),items: [{key: "general",label: t("settings.general.title", "General"),- icon: "settings-rounded",- component: <GeneralSection hideTitle />,- },- {- key: "hotkeys",- label: t("settings.hotkeys.title", "Keyboard Shortcuts"),- icon: "keyboard-rounded",- component: <HotkeysSection />,+ description: t(+ "settings.preferences.description",+ "How the editor looks and behaves for you, and your account.",+ ),+ icon: "tune-rounded",+ component: <PreferencesSection />,},],},+ // Reference material: read once and rarely revisited, so it is one page+ // rather than four rows you have to open in turn.{- title: t("settings.help.title", "Help"),+ id: "about",+ title: t("settings.about.title", "About"),items: [{- key: "help",- label: t("settings.help.label", "Tours"),+ key: "about",+ label: t("settings.about.title", "About"),+ description: t(+ "settings.about.description",+ "Tours, legal documents and the licences of everything bundled with this build.",+ ),icon: "help-rounded",component: (- <HelpSection isAdmin={_isAdmin} onRequestClose={onRequestClose} />+ <AboutSection isAdmin={_isAdmin} onRequestClose={onRequestClose} />),},],},- {- title: t("settings.legal.title", "Legal"),- items: [- {- key: "legal",- label: t("settings.legal.label", "Legal"),- icon: "gavel-rounded",- component: <LegalSection />,- },- {- key: "backendThirdPartyLicenses",- label: t("settings.licenses.backendLabel", "Backend Licenses"),- icon: "article-rounded",- component: <BackendThirdPartyLicensesSection />,- },- {- key: "frontendThirdPartyLicenses",- label: t("settings.licenses.frontendLabel", "Frontend Licenses"),- icon: "code-rounded",- component: <FrontendThirdPartyLicensesSection />,- },- ],- },];return sections;};-// Deprecated: Use useConfigNavSections hook instead+/**+ * The editor's own preference sections, for builders that are plain functions+ * rather than hooks (the cloud navs assemble their tree outside a component)+ * and so must be handed a `t` instead of calling useTranslation themselves.+ *+ * Replaces a hardcoded-English copy of this list: the SaaS nav was its only+ * caller, which is why "Preferences", "General" and "Keyboard Shortcuts" never+ * translated there.+ */export const createConfigNavSections = (- _isAdmin: boolean = false,- _runningEE: boolean = false,- _loginEnabled: boolean = false,-): ConfigNavSection[] => {- console.warn(- "createConfigNavSections is deprecated. Use useConfigNavSections hook instead for proper i18n support.",- );- const sections: ConfigNavSection[] = [- {- title: "Preferences",- items: [- {- key: "general",- label: "General",- icon: "settings-rounded",- component: <GeneralSection hideTitle />,- },- {- key: "hotkeys",- label: "Keyboard Shortcuts",- icon: "keyboard-rounded",- component: <HotkeysSection />,- },- ],- },- ];-- return sections;-};+ t: TFunction<"translation", undefined>,+): ConfigNavSection[] => [+ {+ id: "preferences",+ title: t("settings.preferences.title", "Preferences"),+ items: [+ {+ key: "general",+ label: t("settings.general.title", "General"),+ icon: "settings-rounded",+ component: <GeneralSection hideTitle />,+ },+ {+ key: "hotkeys",+ label: t("settings.hotkeys.title", "Keyboard Shortcuts"),+ icon: "keyboard-rounded",+ component: <HotkeysSection />,+ },+ ],+ },+];diff --git a/frontend/editor/src/core/components/shared/config/configSections/AboutSection.css b/frontend/editor/src/core/components/shared/config/configSections/AboutSection.cssnew file mode 100644index 0000000000..7b72fd599e--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/AboutSection.css@@ -0,0 +1,5 @@+.about-section {+ display: flex;+ flex-direction: column;+ gap: var(--space-6, 2rem);+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/AboutSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/AboutSection.tsxnew file mode 100644index 0000000000..f2d6d31f82--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/AboutSection.tsx@@ -0,0 +1,82 @@+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import HelpSection from "@app/components/shared/config/configSections/HelpSection";+import LegalSection from "@app/components/shared/config/configSections/LegalSection";+import {+ BackendThirdPartyLicensesSection,+ FrontendThirdPartyLicensesSection,+} from "@app/components/shared/config/configSections/ThirdPartyLicensesSection";+import "@app/components/shared/config/configSections/AboutSection.css";++export interface AboutSectionProps {+ isAdmin: boolean;+ /** Tours need the settings page out of the way before they can run. */+ onRequestClose: () => void;+}++/**+ * The reference material: tours, legal links and bundled licences. Each card's+ * id is the `#slug` that deep links and search results address.+ *+ * Backend licences come last: it is the only card here that fetches, and the+ * only one that can render an error in place of its list.+ */+export default function AboutSection({+ isAdmin,+ onRequestClose,+}: AboutSectionProps) {+ const { t } = useTranslation();+ return (+ <div className="settings-section-container">+ <div className="about-section">+ <SettingsCard+ id="help"+ title={t("settings.help.label", "Tours")}+ description={t(+ "settings.help.description",+ "Guided walkthroughs of the editor and the admin area.",+ )}+ >+ <HelpSection isAdmin={isAdmin} onRequestClose={onRequestClose} />+ </SettingsCard>++ <SettingsCard+ id="legal"+ title={t("settings.legal.label", "Legal")}+ description={t(+ "settings.legal.description",+ "Terms, privacy policy and your cookie preferences.",+ )}+ >+ <LegalSection />+ </SettingsCard>++ <SettingsCard+ id="frontendThirdPartyLicenses"+ title={t("settings.licenses.frontendLabel", "Frontend Licenses")}+ description={t(+ "settings.licenses.frontendDescription",+ "Licenses for frontend dependencies bundled into the release build.",+ )}+ defaultCollapsed+ lazy+ >+ <FrontendThirdPartyLicensesSection />+ </SettingsCard>++ <SettingsCard+ id="backendThirdPartyLicenses"+ title={t("settings.licenses.backendLabel", "Backend Licenses")}+ description={t(+ "settings.licenses.backendDescription",+ "Licenses for backend dependencies bundled with this server.",+ )}+ defaultCollapsed+ lazy+ >+ <BackendThirdPartyLicensesSection />+ </SettingsCard>+ </div>+ </div>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsxindex 116822fe6f..63a3dcb62d 100644--- a/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx+++ b/frontend/editor/src/core/components/shared/config/configSections/GeneralSection.tsx@@ -1,10 +1,10 @@import React, { useId, useState, useEffect } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";import {Paper,Stack,Switch,Text,- Tooltip,NumberInput,Select,Code,@@ -276,13 +276,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({<Group justify="space-between" align="center"><div><Text fw={600} size="sm">- {t("settings.general.updates.title", "Software Updates")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.updates.description",- "Check for updates and view version information",- )}+ {t("settings.general.updates.title", "Software Updates")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.updates.description",+ "Check for updates and view version information",+ )}+ /></Text></div>{updateSummary && (@@ -417,18 +417,20 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({)}</Badge>)}+ <InfoTooltip+ label={+ desktopUpdateMode.locked+ ? t(+ "settings.general.updates.updateBehaviorLockedDescription",+ "Your administrator has configured how Stirling-PDF handles updates on this machine. Contact them to change this.",+ )+ : t(+ "settings.general.updates.updateBehaviorDescription",+ "Choose whether to prompt before installing updates, install them automatically, or skip update checks entirely.",+ )+ }+ /></Group>- <Text size="xs" c="dimmed">- {desktopUpdateMode.locked- ? t(- "settings.general.updates.updateBehaviorLockedDescription",- "Your administrator has configured how Stirling-PDF handles updates on this machine. Contact them to change this.",- )- : t(- "settings.general.updates.updateBehaviorDescription",- "Choose whether to prompt before installing updates, install them automatically, or skip update checks entirely.",- )}- </Text><Selectaria-labelledby={updateModeLabelId}disabled={desktopUpdateMode.locked}@@ -487,13 +489,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({><div style={{ flex: 1, minWidth: 0 }}><Text fw={500} size="sm">- {t("settings.general.theme", "Theme")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.themeDescription",- "Choose light, dark, or follow your system so it switches automatically.",- )}+ {t("settings.general.theme", "Theme")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.themeDescription",+ "Choose light, dark, or follow your system so it switches automatically.",+ )}+ /></Text></div><SegmentedControl@@ -530,13 +532,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({><div style={{ flex: 1, minWidth: 0 }}><Text fw={500} size="sm">- {t("settings.general.language", "Language")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.languageDescription",- "Choose the display language",- )}+ {t("settings.general.language", "Language")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.languageDescription",+ "Choose the display language",+ )}+ /></Text></div><LanguageSelector position="bottom-end" offset={6} />@@ -558,13 +560,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({{t("settings.general.defaultToolPickerMode","Default tool picker mode",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.defaultToolPickerModeDescription",- "Choose whether the tool picker opens in fullscreen or sidebar by default",- )}+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.defaultToolPickerModeDescription",+ "Choose whether the tool picker opens in fullscreen or sidebar by default",+ )}+ /></Text></div><SegmentedControl@@ -597,13 +599,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({{t("settings.general.defaultStartupView","Default view on launch",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.defaultStartupViewDescription",- "Choose which view is active when the app starts",- )}+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.defaultStartupViewDescription",+ "Choose which view is active when the app starts",+ )}+ /></Text></div><SegmentedControl@@ -637,13 +639,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({><div style={{ flex: 1, minWidth: 0 }}><Text id={viewerZoomLabelId} fw={500} size="sm">- {t("settings.general.defaultViewerZoom", "Default reader zoom")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.defaultViewerZoomDescription",- "Set the default zoom level when opening PDFs in the reader",- )}+ {t("settings.general.defaultViewerZoom", "Default reader zoom")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.defaultViewerZoomDescription",+ "Set the default zoom level when opening PDFs in the reader",+ )}+ /></Text></div><Select@@ -697,13 +699,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({{t("settings.general.hideUnavailableTools","Hide unavailable tools",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.hideUnavailableToolsDescription",- "Remove tools that have been disabled by your server instead of showing them greyed out.",- )}+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.hideUnavailableToolsDescription",+ "Remove tools that have been disabled by your server instead of showing them greyed out.",+ )}+ /></Text></div><Switch@@ -730,13 +732,13 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({{t("settings.general.hideUnavailableConversions","Hide unavailable conversions",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.hideUnavailableConversionsDescription",- "Remove disabled conversion options in the Convert tool instead of showing them greyed out.",- )}+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.hideUnavailableConversionsDescription",+ "Remove disabled conversion options in the Convert tool instead of showing them greyed out.",+ )}+ /></Text></div><Switch@@ -750,101 +752,80 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({}/></div>- <Tooltip- label={t(- "settings.general.autoUnzipTooltip",- "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.",- )}- multiline- w={300}- withArrow++ <div+ id="setting-auto-unzip"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}>- <div- id="setting-auto-unzip"- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- cursor: "help",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text id={autoUnzipLabelId} fw={500} size="sm">- {t("settings.general.autoUnzip", "Auto-unzip API responses")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.autoUnzipDescription",- "Automatically extract files from ZIP responses",+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={autoUnzipLabelId} fw={500} size="sm">+ {t("settings.general.autoUnzip", "Auto-unzip API responses")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.autoUnzipTooltip",+ "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.",)}- </Text>- </div>- <Switch- aria-labelledby={autoUnzipLabelId}- checked={preferences.autoUnzip}- onChange={(event) =>- updatePreference("autoUnzip", event.currentTarget.checked)- }- />+ />+ </Text></div>- </Tooltip>+ <Switch+ aria-labelledby={autoUnzipLabelId}+ checked={preferences.autoUnzip}+ onChange={(event) =>+ updatePreference("autoUnzip", event.currentTarget.checked)+ }+ />+ </div>- <Tooltip- label={t(- "settings.general.autoUnzipFileLimitTooltip",- "Only unzip if the ZIP contains this many files or fewer. Set higher to extract larger ZIPs.",- )}- multiline- w={300}- withArrow+ <div+ id="setting-auto-unzip-file-limit"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}>- <div- id="setting-auto-unzip-file-limit"- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- cursor: "help",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text id={autoUnzipLimitLabelId} fw={500} size="sm">- {t(- "settings.general.autoUnzipFileLimit",- "Auto-unzip file limit",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "settings.general.autoUnzipFileLimitDescription",- "Maximum number of files to extract from ZIP",+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={autoUnzipLimitLabelId} fw={500} size="sm">+ {t(+ "settings.general.autoUnzipFileLimit",+ "Auto-unzip file limit",+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.autoUnzipFileLimitTooltip",+ "Only unzip if the ZIP contains this many files or fewer. Set higher to extract larger ZIPs.",)}- </Text>- </div>- <NumberInput- aria-labelledby={autoUnzipLimitLabelId}- value={fileLimitInput}- onChange={setFileLimitInput}- onBlur={() => {- const numValue = Number(fileLimitInput);- const finalValue =- !fileLimitInput ||- isNaN(numValue) ||- numValue < 1 ||- numValue > 100- ? DEFAULT_AUTO_UNZIP_FILE_LIMIT- : numValue;- setFileLimitInput(finalValue);- updatePreference("autoUnzipFileLimit", finalValue);- }}- min={1}- max={100}- step={1}- disabled={!preferences.autoUnzip}- style={{ width: 90 }}- />+ />+ </Text></div>- </Tooltip>+ <NumberInput+ aria-labelledby={autoUnzipLimitLabelId}+ value={fileLimitInput}+ onChange={setFileLimitInput}+ onBlur={() => {+ const numValue = Number(fileLimitInput);+ const finalValue =+ !fileLimitInput ||+ isNaN(numValue) ||+ numValue < 1 ||+ numValue > 100+ ? DEFAULT_AUTO_UNZIP_FILE_LIMIT+ : numValue;+ setFileLimitInput(finalValue);+ updatePreference("autoUnzipFileLimit", finalValue);+ }}+ min={1}+ max={100}+ step={1}+ disabled={!preferences.autoUnzip}+ style={{ width: 90 }}+ />+ </div></Stack></Paper>diff --git a/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsxindex 54c672ca1f..013d73d8c1 100644--- a/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx+++ b/frontend/editor/src/core/components/shared/config/configSections/HotkeysSection.tsx@@ -146,19 +146,8 @@ const HotkeysSection: React.FC = () => {return (<Stack gap="lg">- <div id="setting-hotkeys-search">- <Text fw={600} size="lg">- {t("settings.hotkeys.title", "Keyboard Shortcuts")}- </Text>- <Text size="sm" c="dimmed">- {t(- "settings.hotkeys.description",- 'Customize keyboard shortcuts for quick tool access. Click "Change shortcut" and press a new key combination. Press Esc to cancel.',- )}- </Text>- </div>-<TextInput+ id="setting-hotkeys-search"placeholder={t("settings.hotkeys.searchPlaceholder", "Search tools...")}value={searchQuery}onChange={(event) => setSearchQuery(event.currentTarget.value)}diff --git a/frontend/editor/src/core/components/shared/config/configSections/ProviderCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/ProviderCard.tsxindex 46260622ad..bf16d76918 100644--- a/frontend/editor/src/core/components/shared/config/configSections/ProviderCard.tsx+++ b/frontend/editor/src/core/components/shared/config/configSections/ProviderCard.tsx@@ -1,4 +1,6 @@import { useEffect, useState } from "react";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { SettingsFieldLabel } from "@app/components/shared/config/SettingsFieldLabel";import {Paper,Group,@@ -7,7 +9,6 @@ import {Stack,TextInput,Textarea,- Switch,NumberInput,TagsInput,Anchor,@@ -102,28 +103,14 @@ export default function ProviderCard({switch (field.type) {case "switch":return (- <div+ <SettingsToggleRowkey={field.key}- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {field.label}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {field.description}- </Text>- </div>- <Switch- checked={Boolean(raw)}- onChange={(e) => handleFieldChange(field.key, e.target.checked)}- disabled={disabled}- />- </div>+ label={field.label}+ info={field.description}+ checked={Boolean(raw)}+ onChange={(checked) => handleFieldChange(field.key, checked)}+ disabled={disabled}+ />);case "password":@@ -143,8 +130,11 @@ export default function ProviderCard({return (<Textareakey={field.key}- label={field.label}- description={field.description}+ label={+ <SettingsFieldLabel info={field.description}>+ {field.label}+ </SettingsFieldLabel>+ }placeholder={field.placeholder}value={asString(raw)}onChange={(e) => handleFieldChange(field.key, e.target.value)}@@ -156,8 +146,11 @@ export default function ProviderCard({return (<NumberInputkey={field.key}- label={field.label}- description={field.description}+ label={+ <SettingsFieldLabel info={field.description}>+ {field.label}+ </SettingsFieldLabel>+ }placeholder={field.placeholder}value={typeof raw === "number" || typeof raw === "string" ? raw : ""@@ -174,8 +167,11 @@ export default function ProviderCard({return (<TagsInputkey={field.key}- label={field.label}- description={field.description}+ label={+ <SettingsFieldLabel info={field.description}>+ {field.label}+ </SettingsFieldLabel>+ }placeholder={field.placeholder}value={tagValue}onChange={(vals) => handleFieldChange(field.key, vals)}@@ -188,8 +184,11 @@ export default function ProviderCard({return (<TextInputkey={field.key}- label={field.label}- description={field.description}+ label={+ <SettingsFieldLabel info={field.description}>+ {field.label}+ </SettingsFieldLabel>+ }placeholder={field.placeholder}value={asString(raw)}onChange={(e) => handleFieldChange(field.key, e.target.value)}diff --git a/frontend/editor/src/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsxindex e3f7b6b990..3b0576b7bb 100644--- a/frontend/editor/src/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx+++ b/frontend/editor/src/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx@@ -27,19 +27,13 @@ interface LicensesResponse {}interface LicensesSectionBodyProps {- title: string;- description: string;dependencies: Dependency[];}const getModuleUrl = (dependency: Dependency) =>dependency.moduleUrl || dependency.moduleLicenseUrl;-function LicensesSectionBody({- title,- description,- dependencies,-}: LicensesSectionBodyProps) {+function LicensesSectionBody({ dependencies }: LicensesSectionBodyProps) {const { t } = useTranslation();const sortedDependencies = useMemo(() =>@@ -60,15 +54,6 @@ function LicensesSectionBody({<Stack gap="lg"><Paper withBorder p="md" radius="md"><Stack gap="md">- <div>- <Text fw={600} size="sm">- {title}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {description}- </Text>- </div>-<Group justify="space-between" align="center"><div><Text fw={600} size="sm">@@ -201,36 +186,14 @@ export function BackendThirdPartyLicensesSection() {);}- return (- <LicensesSectionBody- title={t("settings.licenses.backendTitle", "Backend 3rd Party Licenses")}- description={t(- "settings.licenses.backendDescription",- "Licenses for backend dependencies bundled with this server.",- )}- dependencies={dependencies}- />- );+ return <LicensesSectionBody dependencies={dependencies} />;}export function FrontendThirdPartyLicensesSection() {- const { t } = useTranslation();const dependencies =(frontendLicenses as LicensesResponse).dependencies ?? [];- return (- <LicensesSectionBody- title={t(- "settings.licenses.frontendTitle",- "Frontend 3rd Party Licenses",- )}- description={t(- "settings.licenses.frontendDescription",- "Licenses for frontend dependencies bundled into the release build.",- )}- dependencies={dependencies}- />- );+ return <LicensesSectionBody dependencies={dependencies} />;}export default function ThirdPartyLicensesSection() {diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AccountSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/AccountCards.tsxsimilarity index 80%rename from frontend/editor/src/proprietary/components/shared/config/configSections/AccountSection.tsxrename to frontend/editor/src/core/components/shared/config/configSections/preferences/AccountCards.tsxindex 4f132eb399..4cc0da008f 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AccountSection.tsx+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/AccountCards.tsx@@ -1,4 +1,5 @@import React, { useCallback, useEffect, useMemo, useState } from "react";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";import {Alert,Box,@@ -22,7 +23,20 @@ import { useAccountLogout } from "@app/extensions/accountLogout";import { BASE_PATH, withBasePath } from "@app/constants/app";import { MfaSetupResponse } from "@app/responses/Mfa/MfaResponse";-const AccountSection: React.FC = () => {+/** The signed-in user's shape is layer-specific, so read fields defensively. */+function userField(source: unknown, key: string): string | undefined {+ if (!source || typeof source !== "object") return undefined;+ const value = (source as Record<string, unknown>)[key];+ return typeof value === "string" ? value : undefined;+}++/**+ * The Account and Two-factor cards of the Preferences page, together because+ * they share one account fetch, one SSO check and one logout. Passed into the+ * page's `accountSlot` by the flavors that have accounts; each card carries the+ * id its retired nav row had, so old deep links still resolve.+ */+export function AccountCards() {const { t } = useTranslation();const { user, signOut } = useAuth();const accountLogout = useAccountLogout();@@ -58,25 +72,23 @@ const AccountSection: React.FC = () => {const qrLogoSrc = `${BASE_PATH}/modern-logo/StirlingPDFLogoNoTextDark.svg`;const authTypeFromMetadata = useMemo(() => {- const metadata = user?.app_metadata as- | { authType?: string; authenticationType?: string }- | undefined;- return metadata?.authenticationType ?? metadata?.authType;- }, [user?.app_metadata]);-- const normalizedAuthType = useMemo(- () =>- (user?.authenticationType ?? authTypeFromMetadata ?? "").toLowerCase(),- [authTypeFromMetadata, user?.authenticationType],- );+ const metadata = (user as { app_metadata?: unknown } | null)?.app_metadata;+ const explicit = userField(metadata, "authenticationType");+ return explicit ?? userField(metadata, "authType");+ }, [user]);++ const normalizedAuthType = useMemo(() => {+ const raw = userField(user, "authenticationType") ?? authTypeFromMetadata;+ return (raw ?? "").toLowerCase();+ }, [authTypeFromMetadata, user]);const isSsoUser = useMemo(() => ["sso", "oauth2", "saml2"].includes(normalizedAuthType),[normalizedAuthType],);const userIdentifier = useMemo(- () => user?.email || user?.username || "",- [user?.email, user?.username],+ () => userField(user, "email") || userField(user, "username") || "",+ [user],);const redirectToLogin = useCallback(() => {@@ -347,131 +359,128 @@ const AccountSection: React.FC = () => {};return (- <Stack gap="md">- <div>- <Text fw={600} size="lg">- {t("account.accountSettings", "Account")}- </Text>- <Text size="sm" c="dimmed">- {t("changeCreds.header", "Update Your Account Details")}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="sm">- <Text size="sm" c="dimmed">- {userIdentifier- ? t("settings.general.user", "User") + ": " + userIdentifier- : t("account.accountSettings", "Account Settings")}- </Text>-- <Stack gap="xs">- {isSsoUser && (- <Alert- icon={<LocalIcon icon="info" width="1rem" height="1rem" />}- color="blue"- variant="light"- >- {t(- "changeCreds.ssoManaged",- "Your account is managed by your identity provider.",- )}- </Alert>- )}+ <>+ <SettingsCard+ id="account"+ title={t("account.accountSettings", "Account")}+ description={t("changeCreds.header", "Update Your Account Details")}+ >+ <Paper withBorder p="md" radius="md">+ <Stack gap="sm">+ <Text size="sm" c="dimmed">+ {userIdentifier+ ? t("settings.general.user", "User") + ": " + userIdentifier+ : t("account.accountSettings", "Account Settings")}+ </Text>- <Group gap="sm" wrap="wrap">- {!isSsoUser && (- <Button- leftSection={<LocalIcon icon="key-rounded" />}- onClick={() => setPasswordModalOpen(true)}+ <Stack gap="xs">+ {isSsoUser && (+ <Alert+ icon={<LocalIcon icon="info" width="1rem" height="1rem" />}+ color="blue"+ variant="light">- {t("settings.security.password.update", "Update password")}- </Button>+ {t(+ "changeCreds.ssoManaged",+ "Your account is managed by your identity provider.",+ )}+ </Alert>)}- {!isSsoUser && (- <Button- variant="secondary"- leftSection={<LocalIcon icon="edit-rounded" />}- onClick={() => setUsernameModalOpen(true)}- >- {t("account.changeUsername", "Change username")}- </Button>- )}+ <Group gap="sm" wrap="wrap">+ {!isSsoUser && (+ <Button+ leftSection={<LocalIcon icon="key-rounded" />}+ onClick={() => setPasswordModalOpen(true)}+ >+ {t("settings.security.password.update", "Update password")}+ </Button>+ )}++ {!isSsoUser && (+ <Button+ variant="secondary"+ leftSection={<LocalIcon icon="edit-rounded" />}+ onClick={() => setUsernameModalOpen(true)}+ >+ {t("account.changeUsername", "Change username")}+ </Button>+ )}- <Button- variant="secondary"- accent="danger"- leftSection={<LocalIcon icon="logout-rounded" />}- onClick={handleLogout}- >- {t("settings.general.logout", "Log out")}- </Button>- </Group>- </Stack>- </Stack>- </Paper>-- <Paper withBorder p="md" radius="md">- <Stack gap="sm">- <Text fw={600}>- {t("account.mfa.title", "Two-factor authentication")}- </Text>- <Text size="sm" c="dimmed">- {t(- "account.mfa.description",- "Add an extra layer of security to your account.",- )}- </Text>- {isSsoUser ? (- <Alert- icon={<LocalIcon icon="info" width="1rem" height="1rem" />}- color="blue"- variant="light"- >- {t(- "account.mfa.ssoManaged",- "Two-factor authentication for this account is managed by your identity provider.",- )}- </Alert>- ) : (- <Group gap="sm" wrap="wrap">- {!mfaEnabled ? (- <Button- leftSection={- <LocalIcon icon="check-circle-outline-rounded" />- }- onClick={handleStartMfaSetup}- loading={mfaLoading}- disabled={changeButtonDisabled}- >- {t(- "account.mfa.enableButton",- "Enable two-factor authentication",- )}- </Button>- ) : (<Buttonvariant="secondary"accent="danger"- leftSection={<LocalIcon icon="close-rounded" />}- onClick={() => {- setMfaError("");- setMfaDisableCode("");- setMfaDisableModalOpen(true);- }}- disabled={changeButtonDisabled}+ leftSection={<LocalIcon icon="logout-rounded" />}+ onClick={handleLogout}>- {t(- "account.mfa.disableButton",- "Disable two-factor authentication",- )}+ {t("settings.general.logout", "Log out")}</Button>- )}- </Group>- )}- </Stack>- </Paper>+ </Group>+ </Stack>+ </Stack>+ </Paper>+ </SettingsCard>++ <SettingsCard+ id="twoFactor"+ title={t("account.mfa.title", "Two-factor authentication")}+ description={t(+ "account.mfa.description",+ "Add an extra layer of security to your account.",+ )}+ >+ <Paper withBorder p="md" radius="md">+ <Stack gap="sm">+ {isSsoUser ? (+ <Alert+ icon={<LocalIcon icon="info" width="1rem" height="1rem" />}+ color="blue"+ variant="light"+ >+ {t(+ "account.mfa.ssoManaged",+ "Two-factor authentication for this account is managed by your identity provider.",+ )}+ </Alert>+ ) : (+ <Group gap="sm" wrap="wrap">+ {!mfaEnabled ? (+ <Button+ leftSection={+ <LocalIcon icon="check-circle-outline-rounded" />+ }+ onClick={handleStartMfaSetup}+ loading={mfaLoading}+ disabled={changeButtonDisabled}+ >+ {t(+ "account.mfa.enableButton",+ "Enable two-factor authentication",+ )}+ </Button>+ ) : (+ <Button+ variant="secondary"+ accent="danger"+ leftSection={<LocalIcon icon="close-rounded" />}+ onClick={() => {+ setMfaError("");+ setMfaDisableCode("");+ setMfaDisableModalOpen(true);+ }}+ disabled={changeButtonDisabled}+ >+ {t(+ "account.mfa.disableButton",+ "Disable two-factor authentication",+ )}+ </Button>+ )}+ </Group>+ )}+ </Stack>+ </Paper>+ </SettingsCard><Modalopened={passwordModalOpen}@@ -776,8 +785,8 @@ const AccountSection: React.FC = () => {</Stack></form></Modal>- </Stack>+ </>);-};+}-export default AccountSection;+export default AccountCards;diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/AdminSetupBanner.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/AdminSetupBanner.tsxnew file mode 100644index 0000000000..e0a8218db9--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/AdminSetupBanner.tsx@@ -0,0 +1,108 @@+import { useState } from "react";+import { Anchor, Code, Group, Paper, Stack, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { ActionIcon } from "@app/ui/ActionIcon";+import LocalIcon from "@app/components/shared/LocalIcon";+import { useAppConfig } from "@app/contexts/AppConfigContext";++const BANNER_DISMISSED_KEY = "stirlingpdf_features_banner_dismissed";++/**+ * Shown only when login is off: the two env vars that turn on accounts, teams+ * and the admin surface. Dismissed for good once closed.+ */+export function AdminSetupBanner() {+ const { t } = useTranslation();+ const { config } = useAppConfig();+ const [bannerDismissed, setBannerDismissed] = useState(() => {+ // Check localStorage on mount+ return localStorage.getItem(BANNER_DISMISSED_KEY) === "true";+ });++ // Check if login is disabled+ const loginDisabled = !config?.enableLogin;++ const handleDismissBanner = () => {+ setBannerDismissed(true);+ localStorage.setItem(BANNER_DISMISSED_KEY, "true");+ };++ if (!loginDisabled || bannerDismissed) {+ return null;+ }++ return (+ <Paper+ withBorder+ p="md"+ radius="md"+ style={{+ background: "var(--mantine-color-blue-0)",+ position: "relative",+ }}+ >+ <ActionIcon+ variant="tertiary"+ size="sm"+ style={{ position: "absolute", top: "0.5rem", right: "0.5rem" }}+ onClick={handleDismissBanner}+ aria-label={t("settings.general.enableFeatures.dismiss", "Dismiss")}+ >+ <LocalIcon icon="close-rounded" width="1rem" height="1rem" />+ </ActionIcon>+ <Stack gap="sm">+ <Group gap="xs">+ <LocalIcon+ icon="admin-panel-settings-rounded"+ width="1.2rem"+ height="1.2rem"+ style={{ color: "var(--c-accent-text)" }}+ />+ <Text+ fw={600}+ size="sm"+ style={{ color: "var(--mantine-color-blue-9)" }}+ >+ {t(+ "settings.general.enableFeatures.title",+ "For System Administrators",+ )}+ </Text>+ </Group>+ <Text size="sm" c="dimmed">+ {t(+ "settings.general.enableFeatures.intro",+ "Enable user authentication, team management, and workspace features for your organization.",+ )}+ </Text>+ <Group gap="xs" wrap="wrap">+ <Text size="sm" c="dimmed">+ {t("settings.general.enableFeatures.action", "Configure")}+ </Text>+ <Code>SECURITY_ENABLELOGIN=true</Code>+ <Text size="sm" c="dimmed">+ {t("settings.general.enableFeatures.and", "and")}+ </Text>+ <Code>DISABLE_ADDITIONAL_FEATURES=false</Code>+ </Group>+ <Text size="xs" c="dimmed" fs="italic">+ {t(+ "settings.general.enableFeatures.benefit",+ "Enables user roles, team collaboration, admin controls, and enterprise features.",+ )}+ </Text>+ <Anchor+ href="https://docs.stirlingpdf.com/Configuration/System%20and%20Security/"+ target="_blank"+ size="sm"+ >+ {t(+ "settings.general.enableFeatures.learnMore",+ "Learn more in documentation",+ )}{" "}+ →+ </Anchor>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsxnew file mode 100644index 0000000000..7ea5847b10--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/AppearanceCard.tsx@@ -0,0 +1,79 @@+import { Paper, Stack, Text } from "@mantine/core";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useTranslation } from "react-i18next";+import { SegmentedControl } from "@app/ui/SegmentedControl";+import { useTheme } from "@app/components/shared/ThemeProvider";+import LanguageSelector from "@app/components/shared/LanguageSelector";+import { type ThemeMode } from "@app/constants/theme";++/** How the app looks: theme and display language. Both write through at once. */+export function AppearanceCard() {+ const { t } = useTranslation();+ const { setTheme, themeMode } = useTheme();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div+ id="setting-theme"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text fw={500} size="sm">+ {t("settings.general.theme", "Theme")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.themeDescription",+ "Choose light, dark, or follow your system so it switches automatically.",+ )}+ />+ </Text>+ </div>+ <SegmentedControl+ value={themeMode}+ onChange={(val) => setTheme(val as ThemeMode)}+ options={[+ {+ label: t("settings.general.themeLight", "Light"),+ value: "light",+ },+ {+ label: t("settings.general.themeDark", "Dark"),+ value: "dark",+ },+ {+ label: t("settings.general.themeSystem", "System"),+ value: "system",+ },+ ]}+ />+ </div>+ <div+ id="setting-language"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text fw={500} size="sm">+ {t("settings.general.language", "Language")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.languageDescription",+ "Choose the display language",+ )}+ />+ </Text>+ </div>+ <LanguageSelector position="bottom-end" offset={6} />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/DownloadsCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/DownloadsCard.tsxnew file mode 100644index 0000000000..c90b19bf02--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/DownloadsCard.tsx@@ -0,0 +1,106 @@+import { useEffect, useId, useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { NumberInput, Paper, Stack, Switch, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { usePreferences } from "@app/contexts/PreferencesContext";++const DEFAULT_AUTO_UNZIP_FILE_LIMIT = 4;++/** What happens to ZIPs the API hands back. Automations are unaffected. */+export function DownloadsCard() {+ const { t } = useTranslation();+ // Each setting is a row of label text next to a bare control, so the controls+ // are named by pointing at that text rather than by a <label> association.+ const labelIds = useId();+ const autoUnzipLabelId = `${labelIds}-auto-unzip`;+ const autoUnzipLimitLabelId = `${labelIds}-auto-unzip-limit`;+ const { preferences, updatePreference } = usePreferences();+ const [fileLimitInput, setFileLimitInput] = useState<number | string>(+ preferences.autoUnzipFileLimit,+ );++ // Sync local state with preference changes+ useEffect(() => {+ setFileLimitInput(preferences.autoUnzipFileLimit);+ }, [preferences.autoUnzipFileLimit]);++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div+ id="setting-auto-unzip"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={autoUnzipLabelId} fw={500} size="sm">+ {t("settings.general.autoUnzip", "Auto-unzip API responses")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.autoUnzipTooltip",+ "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.",+ )}+ />+ </Text>+ </div>+ <Switch+ aria-labelledby={autoUnzipLabelId}+ checked={preferences.autoUnzip}+ onChange={(event) =>+ updatePreference("autoUnzip", event.currentTarget.checked)+ }+ />+ </div>++ <div+ id="setting-auto-unzip-file-limit"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={autoUnzipLimitLabelId} fw={500} size="sm">+ {t(+ "settings.general.autoUnzipFileLimit",+ "Auto-unzip file limit",+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.autoUnzipFileLimitTooltip",+ "Only unzip if the ZIP contains this many files or fewer. Set higher to extract larger ZIPs.",+ )}+ />+ </Text>+ </div>+ <NumberInput+ aria-labelledby={autoUnzipLimitLabelId}+ value={fileLimitInput}+ onChange={setFileLimitInput}+ onBlur={() => {+ const numValue = Number(fileLimitInput);+ const finalValue =+ !fileLimitInput ||+ isNaN(numValue) ||+ numValue < 1 ||+ numValue > 100+ ? DEFAULT_AUTO_UNZIP_FILE_LIMIT+ : numValue;+ setFileLimitInput(finalValue);+ updatePreference("autoUnzipFileLimit", finalValue);+ }}+ min={1}+ max={100}+ step={1}+ disabled={!preferences.autoUnzip}+ style={{ width: 90 }}+ />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/EditorDefaultsCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/EditorDefaultsCard.tsxnew file mode 100644index 0000000000..a28b7b822a--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/EditorDefaultsCard.tsx@@ -0,0 +1,233 @@+import { useId } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { Paper, Select, Stack, Switch, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { SegmentedControl } from "@app/ui/SegmentedControl";+import { usePreferences } from "@app/contexts/PreferencesContext";+import type { ToolPanelMode } from "@app/constants/toolPanel";+import {+ type StartupView,+ type ViewerZoomSetting,+} from "@app/services/preferencesService";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";++/** What the editor opens with, and which tools it bothers to list. */+export function EditorDefaultsCard() {+ const { t } = useTranslation();+ // Each setting is a row of label text next to a bare control, so the controls+ // are named by pointing at that text rather than by a <label> association.+ const labelIds = useId();+ const viewerZoomLabelId = `${labelIds}-viewer-zoom`;+ const hideToolsLabelId = `${labelIds}-hide-tools`;+ const hideConversionsLabelId = `${labelIds}-hide-conversions`;+ const { preferences, updatePreference } = usePreferences();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div+ id="setting-tool-picker-mode"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text fw={500} size="sm">+ {t(+ "settings.general.defaultToolPickerMode",+ "Default tool picker mode",+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.defaultToolPickerModeDescription",+ "Choose whether the tool picker opens in fullscreen or sidebar by default",+ )}+ />+ </Text>+ </div>+ <SegmentedControl+ value={preferences.defaultToolPanelMode}+ onChange={(val: string) =>+ updatePreference("defaultToolPanelMode", val as ToolPanelMode)+ }+ options={[+ {+ label: t("settings.general.mode.sidebar", "Sidebar"),+ value: "sidebar",+ },+ {+ label: t("settings.general.mode.fullscreen", "Fullscreen"),+ value: "fullscreen",+ },+ ]}+ />+ </div>+ <div+ id="setting-startup-view"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text fw={500} size="sm">+ {t(+ "settings.general.defaultStartupView",+ "Default view on launch",+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.defaultStartupViewDescription",+ "Choose which view is active when the app starts",+ )}+ />+ </Text>+ </div>+ <SegmentedControl+ value={preferences.defaultStartupView}+ onChange={(val: string) =>+ updatePreference("defaultStartupView", val as StartupView)+ }+ options={[+ {+ label: t("settings.general.startupView.tools", "Tools"),+ value: "tools",+ },+ {+ label: t("settings.general.startupView.read", "Reader"),+ value: "read",+ },+ {+ label: t("settings.general.startupView.automate", "Automate"),+ value: "automate",+ },+ ]}+ />+ </div>+ <div+ id="setting-reader-zoom"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={viewerZoomLabelId} fw={500} size="sm">+ {t("settings.general.defaultViewerZoom", "Default reader zoom")}{" "}+ <InfoTooltip+ label={t(+ "settings.general.defaultViewerZoomDescription",+ "Set the default zoom level when opening PDFs in the reader",+ )}+ />+ </Text>+ </div>+ <Select+ aria-labelledby={viewerZoomLabelId}+ value={preferences.defaultViewerZoom}+ onChange={(val: string | null) => {+ if (val)+ updatePreference("defaultViewerZoom", val as ViewerZoomSetting);+ }}+ data={[+ {+ label: t("settings.general.zoomLevel.auto", "Auto"),+ value: "auto",+ },+ {+ label: t("settings.general.zoomLevel.fitWidth", "Fit width"),+ value: "fitWidth",+ },+ {+ label: t("settings.general.zoomLevel.fitPage", "Fit page"),+ value: "fitPage",+ },+ { label: "50%", value: "50" },+ { label: "75%", value: "75" },+ { label: "100%", value: "100" },+ { label: "125%", value: "125" },+ { label: "150%", value: "150" },+ { label: "200%", value: "200" },+ ]}+ style={{ width: 140 }}+ allowDeselect={false}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />+ </div>+ <div+ id="setting-hide-unavailable-tools"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={hideToolsLabelId} fw={500} size="sm">+ {t(+ "settings.general.hideUnavailableTools",+ "Hide unavailable tools",+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.hideUnavailableToolsDescription",+ "Remove tools that have been disabled by your server instead of showing them greyed out.",+ )}+ />+ </Text>+ </div>+ <Switch+ aria-labelledby={hideToolsLabelId}+ checked={preferences.hideUnavailableTools}+ onChange={(event) =>+ updatePreference(+ "hideUnavailableTools",+ event.currentTarget.checked,+ )+ }+ />+ </div>+ <div+ id="setting-hide-unavailable-conversions"+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text id={hideConversionsLabelId} fw={500} size="sm">+ {t(+ "settings.general.hideUnavailableConversions",+ "Hide unavailable conversions",+ )}{" "}+ <InfoTooltip+ label={t(+ "settings.general.hideUnavailableConversionsDescription",+ "Remove disabled conversion options in the Convert tool instead of showing them greyed out.",+ )}+ />+ </Text>+ </div>+ <Switch+ aria-labelledby={hideConversionsLabelId}+ checked={preferences.hideUnavailableConversions}+ onChange={(event) =>+ updatePreference(+ "hideUnavailableConversions",+ event.currentTarget.checked,+ )+ }+ />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsxnew file mode 100644index 0000000000..6b62315666--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/HotkeysCard.tsx@@ -0,0 +1,297 @@+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ Alert,+ Badge,+ Box,+ Divider,+ Group,+ Paper,+ Stack,+ Text,+ TextInput,+} from "@mantine/core";+import { Button } from "@app/ui/Button";+import { useTranslation } from "react-i18next";+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";+import { useHotkeys } from "@app/contexts/HotkeyContext";+import { ToolId } from "@app/types/toolId";+import HotkeyDisplay from "@app/components/hotkeys/HotkeyDisplay";+import {+ bindingEquals,+ eventToBinding,+ HotkeyBinding,+} from "@app/utils/hotkeys";+import { ToolRegistryEntry } from "@app/data/toolsTaxonomy";++const rowStyle: React.CSSProperties = {+ display: "flex",+ flexDirection: "column",+ gap: "0.5rem",+};++const rowHeaderStyle: React.CSSProperties = {+ display: "flex",+ flexWrap: "wrap",+ alignItems: "center",+ justifyContent: "space-between",+ gap: "0.5rem",+};++/**+ * One rebindable shortcut per registered tool. While a capture is armed this+ * swallows every keystroke in the window, so it disarms as soon as the pointer+ * or the focus leaves the row being rebound - otherwise the first character of+ * a password typed in a sibling card would be captured as a shortcut.+ */+export function HotkeysCard() {+ const { t } = useTranslation();+ const { toolRegistry } = useToolWorkflow();+ const {+ hotkeys,+ defaults,+ updateHotkey,+ resetHotkey,+ pauseHotkeys,+ resumeHotkeys,+ getDisplayParts,+ isMac,+ } = useHotkeys();+ const [editingTool, setEditingTool] = useState<ToolId | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [searchQuery, setSearchQuery] = useState<string>("");+ const editingRowRef = useRef<HTMLDivElement | null>(null);++ const tools = useMemo(+ () => Object.entries(toolRegistry) as [ToolId, ToolRegistryEntry][],+ [toolRegistry],+ );++ const filteredTools = useMemo(() => {+ if (!searchQuery.trim()) return tools;++ const query = searchQuery.toLowerCase();+ return tools.filter(+ ([toolId, tool]) =>+ tool.name.toLowerCase().includes(query) ||+ tool.description.toLowerCase().includes(query) ||+ toolId.toLowerCase().includes(query),+ );+ }, [tools, searchQuery]);++ const cancelCapture = useCallback(() => {+ setEditingTool(null);+ setError(null);+ }, []);++ useEffect(() => {+ if (!editingTool) {+ return;+ }+ pauseHotkeys();+ return () => {+ resumeHotkeys();+ };+ }, [editingTool, pauseHotkeys, resumeHotkeys]);++ // Pointer, focus or window leaving the row being rebound ends the capture, so+ // no other field ever loses a keystroke to it.+ useEffect(() => {+ if (!editingTool) {+ return;+ }++ // Capture phase: a modal or menu that stops propagation must not keep the+ // capture armed behind it.+ const handleLeave = (event: Event) => {+ const target = event.target;+ if (target instanceof Node && editingRowRef.current?.contains(target)) {+ return;+ }+ cancelCapture();+ };++ window.addEventListener("pointerdown", handleLeave, true);+ window.addEventListener("focusin", handleLeave, true);+ window.addEventListener("blur", cancelCapture);+ return () => {+ window.removeEventListener("pointerdown", handleLeave, true);+ window.removeEventListener("focusin", handleLeave, true);+ window.removeEventListener("blur", cancelCapture);+ };+ }, [editingTool, cancelCapture]);++ useEffect(() => {+ if (!editingTool) {+ return;+ }++ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ setEditingTool(null);+ setError(null);+ return;+ }++ event.preventDefault();+ event.stopPropagation();++ const binding = eventToBinding(event as KeyboardEvent);+ if (!binding) {+ const osKey = isMac ? "mac" : "windows";+ setError(t(`settings.hotkeys.errorModifier.${osKey}`));+ return;+ }++ const conflictEntry = (+ Object.entries(hotkeys) as [ToolId, HotkeyBinding][]+ ).find(+ ([toolId, existing]) =>+ toolId !== editingTool && bindingEquals(existing, binding),+ );++ if (conflictEntry) {+ const conflictKey = conflictEntry[0];+ const conflictTool =+ conflictKey in toolRegistry+ ? toolRegistry[conflictKey as ToolId]?.name+ : conflictKey;+ setError(+ t(+ "settings.hotkeys.errorConflict",+ "Shortcut already used by {{tool}}.",+ { tool: conflictTool },+ ),+ );+ return;+ }++ updateHotkey(editingTool, binding);+ setEditingTool(null);+ setError(null);+ };++ window.addEventListener("keydown", handleKeyDown, true);+ return () => {+ window.removeEventListener("keydown", handleKeyDown, true);+ };+ }, [editingTool, hotkeys, toolRegistry, updateHotkey, t]);++ const handleStartCapture = (toolId: ToolId) => {+ setEditingTool(toolId);+ setError(null);+ };++ return (+ <>+ <TextInput+ id="setting-hotkeys-search"+ placeholder={t("settings.hotkeys.searchPlaceholder", "Search tools...")}+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.currentTarget.value)}+ size="md"+ radius="md"+ />++ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ {filteredTools.length === 0 ? (+ <Text c="dimmed" ta="center" py="xl">+ {t("toolPicker.noToolsFound", "No tools found")}+ </Text>+ ) : (+ filteredTools.map(([toolId, tool], index) => {+ const currentBinding = hotkeys[toolId];+ const defaultBinding = defaults[toolId];+ const isEditing = editingTool === toolId;+ const defaultParts = getDisplayParts(defaultBinding);+ const defaultLabel =+ defaultParts.length > 0+ ? defaultParts.join(" + ")+ : t("settings.hotkeys.none", "Not assigned");++ return (+ <React.Fragment key={toolId}>+ <Box+ ref={isEditing ? editingRowRef : undefined}+ style={rowStyle}+ data-testid={`hotkey-row-${toolId}`}+ >+ <div style={rowHeaderStyle}>+ <div+ style={{+ display: "flex",+ flexDirection: "column",+ gap: "0.25rem",+ minWidth: 0,+ }}+ >+ <Text fw={600}>{tool.name}</Text>+ <Group gap="xs" wrap="wrap" align="center">+ <HotkeyDisplay binding={currentBinding} size="md" />+ {!bindingEquals(currentBinding, defaultBinding) && (+ <Badge variant="light" color="orange" radius="sm">+ {t("settings.hotkeys.customBadge", "Custom")}+ </Badge>+ )}+ <Text size="xs" c="dimmed">+ {t(+ "settings.hotkeys.defaultLabel",+ "Default: {{shortcut}}",+ { shortcut: defaultLabel },+ )}+ </Text>+ </Group>+ </div>++ <Group gap="xs">+ <Button+ size="sm"+ variant={isEditing ? "primary" : "secondary"}+ onClick={() => handleStartCapture(toolId)}+ >+ {isEditing+ ? t(+ "settings.hotkeys.capturing",+ "Press keys… (Esc to cancel)",+ )+ : t("settings.hotkeys.change", "Change shortcut")}+ </Button>+ <Button+ size="sm"+ variant="tertiary"+ disabled={bindingEquals(+ currentBinding,+ defaultBinding,+ )}+ onClick={() => resetHotkey(toolId)}+ >+ {t("settings.hotkeys.reset", "Reset")}+ </Button>+ </Group>+ </div>++ {isEditing && error && (+ <Alert color="red" radius="sm" variant="filled">+ {error}+ </Alert>+ )}+ </Box>++ {index < filteredTools.length - 1 && <Divider />}+ </React.Fragment>+ );+ })+ )}+ </Stack>+ </Paper>+ </>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/PreferencesSection.css b/frontend/editor/src/core/components/shared/config/configSections/preferences/PreferencesSection.cssnew file mode 100644index 0000000000..b53e51564d--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/PreferencesSection.css@@ -0,0 +1,5 @@+.preferences-section {+ display: flex;+ flex-direction: column;+ gap: var(--space-6, 2rem);+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/PreferencesSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/PreferencesSection.tsxnew file mode 100644index 0000000000..2e1b95af4f--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/PreferencesSection.tsx@@ -0,0 +1,124 @@+import { type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { AdminSetupBanner } from "@app/components/shared/config/configSections/preferences/AdminSetupBanner";+import { AppearanceCard } from "@app/components/shared/config/configSections/preferences/AppearanceCard";+import { EditorDefaultsCard } from "@app/components/shared/config/configSections/preferences/EditorDefaultsCard";+import { DownloadsCard } from "@app/components/shared/config/configSections/preferences/DownloadsCard";+import { SoftwareUpdatesCard } from "@app/components/shared/config/configSections/preferences/SoftwareUpdatesCard";+import { HotkeysCard } from "@app/components/shared/config/configSections/preferences/HotkeysCard";+import type {+ DesktopInstall,+ DesktopUpdateModeControl,+} from "@app/components/shared/config/configSections/preferences/preferencesCardProps";+import "@app/components/shared/config/configSections/preferences/PreferencesSection.css";++export interface PreferencesSectionProps {+ /** SaaS: login is always on, so the "turn login on" banner never applies. */+ hideAdminBanner?: boolean;+ /** SaaS build and managed-disabled desktop: no update UI, and no update call. */+ hideUpdateSection?: boolean;+ desktopInstall?: DesktopInstall;+ desktopUpdateMode?: DesktopUpdateModeControl;+ /**+ * The Account and Two-factor cards. Core has no accounts, so the flavors that+ * do pass them in (AccountCards) rather than core reaching into proprietary.+ * The slot supplies its own `<section>` wrappers and anchors.+ */+ accountSlot?: ReactNode;+ /** Extra rows under Editor defaults: login landing, desktop file defaults. */+ editorDefaultsSlot?: ReactNode;+}++/** True when the URL deep-links at the shortcuts card, which starts collapsed. */+function focusIsHotkeys(): boolean {+ const anchor = window.location.hash.replace(/^#/, "");+ return anchor === "hotkeys" || anchor.startsWith("setting-hotkeys");+}++/**+ * Everything you set for yourself, previously three nav rows (General, Keyboard+ * Shortcuts and Account). None of them saves through the admin API, so this page+ * has no draft and no save footer: every control writes as you touch it.+ *+ * The old General row was one unlabelled card of unrelated controls; it is split+ * into Appearance, Editor defaults, Downloads and Software updates so each can+ * be linked to. Shortcuts stays last and collapsed: it renders a row per+ * registered tool and would otherwise bury everything above it.+ */+export default function PreferencesSection({+ hideAdminBanner = false,+ hideUpdateSection = false,+ desktopInstall,+ desktopUpdateMode,+ accountSlot,+ editorDefaultsSlot,+}: PreferencesSectionProps) {+ const { t } = useTranslation();+ const { config } = useAppConfig();+ const startHotkeysOpen = focusIsHotkeys();++ // Same condition the standalone section used: a version to report, or the+ // desktop updater. Not mounting the card is what skips the update check.+ const showUpdates =+ !hideUpdateSection && Boolean(config?.appVersion || desktopInstall);++ return (+ <div className="settings-section-container">+ <div className="preferences-section">+ {!hideAdminBanner && <AdminSetupBanner />}++ {accountSlot}++ <SettingsCard+ id="appearance"+ title={t("settings.preferences.appearance", "Appearance")}+ >+ <AppearanceCard />+ </SettingsCard>++ <SettingsCard+ id="editorDefaults"+ title={t("settings.preferences.editorDefaults", "Editor defaults")}+ >+ <EditorDefaultsCard />+ {editorDefaultsSlot}+ </SettingsCard>++ <SettingsCard+ id="downloads"+ title={t("settings.preferences.downloads", "Downloads")}+ >+ <DownloadsCard />+ </SettingsCard>++ {showUpdates && (+ <SettingsCard+ id="softwareUpdates"+ title={t("settings.general.updates.title", "Software Updates")}+ >+ <SoftwareUpdatesCard+ desktopInstall={desktopInstall}+ desktopUpdateMode={desktopUpdateMode}+ />+ </SettingsCard>+ )}++ <SettingsCard+ id="hotkeys"+ title={t("settings.hotkeys.title", "Keyboard Shortcuts")}+ description={t(+ "settings.hotkeys.description",+ 'Customize keyboard shortcuts for quick tool access. Click "Change shortcut" and press a new key combination. Press Esc to cancel.',+ )}+ // A row per registered tool, so it stays shut and unmounted until asked for.+ defaultCollapsed={!startHotkeysOpen}+ lazy+ >+ <HotkeysCard />+ </SettingsCard>+ </div>+ </div>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/SoftwareUpdatesCard.tsx b/frontend/editor/src/core/components/shared/config/configSections/preferences/SoftwareUpdatesCard.tsxnew file mode 100644index 0000000000..89db01e612--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/SoftwareUpdatesCard.tsx@@ -0,0 +1,308 @@+import { useEffect, useId, useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { Badge, Group, Paper, Select, Stack, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import LocalIcon from "@app/components/shared/LocalIcon";+import UpdateModal from "@app/components/shared/UpdateModal";+import { updateService, UpdateSummary } from "@app/services/updateService";+import { useFrontendVersionInfo } from "@app/hooks/useFrontendVersionInfo";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { SoftwareUpdatesCardProps } from "@app/components/shared/config/configSections/preferences/preferencesCardProps";++/**+ * Version information and the update check. The page decides whether this card+ * exists at all, so mounting it is what arms the on-open check.+ */+export function SoftwareUpdatesCard({+ desktopInstall,+ desktopUpdateMode,+}: SoftwareUpdatesCardProps) {+ const { t } = useTranslation();+ const labelIds = useId();+ const updateModeLabelId = `${labelIds}-update-mode`;+ const { config } = useAppConfig();+ const [updateSummary, setUpdateSummary] = useState<UpdateSummary | null>(+ null,+ );+ const [updateModalOpened, setUpdateModalOpened] = useState(false);+ const [checkingUpdate, setCheckingUpdate] = useState(false);+ const { appVersion, mismatchVersion } = useFrontendVersionInfo(+ config?.appVersion,+ );+ const frontendVersionLabel = appVersion ?? t("common.loading", "Loading..."); // null = loading, shown only when appVersion !== undefined++ // The version update checks run against: the Tauri app version on desktop,+ // falling back to the backend version.+ const currentVersion = appVersion ?? config?.appVersion ?? null;++ // Check for updates on mount. The card is not rendered at all when the update+ // UI is hidden (SaaS build, managed-disabled desktop), so no call ever fires.+ useEffect(() => {+ if (currentVersion) {+ checkForUpdate();+ }+ }, [currentVersion, config?.machineType]);++ const checkForUpdate = async () => {+ if (!currentVersion) return;++ setCheckingUpdate(true);++ const machineInfo = {+ machineType: config?.machineType ?? "unknown",+ activeSecurity: config?.activeSecurity ?? false,+ licenseType: config?.license ?? "NORMAL",+ };++ const summary = await updateService.getUpdateSummary(+ currentVersion,+ machineInfo,+ );++ if (+ summary?.latest_version &&+ updateService.compareVersions(summary.latest_version, currentVersion) > 0+ ) {+ setUpdateSummary(summary);+ } else {+ setUpdateSummary(null);+ }++ setCheckingUpdate(false);+ };++ // Build desktop install props for the UpdateModal (only when provided by desktop override)+ const desktopInstallProps = desktopInstall?.tauriInstallReady+ ? {+ state: desktopInstall.state,+ progress: desktopInstall.progress,+ errorMessage: desktopInstall.errorMessage,+ canInstall: desktopInstall.canInstall,+ actions: desktopInstall.actions,+ }+ : undefined;++ return (+ <>+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Group justify="space-between" align="center">+ <Text size="xs" c="dimmed">+ {t(+ "settings.general.updates.description",+ "Check for updates and view version information",+ )}+ </Text>+ {updateSummary && (+ <Badge+ color={updateSummary.max_priority === "urgent" ? "red" : "blue"}+ variant="filled"+ >+ {updateSummary.max_priority === "urgent"+ ? t("update.urgentUpdateAvailable", "Urgent Update")+ : t("update.updateAvailable", "Update Available")}+ </Badge>+ )}+ </Group>+ {appVersion !== undefined && (+ <Group justify="space-between" align="center">+ <div>+ <Text size="sm" c="dimmed">+ {t(+ "settings.general.updates.currentFrontendVersion",+ "Current Frontend Version",+ )}+ :{" "}+ <Text component="span" fw={500}>+ {frontendVersionLabel}+ </Text>+ </Text>+ {mismatchVersion && (+ <Text size="sm" c="var(--color-red-dark)" mt={4}>+ {t(+ "settings.general.updates.versionMismatch",+ "Warning: A mismatch has been detected between the client version and the AppConfig version. Using different versions can lead to compatibility issues, errors, and security risks. Please ensure that server and client are using the same version.",+ )}+ </Text>+ )}+ </div>+ </Group>+ )}+ <Group justify="space-between" align="center">+ <div>+ {config?.appVersion && (+ <Text size="sm" c="dimmed">+ {t(+ "settings.general.updates.currentBackendVersion",+ "Current Backend Version",+ )}+ :{" "}+ <Text component="span" fw={500}>+ {config.appVersion}+ </Text>+ </Text>+ )}+ {updateSummary && (+ <Text size="sm" c="dimmed" mt={4}>+ {t(+ "settings.general.updates.latestVersion",+ "Latest Version",+ )}+ :{" "}+ <Text component="span" fw={500} c="var(--c-accent-text)">+ {updateSummary.latest_version}+ </Text>+ </Text>+ )}+ </div>+ <Group gap="sm">+ <Button+ size="sm"+ variant="secondary"+ onClick={checkForUpdate}+ loading={checkingUpdate}+ disabled={!currentVersion}+ leftSection={+ <LocalIcon+ icon="refresh-rounded"+ width="1rem"+ height="1rem"+ />+ }+ >+ {t(+ "settings.general.updates.checkForUpdates",+ "Check for Updates",+ )}+ </Button>+ {updateSummary && (+ <Button+ size="sm"+ accent={+ updateSummary.max_priority === "urgent"+ ? "danger"+ : "default"+ }+ onClick={() => setUpdateModalOpened(true)}+ leftSection={+ <LocalIcon+ icon="system-update-alt-rounded"+ width="1rem"+ height="1rem"+ />+ }+ >+ {t("settings.general.updates.viewDetails", "View Details")}+ </Button>+ )}+ </Group>+ </Group>++ {/* Desktop-only: update behaviour selector (prompt / auto / disabled).+ Rendered disabled with a "Managed by administrator" hint when the+ mode was pinned by a provisioning file. */}+ {desktopUpdateMode && (+ <Stack gap="xs">+ <Group gap="xs" align="center">+ <Text id={updateModeLabelId} fw={600} size="sm">+ {t(+ "settings.general.updates.updateBehavior",+ "Update behavior",+ )}+ </Text>+ {desktopUpdateMode.locked && (+ // `color="gray" variant="light"` rendered as near-invisible+ // light-on-dark in dark mode. `blue light` has enough+ // contrast in both themes to read clearly without being+ // shouty.+ <Badge color="blue" variant="light" size="sm" radius="sm">+ {t(+ "settings.general.updates.managedByAdmin",+ "Managed by administrator",+ )}+ </Badge>+ )}+ <InfoTooltip+ label={+ desktopUpdateMode.locked+ ? t(+ "settings.general.updates.updateBehaviorLockedDescription",+ "Your administrator has configured how Stirling-PDF handles updates on this machine. Contact them to change this.",+ )+ : t(+ "settings.general.updates.updateBehaviorDescription",+ "Choose whether to prompt before installing updates, install them automatically, or skip update checks entirely.",+ )+ }+ />+ </Group>+ <Select+ aria-labelledby={updateModeLabelId}+ disabled={desktopUpdateMode.locked}+ value={desktopUpdateMode.mode}+ onChange={(value) => {+ if (!value) return;+ void desktopUpdateMode.onChange(+ value as "prompt" | "auto" | "disabled",+ );+ }}+ data={[+ {+ value: "prompt",+ label: t(+ "settings.general.updates.modePrompt",+ "Ask me before installing updates",+ ),+ },+ {+ value: "auto",+ label: t(+ "settings.general.updates.modeAuto",+ "Install updates automatically",+ ),+ },+ {+ value: "disabled",+ label: t(+ "settings.general.updates.modeDisabled",+ "Don't check for updates",+ ),+ },+ ]}+ maw={360}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />+ </Stack>+ )}+ </Stack>+ </Paper>++ {/* Update Modal */}+ {updateSummary && (+ <UpdateModal+ opened={updateModalOpened}+ onClose={() => setUpdateModalOpened(false)}+ onRemindLater={() => {+ localStorage.setItem(+ "stirling-pdf-updater:snoozedUntil",+ String(Date.now() + 24 * 60 * 60 * 1000),+ );+ }}+ currentVersion={appVersion ?? config?.appVersion ?? ""}+ updateSummary={updateSummary}+ machineInfo={{+ machineType: config?.machineType ?? "unknown",+ activeSecurity: config?.activeSecurity ?? false,+ licenseType: config?.license ?? "NORMAL",+ }}+ desktopInstall={desktopInstallProps}+ />+ )}+ </>+ );+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/preferences/preferencesCardProps.ts b/frontend/editor/src/core/components/shared/config/configSections/preferences/preferencesCardProps.tsnew file mode 100644index 0000000000..805fe24764--- /dev/null+++ b/frontend/editor/src/core/components/shared/config/configSections/preferences/preferencesCardProps.ts@@ -0,0 +1,42 @@+import type {+ DesktopInstallActions,+ DesktopInstallCanInstall,+ DesktopInstallProgress,+ DesktopInstallState,+} from "@app/components/shared/UpdateModal";++/**+ * Desktop-only: user-facing update policy control, rendered inside the Software+ * updates card alongside the version info. Passed down from the desktop+ * GeneralSection override so this core component never imports a Tauri API.+ */+export interface DesktopUpdateModeControl {+ /** Current mode. */+ mode: "prompt" | "auto" | "disabled";+ /** `true` when the mode was written by a provisioning file - disables the control. */+ locked: boolean;+ /** Called when the user picks a new mode. Async: surface errors via toast. */+ onChange: (mode: "prompt" | "auto" | "disabled") => Promise<void> | void;+}++/** Desktop-only: Tauri updater install state, passed from the desktop override. */+export interface DesktopInstall {+ state: DesktopInstallState;+ progress: DesktopInstallProgress | null;+ errorMessage: string | null;+ tauriInstallReady: boolean;+ /** Result of the `can_install_updates` probe, used to show an inline warning+ * when msiexec would need UAC elevation this user doesn't have. */+ canInstall?: DesktopInstallCanInstall | null;+ actions: DesktopInstallActions;+}++/**+ * What the Software updates card needs from the page that owns it. Every other+ * preferences card reads its own context (preferences, theme, app config) and+ * writes straight through, so this is the only card with props.+ */+export interface SoftwareUpdatesCardProps {+ desktopInstall?: DesktopInstall;+ desktopUpdateMode?: DesktopUpdateModeControl;+}diff --git a/frontend/editor/src/core/components/shared/config/configSections/providerDefinitions.ts b/frontend/editor/src/core/components/shared/config/configSections/providerDefinitions.tsindex 98d2b3844c..5b56a022c5 100644--- a/frontend/editor/src/core/components/shared/config/configSections/providerDefinitions.ts+++ b/frontend/editor/src/core/components/shared/config/configSections/providerDefinitions.ts@@ -16,8 +16,13 @@ export interface ProviderField {defaultValue?: FieldValue;}+/** Signing in with this provider, versus wiring the server to another service. */+export type ProviderCategory = "signin" | "integration";+export interface Provider {id: string;+ /** Which settings page lists it; defaults to "signin" when unset. */+ category?: ProviderCategory;name: string;icon: string;type: ProviderType;@@ -335,6 +340,7 @@ const useSMTPProvider = (): Provider => {return {id: "smtp",+ category: "integration",name: t("provider.smtp.name", "SMTP Mail"),icon: "mail-rounded",type: "oauth2",@@ -409,6 +415,7 @@ const useTelegramProvider = (): Provider => {return {id: "telegram",+ category: "integration",name: t("admin.settings.telegram.title", "Telegram Bot"),icon: "send-rounded",type: "telegram",@@ -809,6 +816,7 @@ const useGoogleDriveProvider = (): Provider => {return {id: "googledrive",+ category: "integration",name: t("provider.googledrive.name", "Google Drive"),icon: "/images/google-drive.svg",type: "googledrive",diff --git a/frontend/editor/src/core/components/shared/AppConfigModal.css b/frontend/editor/src/core/components/shared/config/settingsSections.csssimilarity index 98%rename from frontend/editor/src/core/components/shared/AppConfigModal.cssrename to frontend/editor/src/core/components/shared/config/settingsSections.cssindex 1f2246c8f5..364858ef2c 100644--- a/frontend/editor/src/core/components/shared/AppConfigModal.css+++ b/frontend/editor/src/core/components/shared/config/settingsSections.css@@ -1,4 +1,5 @@-/* AppConfigModal styles */+/* Styles shared by every settings section, and the section chrome the settings+ page draws around them. *//* Deep-link highlight: pulses the control the super search jumped to(navigated via /settings/{section}?focus={anchor}). */diff --git a/frontend/editor/src/core/components/shared/config/types.ts b/frontend/editor/src/core/components/shared/config/types.tsindex 6b7d62192d..d7381b8400 100644--- a/frontend/editor/src/core/components/shared/config/types.ts+++ b/frontend/editor/src/core/components/shared/config/types.ts@@ -37,12 +37,22 @@ export const VALID_NAV_KEYS = ["adminAiModels","adminAiDocuments","adminAiLimits",+ // Holds all four AI rows above; they stay listed so their deep links alias.+ "adminAi","help","legal","backendThirdPartyLicenses","frontendThirdPartyLicenses",+ // Holds all four of the rows above; they stay listed so their deep links alias.+ "about","payg","account-link",+ // Server administration moved off the processor's own nav (see+ // portalSettingsSections).+ "users",+ "billing",+ "audit",+ "storage",] as const;// Derive the type from the array@@ -56,15 +66,32 @@ export type NavKey = (typeof VALID_NAV_KEYS)[number];export interface ConfigNavItem {key: NavKey;label: string;+ /** One line under the page title. The page owns the header; sections don't repeat it. */+ description?: string;icon: string;component: React.ReactNode;disabled?: boolean;disabledTooltip?: string;badge?: string;badgeColor?: string;+ /**+ * The section draws its own page header and gutters, so the settings page+ * gives it the whole pane and keeps only the chrome it can't provide (the+ * mobile back button).+ */+ fullBleed?: boolean;}export interface ConfigNavSection {+ /** Stable across languages and layers: merge target, and the key the fold state is remembered under. */+ id?: string;title: string;items: ConfigNavItem[];+ /**+ * Where this group's items land when it merges into a group that already+ * exists (see mergeSettingsGroups). "lead" (the default) is for items that+ * stand in for superseded ones and should hold their place; "append" is for+ * additions, and for replacements of something that sat at the bottom.+ */+ mergeAt?: "lead" | "append";}diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsxindex a0b990cd6c..a5cd864c56 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.noFileProvider.test.tsx@@ -31,7 +31,7 @@ function renderInProcessorShape() {initialConfig={{ enableEasterEggs: true }}><QuickNavHostProvider>- <QuickNavHostBridge portalAccess onOpenSettings={() => {}} />+ <QuickNavHostBridge portalAccess /></QuickNavHostProvider></AppConfigProvider></QueryClientProvider>diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsxindex 6eeb140623..ca9af1a22b 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx@@ -20,7 +20,6 @@ export interface QuickNavHostBridgeProps {portalAccess?: boolean;readerMode?: boolean;onSetReaderMode?: (on: boolean) => void;- onOpenSettings: () => void;requestNavigation?: (go: () => void) => void;onGoToDefaultState?: () => void;onSelectTool?: (toolId: ToolId) => void;@@ -34,7 +33,6 @@ export function QuickNavHostBridge({portalAccess = false,readerMode = false,onSetReaderMode,- onOpenSettings,requestNavigation,onSelectTool,activeTool = null,@@ -71,7 +69,6 @@ export function QuickNavHostBridge({toolReasons: mergedToolReasons,},{- openSettings: onOpenSettings,requestNavigation,selectTool: onSelectTool,setReaderMode: onSetReaderMode,diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.css b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.cssindex c12a6a1f71..6901fa193b 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.css+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.css@@ -27,3 +27,8 @@outline: 0.125rem solid var(--c-primary);outline-offset: 0.125rem;}++/* Current-destination ring, echoing the edge bar the app entries use. */+.quick-nav-rail-account[data-active] .quick-nav-rail-avatar {+ box-shadow: 0 0 0 0.125rem var(--c-accent-fg, var(--c-primary));+}diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsxindex 1404925de6..7c89fd0227 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailAccount.tsx@@ -5,24 +5,27 @@ import type { QuickNavIdentity } from "@app/contexts/QuickNavHostContext";import "@app/components/shared/quickNav/QuickNavRailAccount.css";export interface QuickNavRailAccountProps {- onOpenSettings: () => void;+ onOpen: () => void;/** Null between apps; the disc still renders, so the bar keeps its shape. */identity: QuickNavIdentity | null;+ /** Drawn as the current destination while the settings page is open. */+ active?: boolean;}-/** The avatar opens settings, so there is no separate gear beside it. */+/** The avatar is the only way into settings, and lands on your own account. */export function QuickNavRailAccount({- onOpenSettings,+ onOpen,identity,+ active = false,}: QuickNavRailAccountProps) {const { t } = useTranslation();const displayName =identity?.displayName ?? t("auth.displayName.user", "User");const profilePictureUrl = identity?.profilePictureUrl ?? null;- const label = `${displayName} — ${t("fileSidebar.openSettings", "Open settings")}`;+ const label = `${displayName} — ${t("quickNav.account", "Account")}`;return (- <div className="quick-nav-rail-account">+ <div className="quick-nav-rail-account" data-active={active || undefined}><Tooltip content={label} position="right" arrow>{/* A span, not the Avatar: Tooltip binds by cloning its child. */}<span@@ -34,8 +37,9 @@ export function QuickNavRailAccount({src={profilePictureUrl ?? undefined}name={displayName}size="sm"- onClick={onOpenSettings}+ onClick={onOpen}ariaLabel={label}+ ariaCurrent={active ? "page" : undefined}className="quick-nav-rail-avatar"/></span>diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsxindex 5c0be45db0..bc1cb082b9 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsx@@ -22,6 +22,8 @@ export interface QuickNavEntry {controls?: string;/** "danger" waits on the user; "warning" is awareness only. */badgeTone?: "danger" | "warning";+ /** Stable hook for tests and tours. */+ testId?: string;onClick: () => void;}@@ -43,6 +45,7 @@ export function RailButton({current,expanded,controls,+ testId,onClick,}: Omit<QuickNavEntry, "id">) {return (@@ -62,6 +65,7 @@ export function RailButton({aria-controls={expanded === undefined ? undefined : controls}// aria-disabled, not `disabled`: stays focusable, so its tooltip is reachable.aria-disabled={disabled || undefined}+ data-testid={testId}onClick={disabled ? undefined : onClick}>{icon}diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsxindex 154700518e..bcbd12b0e1 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx@@ -22,7 +22,12 @@ export interface QuickNavRailContainerProps extends Omit<"footer"> {/** The rail owns the account control, so the sidebars drop their own row. */- onOpenSettings?: () => void;+ onOpenAccount?: () => void;+ /** Marks the avatar current for the whole settings page, which it now owns. */+ accountActive?: boolean;+ /** Omitted in builds with no docs to browse. */+ onOpenDocs?: () => void;+ docsActive?: boolean;/** Omitted in builds with no processor to invite anyone into. */onInvite?: () => void;onToggleNotifications?: () => void;@@ -33,7 +38,10 @@ export interface QuickNavRailContainerProps extends Omit</** The fixed-width column the rail sits in. */export function QuickNavRailContainer({- onOpenSettings,+ onOpenAccount,+ accountActive = false,+ onOpenDocs,+ docsActive = false,onInvite,onToggleNotifications,notificationsOpen,@@ -68,10 +76,34 @@ export function QuickNavRailContainer({onClick={onInvite}/>)}- {onOpenSettings && (+ {onOpenDocs && (+ <RailButton+ label={t("quickNav.docs", "Documentation")}+ icon={+ docsActive ? (+ <LocalIcon+ icon="help-rounded"+ width="1.125rem"+ height="1.125rem"+ />+ ) : (+ <LocalIcon+ icon="help-outline-rounded"+ width="1.125rem"+ height="1.125rem"+ />+ )+ }+ current={docsActive}+ testId="docs-button"+ onClick={onOpenDocs}+ />+ )}+ {onOpenAccount && (<QuickNavRailAccount- onOpenSettings={onOpenSettings}+ onOpen={onOpenAccount}identity={identity}+ active={accountActive}/>)}</div>diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsxindex e7a1b6e8c6..c3d8741843 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx@@ -13,10 +13,16 @@ import {import { EDITOR_BASENAME } from "@app/routes/editorBasename";import { PORTAL_BASENAME } from "@app/routes/portalBasename";import { HAS_PORTAL } from "@app/routes/hasPortal";+import { DOCS_PATH, HAS_DOCS } from "@app/routes/docsRoute";+import { stripBasePath } from "@app/constants/app";+import { rememberSettingsOrigin } from "@app/utils/settingsNavigation";const SIZE = "1.125rem";/** Entries come from the URL, not either app's context, so the rail survives a switch. */+/** Interpolated, not inlined: a literal "#acc…" reads as a hex colour to theme-lint. */+const ACCOUNT_ANCHOR = "account";+export function QuickNavRailHost() {const { t } = useTranslation();const navigate = useNavigate();@@ -25,7 +31,13 @@ export function QuickNavRailHost() {const appMounted = Boolean(host?.appMounted);- const inPortal = pathname.startsWith(PORTAL_BASENAME);+ const path = stripBasePath(pathname);+ const inSettings = path.startsWith("/settings");+ const inDocs = path.startsWith(DOCS_PATH);+ const inPortal = path.startsWith(PORTAL_BASENAME);+ // Settings and the docs browser are pages in their own right, so neither app+ // is the current one while you are on them.+ const inEditor = !inPortal && !inSettings && !inDocs;// Only the app knows its own default state.const returnHome = () => {@@ -55,50 +67,76 @@ export function QuickNavRailHost() {return { disabled: Boolean(reason), reason };};- const apps: QuickNavEntry[] = [- {- id: "processor",- label: t("quickNav.processor", "Processor"),- // Two literals, not a computed name: the offline icon bundle scans for `icon="..."`.- icon: inPortal ? (- <LocalIcon icon="memory-rounded" width={SIZE} height={SIZE} />- ) : (- <LocalIcon icon="memory-outline-rounded" width={SIZE} height={SIZE} />- ),- current: inPortal,- disabled: HAS_PORTAL && !inPortal && !host?.portalAccess,- reason:- HAS_PORTAL && !inPortal && !host?.portalAccess- ? t("quickNav.noProcessorAccess", "Ask an admin for processor access")- : undefined,- onClick: () => {- if (inPortal) {- returnHome();- return;- }- saveEditorReturnPath();- go(PORTAL_BASENAME);- },+ // The three apps you switch between. Reader is a mode over the editor rather+ // than a place of its own, but it leads the group because it is where most+ // visits start.+ const reader: QuickNavEntry = {+ id: "reader",+ label: t("quickNav.reader", "Reader"),+ icon: (+ <LocalIcon icon="menu-book-outline-rounded" width={SIZE} height={SIZE} />+ ),+ pressed: Boolean(host?.readerMode),+ // From the processor there is no editor to toggle - see pendingReaderMode.+ onClick: () => {+ const setMode = host?.actions.current?.setReaderMode;+ if (setMode) {+ setMode(!host?.readerMode);+ return;+ }+ requestReaderMode();+ go(EDITOR_BASENAME);},- {- id: "editor",- label: t("quickNav.editor", "Editor"),- icon: inPortal ? (- <LocalIcon icon="edit-outline-rounded" width={SIZE} height={SIZE} />- ) : (- <LocalIcon icon="edit-rounded" width={SIZE} height={SIZE} />- ),- current: !inPortal,- onClick: () => {- if (!inPortal) {- returnHome();- return;- }- // Back to where you left the editor, not its front door.- navigate(takeEditorReturnPath() ?? EDITOR_BASENAME);- },+ };++ const editor: QuickNavEntry = {+ id: "editor",+ label: t("quickNav.editor", "Editor"),+ icon: inEditor ? (+ <LocalIcon icon="edit-rounded" width={SIZE} height={SIZE} />+ ) : (+ <LocalIcon icon="edit-outline-rounded" width={SIZE} height={SIZE} />+ ),+ current: inEditor,+ onClick: () => {+ if (inEditor) {+ returnHome();+ return;+ }+ // Back to where you left the editor, not its front door.+ navigate(takeEditorReturnPath() ?? EDITOR_BASENAME);},- ];+ };++ const processor: QuickNavEntry = {+ id: "processor",+ label: t("quickNav.processor", "Processor"),+ // Two literals, not a computed name: the offline icon bundle scans for `icon="..."`.+ icon: inPortal ? (+ <LocalIcon icon="memory-rounded" width={SIZE} height={SIZE} />+ ) : (+ <LocalIcon icon="memory-outline-rounded" width={SIZE} height={SIZE} />+ ),+ current: inPortal,+ disabled: HAS_PORTAL && !inPortal && !host?.portalAccess,+ reason:+ HAS_PORTAL && !inPortal && !host?.portalAccess+ ? t("quickNav.noProcessorAccess", "Ask an admin for processor access")+ : undefined,+ onClick: () => {+ if (inPortal) {+ returnHome();+ return;+ }+ if (inEditor) saveEditorReturnPath();+ go(PORTAL_BASENAME);+ },+ };++ // Editor and processor only pair off where there is a processor to reach.+ const apps: QuickNavEntry[] = HAS_PORTAL+ ? [reader, editor, processor]+ : [reader];const within: QuickNavEntry[] = [{@@ -109,28 +147,6 @@ export function QuickNavRailHost() {),onClick: () => go("/files"),},- {- id: "reader",- label: t("quickNav.reader", "Reader"),- icon: (- <LocalIcon- icon="menu-book-outline-rounded"- width={SIZE}- height={SIZE}- />- ),- pressed: Boolean(host?.readerMode),- // From the processor there is no editor to toggle - see pendingReaderMode.- onClick: () => {- const setMode = host?.actions.current?.setReaderMode;- if (setMode) {- setMode(!host?.readerMode);- return;- }- requestReaderMode();- go(EDITOR_BASENAME);- },- },{id: "automate",label: t("quickAccess.automate", "Automate"),@@ -155,18 +171,36 @@ export function QuickNavRailHost() {},];- // Read at click time, so it's always the mounted app's.- const openSettings = () => host?.actions.current?.openSettings?.();+ // Reference material, not a workspace: it sits at the foot of the bar under a+ // question mark rather than competing with the apps for the top.+ const openDocs = HAS_DOCS ? () => go(DOCS_PATH) : undefined;++ // The avatar is the only way into settings now, so it lands on the account+ // section and the page's own nav carries the rest. Inside settings it is a+ // tab switch (replace); from an app it is a navigation.+ const openAccount = () => {+ const target = `/settings/general#${ACCOUNT_ANCHOR}`;+ if (inSettings) {+ navigate(target, { replace: true });+ return;+ }+ rememberSettingsOrigin();+ go(target);+ };// A route that isn't the app hides the bar - see useSuppressQuickNavRail.if (!appMounted || host?.chromeless) return null;return (<QuickNavRailContainer- groups={HAS_PORTAL ? [apps, within] : [within]}+ groups={[apps, within]}onReturnHome={returnHome}identity={host?.identity ?? null}- onOpenSettings={host?.hasSettings ? openSettings : undefined}+ onOpenAccount={openAccount}+ // The avatar stands for the whole page, not just its own section.+ accountActive={inSettings}+ onOpenDocs={openDocs}+ docsActive={inDocs}onInvite={// Spelt out: VIEW_PATHS lives in the portal, which core cannot import.HAS_PORTAL && host?.portalAccessdiff --git a/frontend/editor/src/core/contexts/FolderContext.test.tsx b/frontend/editor/src/core/contexts/FolderContext.test.tsxindex efa3cd8dc0..9090731e93 100644--- a/frontend/editor/src/core/contexts/FolderContext.test.tsx+++ b/frontend/editor/src/core/contexts/FolderContext.test.tsx@@ -351,10 +351,11 @@ describe("FolderContext stale-folder 404 cleanup", () => {</FolderProvider></MemoryRouter>,);+ // Wait on the captured api, not just the DOM: the count renders on commit+ // but apiRef is filled by a passive effect, so asserting the text alone can+ // hand back the initial render's api, whose folder map is still empty.await waitFor(() =>- expect(screen.getByTestId("count").textContent).toBe(- String(initial.length),- ),+ expect(apiRef.current?.folderCount).toBe(initial.length),);if (!apiRef.current) throw new Error("ApiProbe never reported ready");expect(apiRef.current.folderCount).toBe(initial.length);diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsxindex 0a348262fa..66b1fee411 100644--- a/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.test.tsx@@ -14,7 +14,7 @@ function Probe({ onRead }: { onRead: (value: unknown) => void }) {chromeless: host?.chromeless,identity: host?.identity,activeTool: host?.activeTool,- openSettings: Boolean(host?.actions.current?.openSettings),+ goToDefaultState: Boolean(host?.actions.current?.goToDefaultState),});return null;}@@ -22,7 +22,7 @@ function Probe({ onRead }: { onRead: (value: unknown) => void }) {function App() {useRegisterQuickNavHost({ identity: { displayName: "Ada", profilePictureUrl: null } },- { openSettings: () => {} },+ { goToDefaultState: () => {} },);return null;}@@ -58,7 +58,7 @@ describe("QuickNavHostContext", () => {displayName: "Ada",profilePictureUrl: null,});- expect(read().openSettings).toBe(true);+ expect(read().goToDefaultState).toBe(true);view.rerender(<QuickNavHostProvider>@@ -74,7 +74,7 @@ describe("QuickNavHostContext", () => {</QuickNavHostProvider>,);expect(after.appMounted).toBe(true);- expect(after.openSettings).toBe(false);+ expect(after.goToDefaultState).toBe(false);});it("clears the open tool when the next app registers without one", () => {diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.tsxindex 9fe409c78b..8aa113c3f4 100644--- a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx@@ -29,12 +29,9 @@ export interface QuickNavHostData {notificationsOpen: boolean;/** Translated; absent means usable. */toolReasons: QuickNavToolReasons;- /** Mirrors `openSettings`, which lives in a ref and so cannot trigger a render. */- hasSettings: boolean;}export interface QuickNavHostActions {- openSettings?: () => void;/** The editor reads its tool from the URL only on mount. */selectTool?: (toolId: ToolId) => void;setReaderMode?: (on: boolean) => void;@@ -70,7 +67,6 @@ const EMPTY_DATA: QuickNavHostData = {readerMode: false,activeTool: null,notificationsOpen: false,- hasSettings: false,};function sameReasons(@@ -100,7 +96,6 @@ export function QuickNavHostProvider({ children }: { children: ReactNode }) {merged.readerMode === prev.readerMode &&merged.activeTool === prev.activeTool &&merged.notificationsOpen === prev.notificationsOpen &&- merged.hasSettings === prev.hasSettings &&merged.identity?.displayName === prev.identity?.displayName &&merged.identity?.profilePictureUrl ===prev.identity?.profilePictureUrl &&@@ -156,8 +151,6 @@ export function useRegisterQuickNavHost(notificationsOpen,toolReasons,} = data;- const hasSettings = Boolean(actions.openSettings);-useEffect(() => {host?.setData({appMounted: true,@@ -170,7 +163,6 @@ export function useRegisterQuickNavHost(notificationsOpen: notificationsOpen ?? false,// Omitted when unknown, so the last answer survives a re-fetch....(toolReasons ? { toolReasons } : {}),- hasSettings,});// By field: identity is rebuilt every render.}, [@@ -183,7 +175,6 @@ export function useRegisterQuickNavHost(activeTool,notificationsOpen,toolReasons,- hasSettings,]);const setActions = host?.setActions;diff --git a/frontend/editor/src/core/data/settingsAliases.ts b/frontend/editor/src/core/data/settingsAliases.tsnew file mode 100644index 0000000000..ea8e261f3e--- /dev/null+++ b/frontend/editor/src/core/data/settingsAliases.ts@@ -0,0 +1,29 @@+import type { NavKey } from "@app/components/shared/config/types";++/**+ * Retired section keys and the section that now holds their content, so a+ * bookmark or search result for a folded row still lands on the right page+ * instead of falling through to whichever row happens to be first.+ *+ * Core owns this because folds happen in core: the portal's own alias map is+ * merged over it, never substituted for it, so a build without the processor+ * still resolves these.+ */+export const BASE_SECTION_ALIASES: Partial<Record<string, NavKey>> = {+ help: "about",+ legal: "about",+ backendThirdPartyLicenses: "about",+ frontendThirdPartyLicenses: "about",+ adminAiGeneral: "adminAi",+ adminAiModels: "adminAi",+ adminAiDocuments: "adminAi",+ adminAiLimits: "adminAi",+ hotkeys: "general",+ account: "general",+ adminFeatures: "adminGeneral",+ adminStorageSharing: "adminGeneral",+ adminFolderAccess: "adminGeneral",+ adminEndpoints: "adminGeneral",+ adminMcp: "adminConnections",+ adminPrivacy: "adminLegal",+};diff --git a/frontend/editor/src/core/data/settingsContentSearch.ts b/frontend/editor/src/core/data/settingsContentSearch.tsindex 7cee4d6056..edadf47a83 100644--- a/frontend/editor/src/core/data/settingsContentSearch.ts+++ b/frontend/editor/src/core/data/settingsContentSearch.ts@@ -19,37 +19,32 @@ import type { TFunction } from "i18next";* prefix.*/const SECTION_TRANSLATION_PREFIXES: Partial<Record<string, string[]>> = {- general: ["settings.general"],- hotkeys: ["settings.hotkeys"],- account: ["account"],+ general: ["settings.general", "settings.hotkeys", "account"],people: ["settings.workspace"],teams: ["settings.workspace", "settings.team"],"api-keys": ["settings.developer"],connectionMode: ["settings.connection"],planBilling: ["settings.planBilling"],- adminGeneral: ["admin.settings.general"],- adminFeatures: ["admin.settings.features"],- adminEndpoints: ["admin.settings.endpoints"],- adminDatabase: ["admin.settings.database"],+ adminGeneral: [+ "admin.settings.general",+ "admin.settings.features",+ "admin.settings.endpoints",+ "admin.settings.storageSharing",+ "admin.settings.folderAccess",+ ],adminAdvanced: ["admin.settings.advanced"],- adminFolderAccess: ["admin.settings.folderAccess"],- // The four AI tabs all render slices of the one admin.settings.ai subtree.- adminAiGeneral: ["admin.settings.ai"],- adminAiModels: ["admin.settings.ai"],- adminAiDocuments: ["admin.settings.ai"],- adminAiLimits: ["admin.settings.ai"],- adminSecurity: ["admin.settings.security"],- adminMcp: ["admin.settings.mcp"],+ adminDatabase: ["admin.settings.database"],+ // One page now, so one entry: mapping four keys at the same subtree returned+ // four byte-identical results for every AI query.+ adminAi: ["admin.settings.ai"],+ adminSecurity: ["admin.settings.security", "admin.settings.connections"],adminConnections: ["admin.settings.connections","admin.settings.mail",- "admin.settings.security","admin.settings.telegram",- "admin.settings.premium",- "admin.settings.general",- "settings.securityAuth",- "settings.connection",+ "admin.settings.mcp",],+ adminLegal: ["admin.settings.legal", "admin.settings.privacy"],adminPlan: ["settings.planBilling","admin.settings.premium",@@ -57,8 +52,6 @@ const SECTION_TRANSLATION_PREFIXES: Partial<Record<string, string[]>> = {],adminAudit: ["settings.licensingAnalytics"],adminUsage: ["settings.licensingAnalytics"],- adminLegal: ["admin.settings.legal"],- adminPrivacy: ["admin.settings.privacy"],};export const getTranslationPrefixesForNavKey = (key: string): string[] => {diff --git a/frontend/editor/src/core/data/settingsSearchIndex.ts b/frontend/editor/src/core/data/settingsSearchIndex.tsindex c130546a8a..cb43c46498 100644--- a/frontend/editor/src/core/data/settingsSearchIndex.ts+++ b/frontend/editor/src/core/data/settingsSearchIndex.ts@@ -5,7 +5,7 @@ import { NavKey } from "@app/components/shared/config/types";** Section-level content matching (settingsContentSearch) only navigates to a* whole section; this index lets the global super search deep-link to an- * individual control: navigating to `/settings/{section}?focus={anchor}`,+ * individual control: navigating to `/settings/{section}#{anchor}`,* where `anchor` is the DOM `id` placed on that control's row (see* AppConfigModal's focus-scroll effect and the `id=` attributes added to the* matching section components).@@ -13,7 +13,7 @@ import { NavKey } from "@app/components/shared/config/types";export interface SettingsSearchEntry {/** Settings section this row lives in (nav key, e.g. "general"). */section: NavKey;- /** DOM id on the control's row; used as the `?focus=` anchor. */+ /** DOM id on the control's row, and its `#slug` in the URL. */anchor: string;/** i18n key for the display label. */labelKey: string;@@ -96,10 +96,180 @@ export const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = [},// --- Keyboard Shortcuts ---{- section: "hotkeys",+ section: "general",anchor: "setting-hotkeys-search",labelKey: "settings.hotkeys.title",labelFallback: "Keyboard Shortcuts",keywords: ["hotkey", "shortcut", "keybinding", "keyboard"],},+ // --- About: one row per card the four folded rows became, carrying the+ // labels and search terms those rows had.+ {+ section: "about",+ anchor: "help",+ labelKey: "settings.help.label",+ labelFallback: "Tours",+ keywords: ["tour", "walkthrough", "guide", "onboarding", "help"],+ },+ {+ section: "about",+ anchor: "legal",+ labelKey: "settings.legal.label",+ labelFallback: "Legal",+ keywords: ["terms", "privacy", "policy", "cookie", "consent", "gdpr"],+ },+ {+ section: "about",+ anchor: "frontendThirdPartyLicenses",+ labelKey: "settings.licenses.frontendLabel",+ labelFallback: "Frontend Licenses",+ keywords: [+ "licence",+ "license",+ "attribution",+ "dependencies",+ "open source",+ ],+ },+ {+ section: "about",+ anchor: "backendThirdPartyLicenses",+ labelKey: "settings.licenses.backendLabel",+ labelFallback: "Backend Licenses",+ keywords: [+ "licence",+ "license",+ "attribution",+ "dependencies",+ "open source",+ ],+ },+ // --- AI engine: one row per card the four folded rows became.+ {+ section: "adminAi",+ anchor: "adminAiGeneral",+ labelKey: "admin.settings.ai.general.connection",+ labelFallback: "Connection",+ keywords: ["ai", "engine", "url", "timeout", "enable", "connection"],+ },+ {+ section: "adminAi",+ anchor: "adminAiCapabilities",+ labelKey: "admin.settings.ai.general.capabilities.title",+ labelFallback: "Capabilities",+ keywords: ["chat", "features", "classify", "math", "comment"],+ },+ {+ section: "adminAi",+ anchor: "adminAiModels",+ labelKey: "settings.ai.models",+ labelFallback: "Models & Providers",+ keywords: ["llm", "openai", "anthropic", "ollama", "model", "provider"],+ },+ {+ section: "adminAi",+ anchor: "adminAiDocuments",+ labelKey: "settings.ai.documents",+ labelFallback: "Documents & RAG",+ keywords: ["rag", "embedding", "retrieval", "vector", "index", "search"],+ },+ {+ section: "adminAi",+ anchor: "adminAiLimits",+ labelKey: "settings.ai.limits",+ labelFallback: "Limits & Performance",+ keywords: ["tokens", "rate", "concurrency", "guardrail", "performance"],+ },+ // --- Anchors for the rows the folds retired; each lands on its host card.+ {+ section: "general",+ anchor: "hotkeys",+ labelKey: "settings.hotkeys.title",+ labelFallback: "Keyboard Shortcuts",+ keywords: ["hotkey", "shortcut", "keybinding", "keyboard"],+ },+ {+ section: "general",+ anchor: "account",+ labelKey: "account.accountSettings",+ labelFallback: "Account",+ keywords: [+ "account",+ "password",+ "username",+ "profile",+ "mfa",+ "two factor",+ ],+ },+ {+ section: "adminGeneral",+ anchor: "adminEndpoints",+ labelKey: "settings.configuration.endpoints",+ labelFallback: "Endpoints",+ keywords: ["endpoint", "api", "routes", "disable tool"],+ },+ {+ section: "adminGeneral",+ anchor: "adminStorageSharing",+ labelKey: "settings.configuration.storageSharing",+ labelFallback: "File Storage & Sharing",+ keywords: ["storage", "sharing", "share link", "quota"],+ },+ {+ section: "adminGeneral",+ anchor: "adminFolderAccess",+ labelKey: "settings.configuration.folderAccess",+ labelFallback: "Folder Access",+ keywords: ["folder", "directory", "path", "allowlist"],+ },+ {+ section: "adminGeneral",+ anchor: "adminFeatures",+ labelKey: "admin.settings.features.serverCertificate.label",+ labelFallback: "Certificate Signing",+ keywords: ["certificate", "signing", "sign with stirling"],+ },+ {+ section: "adminConnections",+ anchor: "adminMcp",+ labelKey: "settings.configuration.mcp",+ labelFallback: "MCP Server",+ keywords: ["mcp", "model context protocol", "tools"],+ },+ {+ section: "adminConnections",+ anchor: "adminConnections",+ labelKey: "settings.configuration.connections",+ labelFallback: "Single sign-on",+ keywords: ["sso", "saml", "oauth", "google", "keycloak", "smtp", "mail"],+ },+ {+ section: "adminLegal",+ anchor: "adminPrivacy",+ labelKey: "settings.configuration.privacy",+ labelFallback: "Privacy",+ keywords: ["privacy", "analytics", "tracking", "robots", "metrics"],+ },+ {+ section: "adminLegal",+ anchor: "adminLegal",+ labelKey: "settings.configuration.legal",+ labelFallback: "Legal documents",+ keywords: ["legal", "terms", "privacy policy", "cookie"],+ },+ {+ section: "adminSecurity",+ anchor: "auditLogging",+ labelKey: "settings.licensingAnalytics.audit",+ labelFallback: "Audit log",+ keywords: ["audit", "log", "retention", "events"],+ },+ {+ section: "adminDatabase",+ anchor: "adminDatabase",+ labelKey: "settings.configuration.database",+ labelFallback: "Database",+ keywords: ["database", "postgres", "h2", "backup", "restore", "datasource"],+ },];diff --git a/frontend/editor/src/core/data/settingsSectionRegistry.ts b/frontend/editor/src/core/data/settingsSectionRegistry.tsindex e2222d4daf..933dec1204 100644--- a/frontend/editor/src/core/data/settingsSectionRegistry.ts+++ b/frontend/editor/src/core/data/settingsSectionRegistry.ts@@ -49,6 +49,8 @@ export interface SettingsSectionEntry {* which keys off the local backend's login mode rather than auth state.*/requiresAccount?: boolean;+ /** Section is the processor's; only a session that can enter it sees it. */+ requiresPortalAccess?: boolean;}/** Core (OSS) sections — always present in every build. */@@ -57,32 +59,38 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [key: "general",labelKey: "settings.general.title",labelFallback: "General",- keywords: ["theme", "language", "appearance", "preferences", "startup"],+ keywords: [+ "theme",+ "language",+ "appearance",+ "preferences",+ "startup",+ "hotkey",+ "shortcut",+ "keybinding",+ "keyboard",+ ],groupLabelKey: "settings.preferences.title",groupLabelFallback: "Preferences",},{- key: "hotkeys",- labelKey: "settings.hotkeys.title",- labelFallback: "Keyboard Shortcuts",- keywords: ["hotkey", "shortcut", "keybinding", "keyboard"],- groupLabelKey: "settings.preferences.title",- groupLabelFallback: "Preferences",- },- {- key: "help",- labelKey: "settings.help.label",- labelFallback: "Tours",- keywords: ["help", "tour", "guide", "support", "docs"],- groupLabelKey: "settings.help.title",- groupLabelFallback: "Help",- },- {- key: "legal",- labelKey: "settings.legal.label",- labelFallback: "Legal",- keywords: ["legal", "terms", "privacy", "licenses"],- groupLabelKey: "settings.legal.title",- groupLabelFallback: "Legal",+ key: "about",+ labelKey: "settings.about.title",+ labelFallback: "About",+ keywords: [+ "about",+ "tours",+ "walkthrough",+ "legal",+ "terms",+ "privacy",+ "cookie",+ "licence",+ "license",+ "attribution",+ "dependencies",+ ],+ groupLabelKey: "settings.about.title",+ groupLabelFallback: "About",},];diff --git a/frontend/editor/src/core/data/settingsSectionTargets.test.ts b/frontend/editor/src/core/data/settingsSectionTargets.test.tsnew file mode 100644index 0000000000..913d3ef122--- /dev/null+++ b/frontend/editor/src/core/data/settingsSectionTargets.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import { BASE_SECTION_ALIASES } from "@app/data/settingsAliases";+import { SETTINGS_SEARCH_INDEX } from "@app/data/settingsSearchIndex";++/**+ * Sections keep folding into one another, and both tables address a page by its+ * nav key. A key that stops being a row leaves the alias pointing at the wrong+ * page and the search result landing on the wrong one — invisible until someone+ * follows the link, because the URL still resolves.+ */+describe("settings section targets", () => {+ const retired = new Set(Object.keys(BASE_SECTION_ALIASES));++ it("never aliases a key to another retired key", () => {+ const chained = Object.entries(BASE_SECTION_ALIASES)+ .filter(([, target]) => !target || retired.has(target))+ .map(([key, target]) => `${key} -> ${target}`);+ expect(chained).toEqual([]);+ });++ it("never files a search row under a retired key", () => {+ const stale = SETTINGS_SEARCH_INDEX.filter((e) =>+ retired.has(e.section),+ ).map((e) => `${e.anchor} -> ${e.section}`);+ expect(stale).toEqual([]);+ });++ // A folded section becomes an anchor on the page that absorbed it, so the+ // bookmark and the search result have to arrive at the same page.+ it("sends a retired key and its anchor to the same page", () => {+ const disagreeing = SETTINGS_SEARCH_INDEX.filter(+ (e) =>+ retired.has(e.anchor) && BASE_SECTION_ALIASES[e.anchor] !== e.section,+ ).map(+ (e) =>+ `${e.anchor}: alias -> ${BASE_SECTION_ALIASES[e.anchor]}, index -> ${e.section}`,+ );+ expect(disagreeing).toEqual([]);+ });+});diff --git a/frontend/editor/src/portal/docs/headings.test.ts b/frontend/editor/src/core/docs/headings.test.tssimilarity index 95%rename from frontend/editor/src/portal/docs/headings.test.tsrename to frontend/editor/src/core/docs/headings.test.tsindex 8069fa2fef..e20259829f 100644--- a/frontend/editor/src/portal/docs/headings.test.ts+++ b/frontend/editor/src/core/docs/headings.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { extractHeadings, slugify } from "@portal/docs/headings";+import { extractHeadings, slugify } from "@app/docs/headings";describe("slugify", () => {it("lowercases, hyphenates, and trims punctuation", () => {diff --git a/frontend/editor/src/portal/docs/headings.ts b/frontend/editor/src/core/docs/headings.tssimilarity index 100%rename from frontend/editor/src/portal/docs/headings.tsrename to frontend/editor/src/core/docs/headings.tsdiff --git a/frontend/editor/src/portal/docs/manifest/registry.ts b/frontend/editor/src/core/docs/manifest/registry.tssimilarity index 90%rename from frontend/editor/src/portal/docs/manifest/registry.tsrename to frontend/editor/src/core/docs/manifest/registry.tsindex 730367f87e..6fe8e2de5d 100644--- a/frontend/editor/src/portal/docs/manifest/registry.ts+++ b/frontend/editor/src/core/docs/manifest/registry.ts@@ -5,12 +5,12 @@*/// Imported as a raw string (not a JSON module) so tsc doesn't infer a ~half-MB// literal type; parsed once here into the typed manifest.-import manifestRaw from "@portal/generated/docsManifest.json?raw";+import manifestRaw from "@app/generated/docsManifest.json?raw";import type {DocEntry,DocsManifest,DocsNavSection,-} from "@portal/docs/manifest/transform";+} from "@app/docs/manifest/transform";const manifest = JSON.parse(manifestRaw) as DocsManifest;diff --git a/frontend/editor/src/portal/docs/manifest/transform.test.ts b/frontend/editor/src/core/docs/manifest/transform.test.tssimilarity index 99%rename from frontend/editor/src/portal/docs/manifest/transform.test.tsrename to frontend/editor/src/core/docs/manifest/transform.test.tsindex 5bc105f7ef..1dac40b377 100644--- a/frontend/editor/src/portal/docs/manifest/transform.test.ts+++ b/frontend/editor/src/core/docs/manifest/transform.test.ts@@ -14,7 +14,7 @@ import {stripRedundantH1,type CategoryMap,type RawDoc,-} from "@portal/docs/manifest/transform";+} from "@app/docs/manifest/transform";const OPTS = {repo: "Owner/Repo",diff --git a/frontend/editor/src/portal/docs/manifest/transform.ts b/frontend/editor/src/core/docs/manifest/transform.tssimilarity index 99%rename from frontend/editor/src/portal/docs/manifest/transform.tsrename to frontend/editor/src/core/docs/manifest/transform.tsindex 60ced60ee4..74fedb53e9 100644--- a/frontend/editor/src/portal/docs/manifest/transform.ts+++ b/frontend/editor/src/core/docs/manifest/transform.ts@@ -13,7 +13,7 @@*//* ──────────────────────────────────────────────────────────────────────── */-/* Manifest shape (mirrored structurally by @portal/api/docs) */+/* Manifest shape (mirrored structurally by the portal API types) *//* ──────────────────────────────────────────────────────────────────────── */export interface DocsNavItem {diff --git a/frontend/editor/src/portal/docs/search.test.ts b/frontend/editor/src/core/docs/search.test.tssimilarity index 99%rename from frontend/editor/src/portal/docs/search.test.tsrename to frontend/editor/src/core/docs/search.test.tsindex 84d7c53c76..8f1d7c10bc 100644--- a/frontend/editor/src/portal/docs/search.test.ts+++ b/frontend/editor/src/core/docs/search.test.ts@@ -5,7 +5,7 @@ import {searchDocs,toPlainText,type SearchDoc,-} from "@portal/docs/search";+} from "@app/docs/search";const DOCS: SearchDoc[] = [{diff --git a/frontend/editor/src/portal/docs/search.ts b/frontend/editor/src/core/docs/search.tssimilarity index 100%rename from frontend/editor/src/portal/docs/search.tsrename to frontend/editor/src/core/docs/search.tsdiff --git a/frontend/editor/src/portal/generated/docsManifest.json b/frontend/editor/src/core/generated/docsManifest.jsonsimilarity index 100%rename from frontend/editor/src/portal/generated/docsManifest.jsonrename to frontend/editor/src/core/generated/docsManifest.jsondiff --git a/frontend/editor/src/core/hooks/useCookieConsent.ts b/frontend/editor/src/core/hooks/useCookieConsent.tsindex 660485f2d5..95e66b9bf1 100644--- a/frontend/editor/src/core/hooks/useCookieConsent.ts+++ b/frontend/editor/src/core/hooks/useCookieConsent.ts@@ -29,16 +29,6 @@ interface CookieConsentConfig {analyticsEnabled?: boolean;}-// Shard so Mantine's scroll-lock doesn't swallow events on the consent dialog;-// lazy because #cc-main only exists post-load.-export const COOKIE_CONSENT_SCROLL_SHARD = {- get current(): HTMLElement | null {- return typeof document === "undefined"- ? null- : document.getElementById("cc-main");- },-};-export const useCookieConsent = ({analyticsEnabled = false,}: CookieConsentConfig = {}) => {diff --git a/frontend/editor/src/core/hooks/usePortalAccess.ts b/frontend/editor/src/core/hooks/usePortalAccess.tsnew file mode 100644index 0000000000..6cdb3bfe5f--- /dev/null+++ b/frontend/editor/src/core/hooks/usePortalAccess.ts@@ -0,0 +1,24 @@+/**+ * Whether the current user can reach the processor. The one seam every+ * consumer asks, so the settings nav, the super search and the app switcher+ * can never disagree - each build answers it from whichever session actually+ * carries the flag.+ *+ * `settled` is false only while the answer is still being fetched: callers+ * that would act on "no access" (hiding a section, redirecting a deep link)+ * must wait for it rather than treat a pending lookup as a denial.+ *+ * Core ships no processor, so the answer is always no, and always settled.+ */+export interface PortalAccessState {+ granted: boolean;+ settled: boolean;+}++export function usePortalAccessState(): PortalAccessState {+ return { granted: false, settled: true };+}++export function usePortalAccess(): boolean {+ return usePortalAccessState().granted;+}diff --git a/frontend/editor/src/core/hooks/useSuperSearch.ts b/frontend/editor/src/core/hooks/useSuperSearch.tsindex 9f6a16f2f4..dcbfadc966 100644--- a/frontend/editor/src/core/hooks/useSuperSearch.ts+++ b/frontend/editor/src/core/hooks/useSuperSearch.ts@@ -15,6 +15,7 @@ import { useAuth } from "@app/auth/UseSession";import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";import { useNavigationActions } from "@app/contexts/NavigationContext";import { ViewerContext } from "@app/contexts/ViewerContext";+import { usePortalAccess } from "@app/hooks/usePortalAccess";import { useAppConfig } from "@app/contexts/AppConfigContext";import { useFileActions } from "@app/contexts/file/fileHooks";import { fileStorage } from "@app/services/fileStorage";@@ -97,18 +98,21 @@ export function isProcessorGateOpen(gates: SuperSearchGates | null): boolean {export function useSuperSearchGates(): SuperSearchGates | null {const authState = useAuth();const { config } = useAppConfig();+ // Through the seam, not authState: on SaaS the editor's Supabase session+ // carries no permission flags, so reading it here hid every processor lane.+ const portalAccessible = usePortalAccess();return useMemo(() =>config? {isAdmin: authState.isAdmin ?? config.isAdmin ?? false,loginEnabled: config.enableLogin ?? false,- portalAccessible: authState.portalAccess ?? false,+ portalAccessible,isAnonymous: authState.isAnonymous,showSettingsWhenNoLogin: config.showSettingsWhenNoLogin ?? true,}: null,- [authState.isAdmin, authState.isAnonymous, authState.portalAccess, config],+ [authState.isAdmin, authState.isAnonymous, portalAccessible, config],);}@@ -152,7 +156,9 @@ export function useEditorSearchScopes(): SuperSearchScope[] {},...PORTAL_ENTITY_SCOPE_DEFS.filter((def) =>- visibleViewIds.has(def.viewId) &&+ // A settings-hosted entity is reachable wherever the processor is.+ (def.settingsKey !== undefined ||+ visibleViewIds.has(def.viewId)) &&isPortalEntityScopeAccessible(def.id, gates?.isAdmin ?? false),).map((def) => ({id: def.id,@@ -299,17 +305,13 @@ export function rankSettingsResults(gates: SuperSearchGates | null,openSettings: (section: string, anchor?: string) => void,limit = GROUP_RESULT_CEILING,- /** Sections the host's settings modal refuses to show (e.g. the portal's- * hiddenSectionKeys) — offering them would deep-link into a blank modal. */- excludeSections?: readonly string[],): SuperSearchResult[] {if (!trimmed) return [];- // Sections gated like the modal nav. The registry resolves per build+ // Sections gated like the settings nav. The registry resolves per build// (core / proprietary / saas / desktop), so this only ever sees sections- // the current build's settings modal can actually show.+ // the current build's settings page can actually show.const visibleSections = SETTINGS_SECTION_REGISTRY.filter((s) => {- if (excludeSections?.includes(s.key)) return false;// Null gates (config still loading): hide every gated section.// requiresLogin keys off the deployment's login *mode*, mirroring the nav// builder: with login on the editor is login-walled (an unauthenticated@@ -327,6 +329,9 @@ export function rankSettingsResults(// Account-bound sections mirror the SaaS builder's `!isAnonymous` gate.if (s.requiresAccount && (gates ? (gates.isAnonymous ?? false) : true))return false;+ // The processor's own sections mirror its nav builder's portalAccess gate.+ if (s.requiresPortalAccess && gates?.portalAccessible !== true)+ return false;return true;});// Row context: the display label of the section the row lives in.@@ -334,7 +339,7 @@ export function rankSettingsResults(visibleSections.map((s) => [s.key, t(s.labelKey, s.labelFallback)]),);- // Row-level entries (deep-link with ?focus=) take priority. Rows for+ // Row-level entries (deep-link by slug) take priority. Rows for// sections this build/user can't open are dropped with them.const rowMatches = rankByFuzzy(SETTINGS_SEARCH_INDEX.filter((e) => sectionLabelFor.has(e.section)),@@ -569,7 +574,7 @@ export function useSuperSearch(const openSettings = useCallback((section: string, anchor?: string) => {const path = anchor- ? `/settings/${section}?focus=${encodeURIComponent(anchor)}`+ ? `/settings/${section}#${encodeURIComponent(anchor)}`: `/settings/${section}`;navigate(path);},diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsxindex bfd0f8d6d7..6e201b4908 100644--- a/frontend/editor/src/core/pages/HomePage.tsx+++ b/frontend/editor/src/core/pages/HomePage.tsx@@ -35,13 +35,12 @@ import Workbench from "@app/components/layout/Workbench";import FileSidebar from "@app/components/shared/FileSidebar";import FileManager from "@app/components/FileManager";import LocalIcon from "@app/components/shared/LocalIcon";-import AppConfigModal from "@app/components/shared/AppConfigModalLazy";import {getStartupNavigationAction,getDefaultWorkbenchForFileCount,} from "@app/utils/homePageNavigation";import { EDITOR_BASENAME } from "@app/routes/editorBasename";-import { stripBasePath } from "@app/constants/app";+import { rememberSettingsOrigin } from "@app/utils/settingsNavigation";import { HomePageExtensions } from "@app/components/home/HomePageExtensions";import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";@@ -127,7 +126,6 @@ export default function HomePage() {const sliderRef = useRef<HTMLDivElement | null>(null);const [activeMobileView, setActiveMobileView] = useState<MobileView>("tools");const isProgrammaticScroll = useRef(false);- const [configModalOpen, setConfigModalOpen] = useState(false);const otherApp = useOtherAppSwitch();const location = useLocation();// Persisted user preference for the FileSidebar collapsed state. Auto-@@ -135,45 +133,15 @@ export default function HomePage() {// doesn't write to storage, so deep-linking to /files won't overwrite what// the user actually chose last time.const [fileSidebarCollapsed, setFileSidebarCollapsed] = useState(- readPersistedSidebarCollapsed,+ // Reader mode outlives this page (settings swaps it out and back), and it+ // collapses the sidebar without persisting that, so it wins on mount too.+ () => readerMode || readPersistedSidebarCollapsed(),);- // Open the config modal whenever the URL is /settings/* (e.g. from the admin- // tour's openConfigModal action which navigates to /settings/overview).- useEffect(() => {- const isSettings = location.pathname.startsWith("/settings");- setConfigModalOpen(isSettings);- }, [location.pathname]);-- useEffect(() => {- const handler = () => setConfigModalOpen(true);- window.addEventListener("appConfig:open", handler);- return () => window.removeEventListener("appConfig:open", handler);- }, []);-- // Where the user was before settings opened, so close can restore it. Null- // when opened directly on a /settings URL (deep link) - close falls back to- // the editor root.- const settingsOriginRef = useRef<string | null>(null);- const wasConfigOpenRef = useRef(false);- useEffect(() => {- if (configModalOpen && !wasConfigOpenRef.current) {- settingsOriginRef.current = location.pathname.startsWith("/settings")- ? null- : location.pathname;- }- wasConfigOpenRef.current = configModalOpen;- }, [configModalOpen, location.pathname]);-- const handleCloseConfig = useCallback(() => {- // Restore the URL before clearing the flag, or a late /settings commit- // re-opens the modal. Read window.location, not useLocation: a tab switch- // updates the URL synchronously while the router's commit lags. Replace to- // the origin rather than navigate(-1), which webkit can drop.- if (stripBasePath(window.location.pathname).startsWith("/settings")) {- navigate(settingsOriginRef.current ?? EDITOR_BASENAME, { replace: true });- }- setConfigModalOpen(false);+ // Settings is its own page; it restores the recorded origin on Back.+ const openSettings = useCallback(() => {+ rememberSettingsOrigin();+ navigate("/settings");}, [navigate]);const { activeFiles } = useFileContext();@@ -522,7 +490,6 @@ export default function HomePage() {<HomePageExtensions /><QuickNavHostBridgeportalAccess={Boolean(otherApp)}- onOpenSettings={() => setConfigModalOpen(true)}requestNavigation={requestNavigation}readerMode={readerMode}onSetReaderMode={setReaderMode}@@ -687,7 +654,7 @@ export default function HomePage() {variant="tertiary"className="mobile-bottom-button"aria-label={t("quickAccess.config", "Config")}- onClick={() => setConfigModalOpen(true)}+ onClick={openSettings}><LocalIconicon="settings-rounded"@@ -700,10 +667,6 @@ export default function HomePage() {</Button></div><FileManager selectedTool={selectedTool} />- <AppConfigModal- opened={configModalOpen}- onClose={handleCloseConfig}- /></div>) : (<Group@@ -734,17 +697,13 @@ export default function HomePage() {fileSidebarCollapsed}onToggleCollapse={handleSidebarToggle}- onOpenSettings={() => setConfigModalOpen(true)}+ onOpenSettings={openSettings}/></div><FolderTreePanel active={navigationState.workbench === "myFiles"} /><Workbench />{!hideToolPanel && <RightSidebar />}<FileManager selectedTool={selectedTool} />- <AppConfigModal- opened={configModalOpen}- onClose={handleCloseConfig}- /></Group>)}</FilesPageProvider>diff --git a/frontend/editor/src/core/pages/SettingsPage.css b/frontend/editor/src/core/pages/SettingsPage.cssnew file mode 100644index 0000000000..5d8f6e83cb--- /dev/null+++ b/frontend/editor/src/core/pages/SettingsPage.css@@ -0,0 +1,328 @@+/* Full-page settings. The section stylesheet's `modal-*` class names are kept —+ every section component, the admin tour and the e2e suite target them — and+ restyled here at page scale: a sidebar beside a canvas, not a dialog. */++.settings-page {+ display: flex;+ height: 100%;+ min-height: 0;+ background: var(--c-bg);+ color: var(--c-text);+}++/* ---- Sidebar ---- */++.settings-page .settings-page__nav {+ width: 17.5rem;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ min-height: 0;+ border-radius: 0;+ background: var(--c-surface);+ border-inline-end: 1px solid var(--c-border-subtle);+}++.settings-page__nav-head {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ padding: var(--space-4) var(--space-3) var(--space-2);+ flex-shrink: 0;+}++.settings-page__nav-title {+ font-size: 1.0625rem;+ font-weight: 700;+ letter-spacing: -0.01em;+ color: var(--c-text);+}++.settings-page .modal-nav-scroll {+ padding: 0 var(--space-3) var(--space-6);+}++.settings-page .modal-nav-section {+ margin: 0;+ padding-top: var(--space-2);+}++/* Rule a real group, and the run of loose rows that follows one. Ruling every+ section instead just stripes the rail. */+.settings-page .modal-nav-section[data-group],+.settings-page+ .modal-nav-section[data-group]+ + .modal-nav-section:not([data-group]) {+ margin-top: var(--space-3);+ padding-top: var(--space-3);+ border-top: 1px solid var(--c-border-subtle);+}++.settings-page__group {+ margin: 0;+ padding: 0 var(--space-3) 0.15rem;+ font-size: 0.6875rem;+ font-weight: 500;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--c-text-subtle);+ opacity: 0.75;+}++.settings-page .modal-nav-section-items {+ margin-top: var(--space-1);+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+}++/* A button, so it's keyboard-reachable; the reset keeps the row shape. */+.settings-page .modal-nav-item {+ width: 100%;+ margin: 0;+ padding: 0 var(--space-3);+ min-height: 2.25rem;+ border: none;+ border-radius: var(--radius-nav);+ background: none;+ text-align: start;+ font: inherit;+ color: var(--c-text-muted);+ cursor: pointer;+ transition:+ background var(--motion-fast),+ color var(--motion-fast);+}++.settings-page .modal-nav-item:hover:not([aria-disabled="true"]) {+ background: var(--c-hover);+ color: var(--c-text);+}++.settings-page .modal-nav-item:focus-visible {+ outline: 2px solid var(--c-accent-fg, var(--c-primary));+ outline-offset: -2px;+}++.settings-page .modal-nav-item.active {+ background: var(--c-primary-subtle);+ color: var(--c-accent-fg, var(--c-primary));+}++.settings-page .modal-nav-item.active .settings-page__nav-label {+ font-weight: 600;+}++.settings-page .modal-nav-item[aria-disabled="true"] {+ opacity: 0.5;+ cursor: not-allowed;+}++.settings-page__nav-icon {+ flex-shrink: 0;+ color: var(--c-text-subtle);+}++.settings-page .modal-nav-item.active .settings-page__nav-icon,+.settings-page+ .modal-nav-item:hover:not([aria-disabled="true"])+ .settings-page__nav-icon {+ color: currentColor;+}++.settings-page__nav-label {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 0.875rem;+ font-weight: 500;+}++.settings-page__nav-warning {+ flex-shrink: 0;+ color: var(--c-warning);+}++/* ---- Content ---- */++/* The global search, unpainted at the top of the column - the processor's+ strip, so the bar sits in the same place in every app. */+.settings-page__search-bar {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 3.1875rem;+ padding: 0 1rem;+ flex-shrink: 0;+}++.settings-page__search-bar .super-search {+ flex: 0 1 24rem;+ width: min(100%, 24rem);+ max-width: 24rem;+}++.settings-page__search-bar .super-search input {+ background-color: transparent;+ padding-top: 4px;+ padding-bottom: 4px;+ font-size: 12.5px;+}++/* Canvas, with the sidebar as the solid panel beside it - the same relationship+ the editor and processor sidebars have with their content. */+.settings-page .settings-page__main {+ flex: 1;+ min-width: 0;+ background: var(--c-bg);+}++/* Readable measure, but the 2rem side gutter stays so the sections' sticky+ footers (which cancel it with a -2rem margin) still span the pane. */+.settings-page .modal-body {+ max-width: 60rem;+ margin-inline: auto;+ padding-top: 2.75rem;+ padding-bottom: 4rem;+}++/* The page owns every section's title: one voice, one size, one place. */+.settings-page__header {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ margin-bottom: var(--space-8);+}++.settings-page__eyebrow {+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--c-accent-fg, var(--c-primary));+}++.settings-page__title {+ margin: 0;+ font-size: 1.75rem;+ font-weight: 700;+ line-height: 1.2;+ letter-spacing: -0.015em;+ color: var(--c-text);+}++.settings-page__description {+ margin: var(--space-1) 0 0;+ max-width: 44rem;+ font-size: 0.9375rem;+ line-height: 1.5;+ color: var(--c-text-muted);+}++/* A section that draws its own header and gutters gets the whole pane. */+.settings-page .modal-body.is-full-bleed {+ max-width: none;+ padding: 0;+}++/* The mobile bar, hidden until the panes stack. */+.settings-page__mobile-bar {+ display: none;+}++/* ---- Mobile: the two panes become two screens ---- */++@media (max-width: 1024px) {+ .settings-page .settings-page__nav {+ width: 100%;+ border-inline-end: none;+ }++ .settings-page .settings-page__mobile-bar {+ display: flex;+ justify-content: flex-start;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ background: var(--c-bg);+ border-bottom: 1px solid var(--c-border-subtle);+ }++ .settings-page__mobile-bar-title {+ font-size: 0.8125rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--c-text-subtle);+ }++ .settings-page .modal-body {+ padding-top: var(--space-5);+ }++ .settings-page__header {+ margin-bottom: var(--space-6);+ }++ /* The bar above already names the group. */+ .settings-page__eyebrow {+ display: none;+ }++ .settings-page__title {+ font-size: 1.5rem;+ }+}++/* ── Cards of the open section, listed under its nav row ───────────────── */++.settings-page__subnav {+ list-style: none;+ margin: 0.125rem 0 0.375rem;+ padding: 0 0 0 1.75rem;+ display: flex;+ flex-direction: column;+ gap: 0.0625rem;+ /* One rule down the group, so the children read as belonging to the row. */+ border-inline-start: 1px solid var(--c-border-subtle);+ margin-inline-start: 1rem;+}++.settings-page__subnav-item {+ display: block;+ width: 100%;+ padding: 0.25rem 0.5rem;+ border: 0;+ border-radius: var(--radius-sm, 4px);+ background: none;+ color: var(--c-text-subtle);+ font-size: 0.8125rem;+ text-align: start;+ text-decoration: none;+ cursor: pointer;+}++.settings-page__subnav-item:hover {+ background: var(--c-hover);+ color: var(--c-text);+}++/* Follows the scroll, so the rail always says where you are. */+.settings-page__subnav-item[aria-current="true"] {+ color: var(--c-text);+ font-weight: 600;+ box-shadow: inset 2px 0 0 var(--c-accent-fg, var(--c-primary));+}++.settings-page__subnav-item:focus-visible {+ outline: 0.125rem solid var(--c-primary);+ outline-offset: -0.125rem;+}++/* The page's own (i) sits beside the title, not under it. */+.settings-page__title-row {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}diff --git a/frontend/editor/src/core/pages/SettingsPage.tsx b/frontend/editor/src/core/pages/SettingsPage.tsxnew file mode 100644index 0000000000..f5df738ca6--- /dev/null+++ b/frontend/editor/src/core/pages/SettingsPage.tsx@@ -0,0 +1,399 @@+import React, {+ useCallback,+ useEffect,+ useMemo,+ useState,+ Suspense,+} from "react";+import { useLocation, useNavigate } from "react-router-dom";+import { useTranslation } from "react-i18next";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import { useSectionHeadings } from "@app/components/settings/useSectionHeadings";+import { useActiveHeading } from "@app/components/settings/useActiveHeading";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";+import { Badge, Tooltip } from "@mantine/core";+import LocalIcon from "@app/components/shared/LocalIcon";+import { SettingsMobileBackButton } from "@app/components/shared/config/SettingsMobileBackButton";+import { SettingsNavChevron } from "@app/components/shared/config/SettingsNavChevron";+import { useSettingsNav } from "@app/components/settings/useSettingsNav";+import SuperSearch from "@app/components/shared/superSearch/SuperSearch";+import { useEditorSearchScopes } from "@app/hooks/useSuperSearch";+import type { NavKey } from "@app/components/shared/config/types";+import { useIsMobile } from "@app/hooks/useIsMobile";+import { useLicenseAlert } from "@app/hooks/useLicenseAlert";+import {+ UnsavedChangesProvider,+ useUnsavedChanges,+} from "@app/contexts/UnsavedChangesContext";+import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";+import { useOtherAppSwitch } from "@app/hooks/useOtherAppSwitch";+import { EDITOR_BASENAME } from "@app/routes/editorBasename";+import { stripBasePath } from "@app/constants/app";+import { takeSettingsOrigin } from "@app/utils/settingsNavigation";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import "@app/components/shared/config/settingsSections.css";+import "@app/pages/SettingsPage.css";++const ANCHOR_POLL_MS = 150;+const ANCHOR_WAIT_MS = 5000;++/** `/settings/people` -> "people". Null for `/settings` itself. */+function sectionFromPath(pathname: string): string | null {+ const match = stripBasePath(pathname).match(/\/settings\/([^/?#]+)/);+ return match?.[1] ?? null;+}++const SettingsPageInner: React.FC = () => {+ const { t } = useTranslation();+ const [contentRef, setContentRef] = useState<HTMLDivElement | null>(null);+ const navigate = useNavigate();+ const location = useLocation();+ const isMobile = useIsMobile();+ const licenseAlert = useLicenseAlert();+ const { confirmIfDirty } = useUnsavedChanges();+ // The rail sits outside every app, so each page tells it what only the+ // signed-in session knows.+ const otherApp = useOtherAppSwitch();+ // The same bar as the editor and the processor, so search is one thing+ // everywhere; settings results deep-link straight back into this page.+ const searchScopes = useEditorSearchScopes();+ const [mobilePane, setMobilePane] = useState<"nav" | "content">(() =>+ sectionFromPath(window.location.pathname) ? "content" : "nav",+ );+ // Leaving restores where the user came from (the editor, the processor,+ // wherever) by replacement, or the editor for a deep link with no origin.+ const leave = useCallback(() => {+ navigate(takeSettingsOrigin() ?? EDITOR_BASENAME, { replace: true });+ }, [navigate]);++ const { sections, overlay, aliases, pending } = useSettingsNav(leave);+ const items = useMemo(() => sections.flatMap((s) => s.items), [sections]);++ const urlSection = sectionFromPath(location.pathname);+ const activeItem = useMemo(+ () => items.find((i) => i.key === urlSection) ?? null,+ [items, urlSection],+ );+ const activeGroup = useMemo(+ () =>+ sections.find((s) => s.items.some((i) => i.key === activeItem?.key))+ ?.title,+ [sections, activeItem],+ );++ // The URL always names what is shown. `/settings` and an unknown key land on+ // the first section; a retired key (an old bookmark, an older search result)+ // follows its alias to whatever replaced it.+ useEffect(() => {+ // `pending` matters as much as an empty list: the permission-gated sections+ // arrive a request later, so a deep link to one of them is not unknown yet.+ if (items.length === 0 || activeItem || pending) return;+ const target =+ (urlSection && aliases?.[urlSection]) ??+ items.find((i) => !i.disabled)?.key ??+ items[0].key;+ // The hash rides along: an aliased bookmark addresses a control, and the+ // control it names is still there under whatever absorbed its section.+ navigate(`/settings/${target}${location.search}${location.hash}`, {+ replace: true,+ });+ }, [+ items,+ activeItem,+ pending,+ urlSection,+ aliases,+ location.search,+ location.hash,+ navigate,+ ]);++ // Replace, not push: Back should leave settings, not walk the tabs you opened.+ const switchSection = useCallback(+ (key: NavKey) => {+ navigate(`/settings/${key}`, { replace: true });+ },+ [navigate],+ );++ const handleNavigation = useCallback(+ async (key: NavKey) => {+ if (!(await confirmIfDirty())) return;+ switchSection(key);+ setMobilePane("content");+ },+ [confirmIfDirty, switchSection],+ );++ const handleMobileBack = useCallback(async () => {+ if (!(await confirmIfDirty())) return;+ setMobilePane("nav");+ }, [confirmIfDirty]);++ // The rail sits beside the page, so its entries are exits too.+ const requestNavigation = useCallback(+ (go: () => void) => {+ void confirmIfDirty().then((ok) => {+ if (ok) go();+ });+ },+ [confirmIfDirty],+ );++ // Sections dispatch `appConfig:navigate` to send the user to a sibling tab.+ useEffect(() => {+ const handler = (ev: Event) => {+ const key = (ev as CustomEvent<{ key?: NavKey }>).detail?.key;+ if (key) switchSection(key);+ };+ window.addEventListener("appConfig:navigate", handler as EventListener);+ return () =>+ window.removeEventListener(+ "appConfig:navigate",+ handler as EventListener,+ );+ }, [switchSection]);++ const headings = useSectionHeadings(activeItem?.key, contentRef);+ const { active: activeHeading, focus: focusHeading } = useActiveHeading(+ contentRef,+ headings,+ );++ const anchor = decodeURIComponent(location.hash.replace(/^#/, ""));+ const activeKey = activeItem?.key;++ // Deep link: /settings/{section}#{slug} scrolls to and briefly highlights one+ // control. The slug is the only address; the super search builds the same URL.+ //+ // Keyed on the section key, never on the item object: the nav builders return+ // fresh arrays each render, so depending on the item would re-arm the jump on+ // every scroll-spy re-render and pin the reader to the anchor. Sections mount+ // lazily, so it polls for the target instead of firing once and missing it.+ useEffect(() => {+ if (!anchor || !activeKey) return;+ let raf = 0;+ let timer = 0;+ const giveUpAt = Date.now() + ANCHOR_WAIT_MS;+ const attempt = () => {+ if (document.getElementById(anchor)) {+ raf = window.requestAnimationFrame(() => focusHeading(anchor));+ } else if (Date.now() < giveUpAt) {+ timer = window.setTimeout(attempt, ANCHOR_POLL_MS);+ }+ };+ timer = window.setTimeout(attempt, ANCHOR_POLL_MS);+ return () => {+ window.clearTimeout(timer);+ if (raf) window.cancelAnimationFrame(raf);+ };+ }, [activeKey, anchor, focusHeading]);++ // Sections that bring their own page header get the whole pane; on mobile the+ // bar stays anyway, because it carries the only way back to the list.+ const fullBleed = activeItem?.fullBleed ?? false;++ return (+ <div className="settings-page" data-tour="settings-modal">+ <QuickNavHostBridge+ portalAccess={Boolean(otherApp)}+ requestNavigation={requestNavigation}+ />++ <aside+ className={`settings-page__nav modal-nav ${isMobile ? "mobile" : ""}`}+ style={+ isMobile && mobilePane !== "nav" ? { display: "none" } : undefined+ }+ aria-label={t("settings.title", "Settings")}+ >+ <div className="settings-page__nav-head">+ <span className="settings-page__nav-title">+ {t("settings.title", "Settings")}+ </span>+ </div>++ <div className="modal-nav-scroll">+ {sections.map((section) => {+ const groupId = section.id ?? section.title;+ // A header that toggles a single row costs a line and a click to+ // show what it already named; the row stands on its own instead.+ const solo = section.items.length === 1;+ return (+ <div+ key={groupId}+ className="modal-nav-section"+ data-group={!solo || undefined}+ >+ {!solo && (+ // A plain label, not a disclosure: the rail is short enough+ // that hiding rows only cost a click to find them again.+ <h2 className="settings-page__group">{section.title}</h2>+ )}+ <div+ id={`settings-group-${groupId}`}+ className="modal-nav-section-items"+ >+ {section.items.map((item) => {+ const isActive = activeItem?.key === item.key;+ const isDisabled = item.disabled ?? false;+ const showPlanWarning =+ item.key === "adminPlan" &&+ licenseAlert.active &&+ licenseAlert.audience === "admin";+ const row = (+ <button+ type="button"+ onClick={() => {+ if (!isDisabled) void handleNavigation(item.key);+ }}+ className={`modal-nav-item ${isActive ? "active" : ""} ${isMobile ? "mobile" : ""}`}+ data-tour={`admin-${item.key}-nav`}+ aria-current={isActive ? "page" : undefined}+ // Not `disabled`: it stays focusable, so the tooltip+ // saying why it is off is reachable by keyboard.+ aria-disabled={isDisabled || undefined}+ >+ <LocalIcon+ icon={item.icon}+ width={18}+ height={18}+ className="settings-page__nav-icon"+ />+ <span className="settings-page__nav-label">+ {item.label}+ </span>+ {item.badge && (+ <Badge+ size="xs"+ variant="light"+ color={item.badgeColor ?? "orange"}+ className="modal-nav-item-badge"+ >+ {item.badge}+ </Badge>+ )}+ {showPlanWarning && (+ <LocalIcon+ icon="warning-rounded"+ width={14}+ height={14}+ className="settings-page__nav-warning"+ />+ )}+ <SettingsNavChevron show={isMobile} />+ </button>+ );+ return isDisabled && item.disabledTooltip ? (+ <Tooltip+ key={item.key}+ label={item.disabledTooltip}+ position="right"+ withArrow+ zIndex={Z_INDEX_OVER_CONFIG_MODAL}+ >+ {row}+ </Tooltip>+ ) : (+ <React.Fragment key={item.key}>+ {row}+ {isActive && headings.length > 1 && (+ <ul className="settings-page__subnav">+ {headings.map((h) => (+ <li key={h.id}>+ <a+ href={`#${h.id}`}+ className="settings-page__subnav-item"+ aria-current={+ activeHeading === h.id ? "true" : undefined+ }+ onClick={(event) => {+ event.preventDefault();+ focusHeading(h.id);+ }}+ >+ {h.label}+ </a>+ </li>+ ))}+ </ul>+ )}+ </React.Fragment>+ );+ })}+ </div>+ </div>+ );+ })}+ </div>+ </aside>++ <div+ className="settings-page__main modal-content"+ data-tour="settings-content-area"+ style={+ isMobile && mobilePane !== "content" ? { display: "none" } : undefined+ }+ >+ <div className="settings-page__search-bar">+ <SuperSearch+ inputId="settings-search-input"+ scopes={searchScopes}+ dropdownClassName="settings-search-dropdown"+ />+ </div>+ <div className="modal-content-scroll" ref={setContentRef}>+ {isMobile && (+ <div className="settings-page__mobile-bar modal-header">+ <SettingsMobileBackButton+ show+ onClick={() => void handleMobileBack()}+ />+ <span className="settings-page__mobile-bar-title">+ {activeGroup}+ </span>+ </div>+ )}+ <div className={`modal-body${fullBleed ? " is-full-bleed" : ""}`}>+ {activeItem && !fullBleed && (+ <header className="settings-page__header">+ {activeGroup && (+ <span className="settings-page__eyebrow">{activeGroup}</span>+ )}+ <div className="settings-page__title-row">+ <h1 className="settings-page__title">{activeItem.label}</h1>+ {activeItem.description && (+ <InfoTooltip+ label={activeItem.description}+ position="right"+ />+ )}+ </div>+ </header>+ )}+ {/* Once, here: every admin section used to draw this itself, so an+ admin with login off met the same block on all thirteen. */}+ <LoginRequiredBanner show={activeItem?.disabled ?? false} />+ {/* Its own boundary: a section that suspends must not take the+ nav and the header down with it. */}+ <Suspense fallback={<LoadingFallback />}>+ {activeItem?.component}+ </Suspense>+ </div>+ </div>+ </div>++ {overlay}+ </div>+ );+};++/** Full-page settings: account, preferences and every server setting. */+export default function SettingsPage() {+ return (+ <UnsavedChangesProvider>+ <SettingsPageInner />+ </UnsavedChangesProvider>+ );+}diff --git a/frontend/editor/src/core/routes/docsRoute.ts b/frontend/editor/src/core/routes/docsRoute.tsnew file mode 100644index 0000000000..297b886017--- /dev/null+++ b/frontend/editor/src/core/routes/docsRoute.ts@@ -0,0 +1,9 @@+/** Where the documentation browser lives, for links and the quick-nav rail. */+export const DOCS_PATH = "/docs";++/**+ * Whether this build ships the documentation browser. Every build does: the+ * manifest and the view live in core, so no edition has to resolve another+ * tree to render them.+ */+export const HAS_DOCS = true;diff --git a/frontend/editor/src/core/tests/helpers/api-stubs.ts b/frontend/editor/src/core/tests/helpers/api-stubs.tsindex 5477422ca6..944c6119da 100644--- a/frontend/editor/src/core/tests/helpers/api-stubs.ts+++ b/frontend/editor/src/core/tests/helpers/api-stubs.ts@@ -190,6 +190,13 @@ export async function mockAppApis(route.fulfill({ json: { user } }),);+ // The signed-in user's teams. Unstubbed this 401s, and the API client reads a+ // 401 here as an expired session: refresh, fail, bounce to /login - so any+ // page that asks (the login-landing setting, the account tab) logs out.+ await page.route("**/api/v1/team/my", (route: Route) =>+ route.fulfill({ json: [] }),+ );+// Tool availability — every tool enabled unless overriddenawait page.route("**/api/v1/config/endpoints-availability", (route: Route) =>route.fulfill({@@ -254,6 +261,36 @@ export async function mockAppApis(route.fulfill({ json: {} }),);+ // An empty section never gets a dirty-tracking snapshot, so anything that+ // compares saved-vs-current reads as unchanged. Give aiEngine real values.+ await page.route(+ "**/api/v1/admin/settings/section/aiEngine",+ (route: Route) =>+ route.fulfill({+ json: {+ enabled: false,+ url: "http://stirling-pdf-engine:5001",+ rag: { embeddingProvider: "voyageai", embeddingModel: "voyage-3" },+ },+ }),+ );++ // Folder access reads this on every visit to the System page; unstubbed it+ // 401s in a retry loop and the refresh failures sign the session out.+ await page.route(+ "**/api/v1/admin/settings/policies/implied-folder-roots",+ (route: Route) => route.fulfill({ json: { impliedRoots: [] } }),+ );++ // Same trap on the merged Legal and Advanced pages, which each pull in a+ // card that fetches on mount.+ await page.route("**/api/v1/admin/login-agreement/**", (route: Route) =>+ route.fulfill({ json: { content: "", enabled: false } }),+ );+ await page.route("**/api/v1/ui-data/tessdata-languages", (route: Route) =>+ route.fulfill({ json: { languages: [] } }),+ );+// Info sub-resourcesawait page.route("**/api/v1/info/wau", (route: Route) =>route.fulfill({ json: { count: 0 } }),diff --git a/frontend/editor/src/core/tests/helpers/ui-helpers.ts b/frontend/editor/src/core/tests/helpers/ui-helpers.tsindex 1ce62bd828..ba3f8a963d 100644--- a/frontend/editor/src/core/tests/helpers/ui-helpers.ts+++ b/frontend/editor/src/core/tests/helpers/ui-helpers.ts@@ -178,38 +178,66 @@ export async function runToolAndWaitForReview().toBeVisible({ timeout: reviewTimeout });}+/** The settings page's root. Settings is a route, not a dialog. */+export const SETTINGS_SURFACE = ".settings-page";+/**- * Open the global Settings dialog. Returns the dialog locator so callers can- * scope further queries to it.+ * Go to the global Settings page by the rail's avatar, the only entry there is,+ * which opens on the Account section. Pass `section` to land on a named one+ * instead. Returns the page's root locator so callers can scope further+ * queries to it.*/-export async function openSettings(page: Page): Promise<Locator> {+export async function openSettings(+ page: Page,+ section?: string | RegExp,+): Promise<Locator> {await page.locator('[data-testid="config-button"]').first().click();- const dialog = page.locator(".mantine-Modal-content").first();- await expect(dialog).toBeVisible({ timeout: 5_000 });- return dialog;+ const surface = page.locator(SETTINGS_SURFACE);+ await expect(surface).toBeVisible({ timeout: 5_000 });+ if (section) {+ await surface+ .locator(".modal-nav-item")+ .filter({ hasText: section })+ .first()+ .click();+ // The URL flips before React commits the section, so wait on the page+ // title rather than on the address bar.+ await expect(surface.locator(".settings-page__title")).toHaveText(section, {+ timeout: 5_000,+ });+ }+ return surface;}/**- * Close the Settings dialog via its built-in Close button and assert the- * dialog is fully dismissed before returning.+ * Leave Settings the way a reader does now that the nav has no Back control:+ * browser back, which lands on the origin because tab switches replace.*/export async function closeSettings(page: Page): Promise<void> {- const modal = page.locator(".mantine-Modal-content").first();- // A click on the X can be swallowed by a re-render, leaving the modal open;- // retry until it's gone. A genuinely broken close still fails - every retry- // misses and the modal stays past the cap.+ const surface = page.locator(SETTINGS_SURFACE);+ // Retry: one back can land on another /settings entry if a spec pushed one.await expect(async () => {- if (await modal.isVisible().catch(() => false)) {- await page- .locator('[aria-label="Close"]')- .first()- .click({ timeout: 2_000 })- .catch(() => {});+ if (await surface.isVisible().catch(() => false)) {+ await page.goBack({ timeout: 2_000 }).catch(() => {});}- await expect(modal).not.toBeVisible({ timeout: 2_000 });+ await expect(surface).not.toBeVisible({ timeout: 2_000 });}).toPass({ timeout: 12_000 });}+/** Unfold every sidebar group, for checks that scan the whole section list. */+export async function expandSettingsGroups(page: Page): Promise<void> {+ // Wait for the aside to render its groups first; evaluateAll on an empty set+ // is a silent no-op that surfaces later as an unrelated missing-item failure.+ await expect(+ page.locator(`${SETTINGS_SURFACE} .settings-page__group`).first(),+ ).toBeAttached({ timeout: 5_000 });+ await page+ .locator(`${SETTINGS_SURFACE} .settings-page__group[aria-expanded="false"]`)+ .evaluateAll((buttons) =>+ buttons.forEach((b) => (b as HTMLButtonElement).click()),+ );+}+/*** Dismiss the onboarding tour tooltip (`Watch walkthroughs here…`) when it's* blocking pointer events on firefox/webkit. No-op when absent.diff --git a/frontend/editor/src/core/tests/live/password-change.spec.ts b/frontend/editor/src/core/tests/live/password-change.spec.tsindex 5586558d63..a7bf8b173a 100644--- a/frontend/editor/src/core/tests/live/password-change.spec.ts+++ b/frontend/editor/src/core/tests/live/password-change.spec.ts@@ -6,13 +6,10 @@ test.describe("21. Password Change Flow", () => {test("should change password end-to-end", async ({ page }) => {await loginAndSetup(page);- // Open settings dialog- await page- .getByRole("button", { name: /settings/i })- .first()- .click();- const settingsDialog = page.locator(".mantine-Modal-content").first();- await expect(settingsDialog).toBeVisible({ timeout: 5000 });+ // Settings is reached by URL or the account menu; the rail has no cog.+ await page.goto("/settings");+ const settingsDialog = page.locator(".settings-page");+ await expect(settingsDialog).toBeVisible({ timeout: 30_000 });// Navigate to Account Settings sectionconst accountNav = page.getByText(/Account Settings/i).first();@@ -58,13 +55,10 @@ test.describe("21. Password Change Flow", () => {test("should reject mismatched passwords with error", async ({ page }) => {await loginAndSetup(page);- // Open settings dialog- await page- .getByRole("button", { name: /settings/i })- .first()- .click();- const settingsDialog = page.locator(".mantine-Modal-content").first();- await expect(settingsDialog).toBeVisible({ timeout: 5000 });+ // Settings is reached by URL or the account menu; the rail has no cog.+ await page.goto("/settings");+ const settingsDialog = page.locator(".settings-page");+ await expect(settingsDialog).toBeVisible({ timeout: 30_000 });// Navigate to Account Settings sectionconst accountNav = page.getByText(/Account Settings/i).first();diff --git a/frontend/editor/src/core/tests/live/username-change.spec.ts b/frontend/editor/src/core/tests/live/username-change.spec.tsindex 526dddda1f..f0a7657ac4 100644--- a/frontend/editor/src/core/tests/live/username-change.spec.ts+++ b/frontend/editor/src/core/tests/live/username-change.spec.ts@@ -6,13 +6,10 @@ test.describe("22. Username Change Flow", () => {test("should update username successfully", async ({ page }) => {await loginAndSetup(page);- // Open settings dialog- await page- .getByRole("button", { name: /settings/i })- .first()- .click();- const settingsDialog = page.locator(".mantine-Modal-content").first();- await expect(settingsDialog).toBeVisible({ timeout: 5000 });+ // Settings is reached by URL or the account menu; the rail has no cog.+ await page.goto("/settings");+ const settingsDialog = page.locator(".settings-page");+ await expect(settingsDialog).toBeVisible({ timeout: 30_000 });// Navigate to Account Settings sectionconst accountNav = page.getByText(/Account Settings/i).first();diff --git a/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.ts b/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.tsindex c268f8d134..d3336072ec 100644--- a/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@app/tests/helpers/stub-test-base";-import { uploadFiles } from "@app/tests/helpers/ui-helpers";+import { SETTINGS_SURFACE, uploadFiles } from "@app/tests/helpers/ui-helpers";import type { Page, Route } from "@playwright/test";import path from "node:path";import fs from "node:fs";@@ -291,20 +291,20 @@ async function openFormDetectionSettings(page: Page) {json: { username: "admin", email: "[email protected]", isAdmin: true },}),);- await page.goto("/", { waitUntil: "domcontentloaded" });+ await page.goto("/editor", { waitUntil: "domcontentloaded" });const configBtn = page.locator('[data-testid="config-button"]').first();await expect(configBtn).toBeVisible({ timeout: 15_000 });await configBtn.click();- const dialog = page.locator(".mantine-Modal-content").first();- await expect(dialog).toBeVisible({ timeout: 5_000 });- await dialog- .getByText(/^(Features|الميزات)$/)+ const settings = page.locator(SETTINGS_SURFACE);+ await expect(settings).toBeVisible({ timeout: 5_000 });+ await settings+ .locator('[data-tour="admin-adminGeneral-nav"]').first().click();- await expect(dialog.getByText(/AI Form Detection/i).first()).toBeVisible({+ await expect(settings.getByText(/AI Form Detection/i).first()).toBeVisible({timeout: 5_000,});- return dialog;+ return settings;}async function shootCard(@@ -312,13 +312,10 @@ async function shootCard(dialog: ReturnType<Page["locator"]>,name: string,) {- const paper = dialog- .locator(".mantine-Paper-root")- .filter({ hasText: "AI Form Detection" })- .last();- await paper.scrollIntoViewIfNeeded();+ const card = dialog.locator("section.settings-card:has(#adminFormDetection)");+ await card.scrollIntoViewIfNeeded();await settle(page);- await paper.screenshot({ path: shot(name) });+ await card.screenshot({ path: shot(name) });}test.describe("admin", () => {diff --git a/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.ts b/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.tsindex 74fd7f23b2..a88a14b032 100644--- a/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.ts@@ -4,6 +4,7 @@ import {mockAppApis,seedCookieConsent,} from "@app/tests/helpers/api-stubs";+import { SETTINGS_SURFACE } from "@app/tests/helpers/ui-helpers";/*** Stubbed coverage for the tool tile (shown even when the endpoint is disabled, so the tool stays@@ -70,7 +71,7 @@ test.describe("Auto Form Detection tool", () => {await expect(page).toHaveURL(/auto-form-detection/i);});- test("admin sees the AI Form Detection box inside the Features section", async ({+ test("admin sees the AI Form Detection box inside the System section", async ({page,}) => {await seedCookieConsent(page);@@ -98,7 +99,7 @@ test.describe("Auto Form Detection tool", () => {json: { username: "admin", email: "[email protected]", isAdmin: true },}),);- await page.goto("/");+ await page.goto("/editor");const configBtn = page.locator('[data-testid="config-button"]').first();if (!(await configBtn.isVisible({ timeout: 5_000 }).catch(() => false))) {@@ -106,14 +107,17 @@ test.describe("Auto Form Detection tool", () => {return;}await configBtn.click();- const dialog = page.locator(".mantine-Modal-content").first();- await expect(dialog).toBeVisible({ timeout: 5_000 });+ const settings = page.locator(SETTINGS_SURFACE);+ await expect(settings).toBeVisible({ timeout: 5_000 });- // AI Form Detection now lives as a box inside the "Features" section,- // not as its own nav entry - navigate there first.- await dialog.getByText("Features", { exact: true }).first().click();+ // AI Form Detection is a card on the System settings page, not a nav entry+ // of its own - navigate there first.+ await settings+ .locator('[data-tour="admin-adminGeneral-nav"]')+ .first()+ .click();- await expect(dialog.getByText(/AI Form Detection/i).first()).toBeVisible({+ await expect(settings.getByText(/AI Form Detection/i).first()).toBeVisible({timeout: 5_000,});});diff --git a/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.ts b/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.tsindex 0b27171c54..a613493b97 100644--- a/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.ts@@ -1,5 +1,8 @@import { test, expect } from "@app/tests/helpers/stub-test-base";-import { openSettings } from "@app/tests/helpers/ui-helpers";+import {+ openSettings,+ expandSettingsGroups,+} from "@app/tests/helpers/ui-helpers";test.describe("18. Cookie Preferences", () => {test.describe("18.1 Cookie Banner", () => {@@ -12,9 +15,11 @@ test.describe("18. Cookie Preferences", () => {);await page.goto("/editor");- // Step 1: The "Cookie Preferences" button lives in Settings → Legal+ // Step 1: The "Cookie Preferences" button lives in Settings → Legal,+ // inside the "About" group the page ships folded.await openSettings(page);- const legalNav = page.locator('[data-tour="admin-legal-nav"]').first();+ await expandSettingsGroups(page);+ const legalNav = page.locator('[data-tour="admin-about-nav"]').first();await expect(legalNav).toBeVisible({ timeout: 5000 });await legalNav.click();diff --git a/frontend/editor/src/core/tests/stubbed/language-localization.spec.ts b/frontend/editor/src/core/tests/stubbed/language-localization.spec.tsindex 3e9d8a05ae..76d5540abb 100644--- a/frontend/editor/src/core/tests/stubbed/language-localization.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/language-localization.spec.ts@@ -1,4 +1,5 @@import { test, expect } from "@app/tests/helpers/stub-test-base";+import { openSettings } from "@app/tests/helpers/ui-helpers";test.describe("13. Language / Localization", () => {test.use({@@ -28,11 +29,7 @@ test.describe("13. Language / Localization", () => {!(await languageButton.isVisible({ timeout: 1000 }).catch(() => false))) {// Open Settings to access the language selector in the General section- await page.locator('[data-testid="config-button"]').first().click();- await page- .locator(".mantine-Modal-content")- .first()- .waitFor({ state: "visible", timeout: 5000 });+ await openSettings(page, /^General$/);languageButton = page.locator('[data-testid="language-selector-button"]').first();diff --git a/frontend/editor/src/core/tests/stubbed/main-dashboard.spec.ts b/frontend/editor/src/core/tests/stubbed/main-dashboard.spec.tsindex 5fa9037363..babcbe4272 100644--- a/frontend/editor/src/core/tests/stubbed/main-dashboard.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/main-dashboard.spec.ts@@ -1,5 +1,8 @@import { test, expect } from "@app/tests/helpers/stub-test-base";-import { openSettings } from "@app/tests/helpers/ui-helpers";+import {+ openSettings,+ expandSettingsGroups,+} from "@app/tests/helpers/ui-helpers";test.describe("2. Main Dashboard / Home Page", () => {test.beforeEach(async ({ page }) => {@@ -102,7 +105,8 @@ test.describe("2. Main Dashboard / Home Page", () => {await expect(page.getByText("Survey")).toHaveCount(0);await openSettings(page);- const legalNav = page.locator('[data-tour="admin-legal-nav"]').first();+ await expandSettingsGroups(page);+ const legalNav = page.locator('[data-tour="admin-about-nav"]').first();await expect(legalNav).toBeVisible({ timeout: 10000 });await legalNav.click();diff --git a/frontend/editor/src/core/tests/stubbed/premium-feature-gates.spec.ts b/frontend/editor/src/core/tests/stubbed/premium-feature-gates.spec.tsindex f9e0a089ed..2ff34eefdc 100644--- a/frontend/editor/src/core/tests/stubbed/premium-feature-gates.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/premium-feature-gates.spec.ts@@ -82,7 +82,7 @@ test.describe("Premium / endpoint gating", () => {return;}await configBtn.click();- const dialog = page.locator(".mantine-Modal-content").first();+ const dialog = page.locator(".settings-page");await expect(dialog).toBeVisible({ timeout: 5_000 });// Admin-only sections must not render for ROLE_USERdiff --git a/frontend/editor/src/core/tests/stubbed/settings-contextual-warnings.spec.ts b/frontend/editor/src/core/tests/stubbed/settings-contextual-warnings.spec.tsnew file mode 100644index 0000000000..f5d5a88ed6--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/settings-contextual-warnings.spec.ts@@ -0,0 +1,46 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });++/**+ * Warnings that describe a consequence must wait for the cause. Standing ones+ * warn about something the reader has not done, and stop being read.+ */+test("the audit cost warning waits until the option is on", async ({+ page,+}) => {+ await page.goto("/settings/adminSecurity");+ await expect(page.locator(".settings-page")).toBeVisible({ timeout: 30_000 });+ await page.locator(".settings-card").first().waitFor({ timeout: 20_000 });+ await page.waitForTimeout(1200);++ await expect(page.locator(".settings-toggle__warning")).toHaveCount(0);++ // Mantine hides the real checkbox; the track is what a user clicks.+ await page+ .locator(".settings-toggle", { hasText: "Capture File Hash" })+ .locator(".mantine-Switch-track")+ .first()+ .click();++ await expect(page.locator(".settings-toggle__warning")).toHaveCount(1);+});++test("the re-index warning waits until the embedding model moves", async ({+ page,+}) => {+ await page.goto("/settings/adminAi");+ await expect(page.locator(".settings-page")).toBeVisible({ timeout: 30_000 });+ await page.locator(".settings-card").first().waitFor({ timeout: 20_000 });+ await page.waitForTimeout(1200);++ const reindex = page.getByText("Re-index required");+ await expect(reindex).toHaveCount(0);++ await page+ .getByRole("textbox", { name: /embedding model/i })+ .first()+ .fill("nomic-embed-text");++ await expect(reindex).toHaveCount(1);+});diff --git a/frontend/editor/src/core/tests/stubbed/settings-deep-links.spec.ts b/frontend/editor/src/core/tests/stubbed/settings-deep-links.spec.tsnew file mode 100644index 0000000000..b633a63c64--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/settings-deep-links.spec.ts@@ -0,0 +1,74 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });++/**+ * Every in-app link into settings addresses a control by its `#slug` - the+ * super search, and the buttons inside banners and cards. The link must land on+ * the control and unfold whatever card it sits in.+ */+async function openSettings(+ page: import("@playwright/test").Page,+ url: string,+) {+ await page.goto(url);+ await expect(page.locator(".settings-page")).toBeVisible({ timeout: 30_000 });+ await page.locator(".settings-card").first().waitFor({ timeout: 20_000 });+ await page.waitForTimeout(1600);+}++const TARGETS = [+ // The two links the audit and usage pages point at.+ ["/settings/adminSecurity#auditLogging", "auditLogging"],+ // The link the mail card and the mobile-upload card point at.+ ["/settings/adminGeneral#frontendUrl", "frontendUrl"],+ ["/settings/adminConnections#adminMcp", "adminMcp"],+ // The row the super search builds for "shortcut" / "keybinding".+ ["/settings/general#setting-hotkeys-search", "setting-hotkeys-search"],+ // A bookmark of a section that has since folded: the alias moves the page,+ // and the control it named has to survive the move.+ ["/settings/adminMcp#adminMcp", "adminMcp"],+] as const;++for (const [url, anchor] of TARGETS) {+ test(`deep link ${url} scrolls to its control`, async ({ page }) => {+ await openSettings(page, url);+ const state = await page.evaluate((id) => {+ const el = document.getElementById(id);+ if (!el) return "MISSING";+ const r = el.getBoundingClientRect();+ const onScreen = r.top > -50 && r.top < window.innerHeight;+ return r.height > 0 && onScreen ? "reached" : "not-reached";+ }, anchor);+ expect(state).toBe("reached");+ });+}++test("a deep link leaves the page scrollable once it has landed", async ({+ page,+}) => {+ // The jump must fire once. Re-arming it on every render pins the reader to+ // the anchor: the scroll spy re-renders on each wheel tick, and the reader is+ // dragged back before the next one lands. Server settings, because it is long+ // enough that being dragged back is a different number from being scrolled.+ await openSettings(page, "/settings/adminGeneral#frontendUrl");+ const scroller = page.locator(".modal-content-scroll");+ const landed = await scroller.evaluate((el) => el.scrollTop);+ for (let i = 0; i < 8; i++) {+ await page.mouse.move(700, 400);+ await page.mouse.wheel(0, 300);+ await page.waitForTimeout(150);+ }+ await page.waitForTimeout(800);+ const scrollTop = await scroller.evaluate((el) => el.scrollTop);+ expect(scrollTop).toBeGreaterThan(landed + 500);+});++test("a deep link into a collapsed card opens it", async ({ page }) => {+ // Keyboard Shortcuts ships collapsed - it renders a row per registered tool.+ await openSettings(page, "/settings/general#hotkeys");+ await expect(page.locator("#hotkeys")).toHaveAttribute(+ "aria-expanded",+ "true",+ );+});diff --git a/frontend/editor/src/core/tests/stubbed/settings-no-raw-translations.spec.ts b/frontend/editor/src/core/tests/stubbed/settings-no-raw-translations.spec.tsnew file mode 100644index 0000000000..bfd880e49e--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/settings-no-raw-translations.spec.ts@@ -0,0 +1,54 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });++/**+ * A `t()` call placed as JSX children instead of `{t()}` prints its own source.+ * The key still counts as referenced, so only the rendered page catches it.+ */+const PAGES = [+ "adminGeneral",+ "adminAi",+ "adminSecurity",+ "adminConnections",+ "adminLegal",+ "adminAdvanced",+ "adminDatabase",+ "adminAudit",+ "adminUsage",+ "adminPlan",+ "general",+ "about",+];++for (const key of PAGES) {+ test(`${key} renders no raw translation calls`, async ({ page }) => {+ await page.goto(`/settings/${key}`);+ await expect(page.locator(".settings-page")).toBeVisible({+ timeout: 30_000,+ });+ await page.waitForTimeout(1200);++ // Open every card and accordion: collapsed panels are `hidden`, and+ // innerText skips them, which is how 26 of these hid the first time.+ await page.evaluate(() => {+ document+ .querySelectorAll<HTMLButtonElement>(+ '.settings-card__toggle[aria-expanded="false"], .mantine-Accordion-control[aria-expanded="false"]',+ )+ .forEach((b) => b.click());+ });+ await page.waitForTimeout(600);++ const hits = await page.evaluate(() => {+ const scroll = document.querySelector(".modal-content-scroll");+ const text = (scroll as HTMLElement | null)?.innerText ?? "";+ return [+ ...new Set(+ [...text.matchAll(/t\(\s*["'][^"']+["']/g)].map((m) => m[0]),+ ),+ ];+ });+ expect(hits, `raw t() calls rendered as text on ${key}`).toEqual([]);+ });+}diff --git a/frontend/editor/src/core/tests/stubbed/settings-subnav-anchors.spec.ts b/frontend/editor/src/core/tests/stubbed/settings-subnav-anchors.spec.tsnew file mode 100644index 0000000000..ddfcbfde7f--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/settings-subnav-anchors.spec.ts@@ -0,0 +1,54 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });++const SUBNAV = ".settings-page__subnav-item";+const ACTIVE = `${SUBNAV}[aria-current="true"]`;++async function openSystem(page: import("@playwright/test").Page) {+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.goto("/settings/adminGeneral");+ await expect(page.locator(".settings-page")).toBeVisible({ timeout: 30_000 });+ await page.locator(".settings-card").first().waitFor({ timeout: 20_000 });+ await page.waitForTimeout(1400);+}++test("sub-headings are real #slug anchors", async ({ page }) => {+ await openSystem(page);+ const hrefs = await page+ .locator(SUBNAV)+ .evaluateAll((els) => els.map((a) => a.getAttribute("href")));+ expect(hrefs.length).toBeGreaterThan(1);+ for (const href of hrefs) expect(href).toMatch(/^#[\w-]+$/);+});++test("the slug follows the reader down the page", async ({ page }) => {+ await openSystem(page);+ const top = await page.locator(ACTIVE).textContent();++ await page.evaluate(() => {+ const s = document.querySelector(".modal-content-scroll") as HTMLElement;+ s.scrollTop = s.scrollHeight;+ });+ await page.waitForTimeout(900);++ const bottom = await page.locator(ACTIVE).textContent();+ expect(bottom).not.toBe(top);+ // The URL names what is on screen, so the address can be shared as-is.+ const hash = await page.evaluate(() => window.location.hash);+ expect(hash).not.toBe("");+});++test("clicking a sub-heading wins over the scroll spy", async ({ page }) => {+ await openSystem(page);+ const target = page.locator(SUBNAV).nth(2);+ const href = await target.getAttribute("href");+ await target.click();+ await page.waitForTimeout(900);+ expect(await page.evaluate(() => window.location.hash)).toBe(href);+});++test("the settings nav has no back control", async ({ page }) => {+ await openSystem(page);+ await expect(page.locator('[data-testid="settings-back"]')).toHaveCount(0);+});diff --git a/frontend/editor/src/core/tests/stubbed/settings.spec.ts b/frontend/editor/src/core/tests/stubbed/settings.spec.tsindex 1b0bfd3be7..56be72e0e3 100644--- a/frontend/editor/src/core/tests/stubbed/settings.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/settings.spec.ts@@ -2,7 +2,7 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";import { openSettings, closeSettings } from "@app/tests/helpers/ui-helpers";/**- * Consolidated settings-dialog coverage. Was previously three files+ * Consolidated settings-page coverage. Was previously three files* (`settings.spec.ts`, `settings-configuration.spec.ts`,* `settings-toggle-behavior.spec.ts`) generated from a numbered test* plan; merged here to cut bloat. Logout flow lives in@@ -10,7 +10,7 @@ import { openSettings, closeSettings } from "@app/tests/helpers/ui-helpers";* invalidation.*/-test.describe("Settings dialog", () => {+test.describe("Settings page", () => {test("opens with sidebar nav and lists General + Keyboard Shortcuts sections", async ({page,}) => {@@ -20,7 +20,8 @@ test.describe("Settings dialog", () => {timeout: 5_000,});}- // General section is selected by default and exposes version info+ // Opening General shows its content - version info lives there+ await openSettings(page, /^General$/);await expect(page.getByText(/version/i).first()).toBeVisible({timeout: 5_000,});@@ -61,7 +62,7 @@ test.describe("Settings dialog", () => {});test("toggle state persists across dialog open/close", async ({ page }) => {- const dialog = await openSettings(page);+ const dialog = await openSettings(page, /^General$/);const toggle = dialog.locator('input[type="checkbox"][role="switch"], input[role="switch"]')@@ -83,7 +84,7 @@ test.describe("Settings dialog", () => {expect(after).not.toBe(before);await closeSettings(page);- await openSettings(page);+ await openSettings(page, /^General$/);const persisted = await toggle.isChecked();expect(persisted).toBe(after);@@ -97,7 +98,7 @@ test.describe("Settings dialog", () => {test("segmented controls (e.g. tool-picker mode) persist across reopen", async ({page,}) => {- const dialog = await openSettings(page);+ const dialog = await openSettings(page, /^General$/);const segmented = dialog.locator(".mantine-SegmentedControl-root").first();if (!(await segmented.isVisible({ timeout: 3_000 }).catch(() => false))) {test.skip(true, "No segmented control on this build");@@ -112,11 +113,11 @@ test.describe("Settings dialog", () => {await labels.nth(1).click();await page.waitForTimeout(300);await closeSettings(page);- await openSettings(page);+ await openSettings(page, /^General$/);// Restoreconst restored = page- .locator(".mantine-Modal-content .mantine-SegmentedControl-root label")+ .locator(".settings-page .mantine-SegmentedControl-root label").first();await restored.click();});@@ -156,7 +157,7 @@ test.describe("Settings dialog", () => {await openSettings(page);const generalNav = page.locator('[data-tour="admin-general-nav"]').first();- const hotkeysNav = page.locator('[data-tour="admin-hotkeys-nav"]').first();+ const aboutNav = page.locator('[data-tour="admin-about-nav"]').first();await expect(generalNav).toBeVisible({ timeout: 5_000 });// First nav into /settings/* takes the React Router path (push). We@@ -172,8 +173,8 @@ test.describe("Settings dialog", () => {// Now do 4 round-trips between two tabs - 8 intra-modal clicks total.for (let i = 0; i < 4; i++) {- await hotkeysNav.click();- await page.waitForURL(/\/settings\/hotkeys/, { timeout: 5_000 });+ await aboutNav.click();+ await page.waitForURL(/\/settings\/about/, { timeout: 5_000 });await generalNav.click();await page.waitForURL(/\/settings\/general/, { timeout: 5_000 });}@@ -188,8 +189,9 @@ test.describe("Settings dialog", () => {// Zero pushes during 8 intra-modal clicks - the regression would show// up here as `after.push - baseline.push >= 1`.expect(after.push - baseline.push).toBe(0);- // Exactly 8 replaces - one per click.- expect(after.replace - baseline.replace).toBe(8);+ // At least one replace per click. Not an exact count any more: the sub-nav+ // also replaces the URL's #slug as the reader lands on a new section.+ expect(after.replace - baseline.replace).toBeGreaterThanOrEqual(8);});test("close returns to origin URL even after switching tabs (no history pile-up)", async ({@@ -241,8 +243,11 @@ test.describe("Settings dialog", () => {];let visited = 0;for (const label of sections) {- const nav = page.getByText(label).first();- if (await nav.isVisible({ timeout: 1_500 }).catch(() => false)) {+ const nav = dialog.locator(".modal-nav-item").filter({ hasText: label });+ const usable =+ (await nav.isVisible({ timeout: 1_500 }).catch(() => false)) &&+ (await nav.isEnabled());+ if (usable) {await nav.click();await page.waitForTimeout(200);const body = await dialog.textContent();diff --git a/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.ts b/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.tsindex d74382aeef..32cf10918a 100644--- a/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/stripe-lazy-load.spec.ts@@ -65,13 +65,12 @@ test.describe("Stripe SDK lazy loading", () => {// checkout without actually clicking Upgrade. Even rendering the// settings drawer must NOT pull Stripe into the entry path — only the// upgrade modal itself, which sits one click further in.- const settingsButton = page- .getByRole("button", { name: /settings/i })- .first();- if (await settingsButton.isVisible({ timeout: 5_000 }).catch(() => false)) {- await settingsButton.click();- await page.waitForTimeout(1_500);- }+ await page.goto("/settings");+ await page+ .locator(".settings-page")+ .waitFor({ timeout: 30_000 })+ .catch(() => {});+ await page.waitForTimeout(1_500);expect(stripeRequests,diff --git a/frontend/editor/src/core/tests/stubbed/super-search.spec.ts b/frontend/editor/src/core/tests/stubbed/super-search.spec.tsindex 431a98b421..ed7621f207 100644--- a/frontend/editor/src/core/tests/stubbed/super-search.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/super-search.spec.ts@@ -146,27 +146,28 @@ test.describe("Super search — bar basics", () => {await expect(page).toHaveURL(/\/merge/);});- test("Ctrl+K inside the settings modal closes it and focuses the bar", async ({+ test("a settings result deep-links to the settings page", async ({page,}) => {const input = page.locator(INPUT);await expect(input).toBeVisible();- await openSettings(page);-- // The modal traps focus, so the bar's own shortcut is inert; the modal- // cedes: it closes itself and hands focus to the bar.- await page.keyboard.press("Control+KeyK");- await expect(page.locator(".modal-container")).not.toBeVisible();- await expect(input).toBeFocused();- await expect(input).toHaveAttribute("aria-expanded", "true");- // Full loop: a settings result deep-links straight back into the modal.await input.fill("general");await page.getByRole("option", { name: /General/ }).first().click();- await expect(page.locator(".modal-container")).toBeVisible();+ await expect(page.locator(".settings-page")).toBeVisible();+ await expect(page).toHaveURL(/\/settings\/general/);+ });++ test("Ctrl+K on the settings page focuses the shared search bar", async ({+ page,+ }) => {+ await openSettings(page);+ // Same bar as the editor and the processor, its own input id.+ await page.keyboard.press("Control+KeyK");+ await expect(page.locator("#settings-search-input")).toBeFocused();});});diff --git a/frontend/editor/src/core/tests/stubbed/tour-onboarding.spec.ts b/frontend/editor/src/core/tests/stubbed/tour-onboarding.spec.tsindex 8d4d07cd8c..283a703625 100644--- a/frontend/editor/src/core/tests/stubbed/tour-onboarding.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/tour-onboarding.spec.ts@@ -1,6 +1,10 @@import path from "path";import { test, expect } from "@app/tests/helpers/stub-test-base";-import { uploadFiles, openSettings } from "@app/tests/helpers/ui-helpers";+import {+ uploadFiles,+ openSettings,+ expandSettingsGroups,+} from "@app/tests/helpers/ui-helpers";/*** Tour selector integrity tests.@@ -203,18 +207,17 @@ test.describe("15.7 Tour selectors - admin modal nav items", () => {"people","teams","adminGeneral",- "adminFeatures",- "adminEndpoints",- "adminDatabase",- "adminConnections",+ "adminAdvanced",+ "adminSecurity","adminAudit","adminUsage",- "help",+ "about",] as const;for (const section of adminNavSections) {test(`admin-${section}-nav is present`, async ({ page }) => {await openSettings(page);+ await expandSettingsGroups(page);const navItem = page.locator(`[data-tour="admin-${section}-nav"]`).first();diff --git a/frontend/editor/src/core/tests/stubbed/workspace-people-teams.spec.ts b/frontend/editor/src/core/tests/stubbed/workspace-people-teams.spec.tsindex f6f3f1fb1e..a00d34919c 100644--- a/frontend/editor/src/core/tests/stubbed/workspace-people-teams.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/workspace-people-teams.spec.ts@@ -2,20 +2,24 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";test.describe("26. Workspace Features", () => {test.beforeEach(async ({ page }) => {- // Open settings dialog- await page- .getByRole("button", { name: /settings/i })- .first()- .click();- const settingsDialog = page.locator(".mantine-Modal-content").first();- await expect(settingsDialog).toBeVisible({ timeout: 5000 });+ // Straight to the page: the rail's settings cog is gone, settings is+ // reached from the account menu or by URL.+ await page.goto("/settings");+ await expect(page.locator(".settings-page")).toBeVisible({+ timeout: 30_000,+ });});test.describe("26.1 Team Members", () => {test("should display workspace members section", async ({ page }) => {// Step 1: Click "People" in the settings nav- const peopleNav = page.getByText(/^People$/i).first();- if (await peopleNav.isVisible({ timeout: 3000 }).catch(() => false)) {+ const peopleNav = page+ .locator(".settings-page .modal-nav-item")+ .filter({ hasText: /^People$/i });+ const usable =+ (await peopleNav.isVisible({ timeout: 3000 }).catch(() => false)) &&+ (await peopleNav.isEnabled());+ if (usable) {await peopleNav.click();// Step 2: Verify the members/team management section loads@@ -32,15 +36,19 @@ test.describe("26. Workspace Features", () => {test.describe("26.2 Teams", () => {test("should display teams management section", async ({ page }) => {// Step 1: Click "Teams" in the settings nav- const teamsNav = page.getByText(/^Teams$/i).first();- if (await teamsNav.isVisible({ timeout: 3000 }).catch(() => false)) {+ const teamsNav = page+ .locator(".settings-page .modal-nav-item")+ .filter({ hasText: /^Teams$/i });+ const usable =+ (await teamsNav.isVisible({ timeout: 3000 }).catch(() => false)) &&+ (await teamsNav.isEnabled());+ if (usable) {await teamsNav.click();// Step 2: Verify the teams management section loadsawait page.waitForTimeout(500);const bodyContent = await page- .locator(".mantine-Modal-content")- .first()+ .locator(".settings-page .modal-body").textContent();expect(bodyContent).toBeTruthy();}diff --git a/frontend/editor/src/core/types/superSearch.ts b/frontend/editor/src/core/types/superSearch.tsindex 3d8e72849f..51c4e8c597 100644--- a/frontend/editor/src/core/types/superSearch.ts+++ b/frontend/editor/src/core/types/superSearch.ts@@ -90,6 +90,8 @@ export interface PortalEntityScopeDef {| "portal-sources";/** Portal view id the scope targets (visibility check vs the page index). */viewId: string;+ /** Set when the entities now live in a settings section rather than on that page. */+ settingsKey?: string;labelKey: string;labelFallback: string;aliases: readonly string[];@@ -106,6 +108,7 @@ export const PORTAL_ENTITY_SCOPE_DEFS: readonly PortalEntityScopeDef[] = [{id: "portal-users",viewId: "users",+ settingsKey: "users",labelKey: "portal.nav.users",labelFallback: "Users",aliases: ["user", "users", "member", "members"],diff --git a/frontend/editor/src/core/ui/Avatar.tsx b/frontend/editor/src/core/ui/Avatar.tsxindex a5ad5986b1..1e5a6f4046 100644--- a/frontend/editor/src/core/ui/Avatar.tsx+++ b/frontend/editor/src/core/ui/Avatar.tsx@@ -14,18 +14,22 @@ export interface AvatarProps {/** Image source. Falls back to initials when missing or load fails. */src?: string;/** Full name. Initials are derived from the first letter of each word, max 2. */- name: string;+ name: string | undefined;size?: AvatarSize;/** Background tone when rendering initials. Defaults to blue. */tone?: AvatarTone;/** Optional click handler — renders as a button when supplied. */onClick?: () => void;ariaLabel?: string;+ /** Marks the button as the current destination when it is a nav control. */+ ariaCurrent?: "page" | "true";className?: string;}-function avatarInitials(name: string): string {- const parts = name.trim().split(/\s+/).filter(Boolean);+function avatarInitials(name: string | undefined | null): string {+ // Defensive: a roster row whose display name never arrived used to throw+ // here and take the whole section down with it.+ const parts = (name ?? "").trim().split(/\s+/).filter(Boolean);if (parts.length === 0) return "?";// Single word (a username or an email) reads as one letter — two letters of// "admin" ("AD") looks like a different person's initials, not a truncation.@@ -44,6 +48,7 @@ export function Avatar({tone = "blue",onClick,ariaLabel,+ ariaCurrent,className,}: AvatarProps) {// A picture URL that 404s (expired signed URL, deleted upload) must not leave@@ -86,6 +91,7 @@ export function Avatar({className={classes}onClick={onClick}aria-label={ariaLabel ?? name}+ aria-current={ariaCurrent}>{content}</button>diff --git a/frontend/editor/src/core/ui/InfoTooltip.css b/frontend/editor/src/core/ui/InfoTooltip.cssindex 7f2b4015d8..05d8975f2e 100644--- a/frontend/editor/src/core/ui/InfoTooltip.css+++ b/frontend/editor/src/core/ui/InfoTooltip.css@@ -8,6 +8,8 @@color: var(--c-text-subtle);cursor: pointer;line-height: 0;+ /* Ignored in flex rows; keeps the icon centred when it sits inside a line of text. */+ vertical-align: middle;}.sui-info:hover {color: var(--c-text);diff --git a/frontend/editor/src/core/utils/settingsNavigation.ts b/frontend/editor/src/core/utils/settingsNavigation.tsindex a4ca4248dd..a9c2bd70c2 100644--- a/frontend/editor/src/core/utils/settingsNavigation.ts+++ b/frontend/editor/src/core/utils/settingsNavigation.ts@@ -1,18 +1,51 @@import { NavKey } from "@app/components/shared/config/types";import { stripBasePath, withBasePath } from "@app/constants/app";-/** Push the URL for a settings section and notify listeners. */-export function navigateToSettings(section: NavKey) {- const newPath = withBasePath(`/settings/${section}`);- window.history.pushState({}, "", newPath);- window.dispatchEvent(new PopStateEvent("popstate"));+const ORIGIN_KEY = "stirling.settingsOrigin";++/**+ * Record where the user is before they go to settings, so its Back control can+ * restore that URL by replacement. Recorded rather than inferred: history.go(-1)+ * is dropped by WebKit under load, and an entry made by pushState carries no+ * router key to tell "came from the editor" apart from "opened a deep link".+ * A no-op while already in settings, so tab switches keep the original origin.+ */+export function rememberSettingsOrigin(): void {+ const here = stripBasePath(window.location.pathname);+ if (here.startsWith("/settings")) return;+ try {+ window.sessionStorage.setItem(ORIGIN_KEY, here + window.location.search);+ } catch {+ // Private mode or storage disabled: Back falls back to the editor.+ }}-export function openSettings(section: NavKey) {- window.history.pushState({}, "", withBasePath(`/settings/${section}`));- window.dispatchEvent(- new CustomEvent("appConfig:open", { detail: { section } }),- );+/** The origin recorded by {@link rememberSettingsOrigin}, cleared on read. */+export function takeSettingsOrigin(): string | null {+ try {+ const origin = window.sessionStorage.getItem(ORIGIN_KEY);+ window.sessionStorage.removeItem(ORIGIN_KEY);+ return origin;+ } catch {+ return null;+ }+}++/**+ * Go to the settings page from outside the router — modals, services, and+ * contexts that must keep working where no <Router> is mounted (portal unit+ * tests render their providers bare). pushState + a synthetic popstate is how+ * React Router picks the change up without a hook.+ *+ * @param section land on this section; omit for the page's default+ * @param anchor scroll to and highlight this control, by its slug+ */+export function navigateToSettings(section?: NavKey, anchor?: string) {+ rememberSettingsOrigin();+ const hash = anchor ? `#${encodeURIComponent(anchor)}` : "";+ const path = `/settings${section ? `/${section}` : ""}${hash}`;+ window.history.pushState({}, "", withBasePath(path));+ window.dispatchEvent(new PopStateEvent("popstate"));}/** URL for a settings section (subpath-aware). */diff --git a/frontend/editor/src/desktop/components/settings/useSettingsNav.tsx b/frontend/editor/src/desktop/components/settings/useSettingsNav.tsxnew file mode 100644index 0000000000..7c177f08ad--- /dev/null+++ b/frontend/editor/src/desktop/components/settings/useSettingsNav.tsx@@ -0,0 +1,6 @@+/**+ * Desktop inherits proprietary's app but ships no portal, so it must not+ * resolve @portal — shadow the seam back to the core sections.+ */+export { useSettingsNav } from "@core/components/settings/useSettingsNav";+export type { SettingsNav } from "@app/components/settings/settingsNavTypes";diff --git a/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx b/frontend/editor/src/desktop/components/shared/config/configNavSections.tsxindex 9a638d1461..f5ea130e68 100644--- a/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx+++ b/frontend/editor/src/desktop/components/shared/config/configNavSections.tsx@@ -3,6 +3,7 @@ import { useState, useEffect } from "react";import { useConfigNavSections as useProprietaryConfigNavSections } from "@proprietary/components/shared/config/configNavSections";import { ConfigNavSection } from "@core/components/shared/config/configNavSections";import { ConnectionSettings } from "@app/components/ConnectionSettings";+import DesktopGeneralSection from "@app/components/shared/config/configSections/GeneralSection";import {createCloudPlanNavItem,createCloudTeamNavItem,@@ -57,28 +58,43 @@ export const useConfigNavSections = (showSettingsWhenNoLogin,);+ // Desktop adds file-association defaults and its own update controls to the+ // Preferences page; core builds the page, desktop supplies its extras.+ const preferences = sections.find((s) => s.id === "preferences");+ if (preferences) {+ preferences.items = preferences.items.map((item) =>+ item.key === "general"+ ? { ...item, component: <DesktopGeneralSection /> }+ : item,+ );+ }+const connectionModeSection: ConfigNavSection = {title: t("settings.connection.title", "Connection Mode"),items: [{key: "connectionMode",label: t("settings.connection.title", "Connection Mode"),+ description: t(+ "settings.connection.description",+ "Work locally on this machine or connect the app to a Stirling server.",+ ),icon: "desktop-cloud-rounded",component: <ConnectionSettings />,},],};- // In local mode only show Preferences + Connection Mode + Legal — everything+ // In local mode only show Preferences + Connection Mode + About — everything// else requires a server and will 500 or show irrelevant admin UI.if (isLocalMode) {const result: ConfigNavSection[] = [];if (sections.length > 0) result.push(sections[0]);result.push(connectionModeSection);- const legalSection = sections.find((section) =>- section.items.some((item) => item.key === "legal"),- );- if (legalSection) result.push(legalSection);+ // Matched on the group id: its items were four rows and are now one, and a+ // miss here drops the group silently.+ const aboutSection = sections.find((section) => section.id === "about");+ if (aboutSection) result.push(aboutSection);return result;}diff --git a/frontend/editor/src/desktop/components/shared/config/configSections/GeneralSection.tsx b/frontend/editor/src/desktop/components/shared/config/configSections/GeneralSection.tsxindex d29f211509..4ca1e43b32 100644--- a/frontend/editor/src/desktop/components/shared/config/configSections/GeneralSection.tsx+++ b/frontend/editor/src/desktop/components/shared/config/configSections/GeneralSection.tsx@@ -1,7 +1,7 @@import React, { useCallback, useEffect, useState } from "react";import { Stack, Alert } from "@mantine/core";import { useTranslation } from "react-i18next";-import CoreGeneralSection from "@core/components/shared/config/configSections/GeneralSection";+import PreferencesSection from "@core/components/shared/config/configSections/preferences/PreferencesSection";import { DefaultAppSettings } from "@app/components/shared/config/configSections/DefaultAppSettings";import { useDesktopInstall } from "@app/hooks/useDesktopInstall";import { useSaaSMode } from "@app/hooks/useSaaSMode";@@ -25,9 +25,7 @@ interface GeneralSectionProps {* still rendered but disabled, with a "Managed by administrator" hint, so* managed-deployment users can see what policy is in effect.*/-const GeneralSection: React.FC<GeneralSectionProps> = ({- hideTitle = false,-}) => {+const GeneralSection: React.FC<GeneralSectionProps> = () => {const { t } = useTranslation();const install = useDesktopInstall();// In SaaS connection mode the cloud owns app versioning — hide the update@@ -88,7 +86,6 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({return (<Stack gap="lg">- <DefaultAppSettings />{updateModeError && (<Alertcolor="red"@@ -102,8 +99,8 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({{updateModeError}</Alert>)}- <CoreGeneralSection- hideTitle={hideTitle}+ <PreferencesSection+ editorDefaultsSlot={<DefaultAppSettings />}hideUpdateSection={isSaaSMode ||(updateModeInfo.mode === "disabled" && updateModeInfo.locked)diff --git a/frontend/editor/src/desktop/components/shared/config/types.ts b/frontend/editor/src/desktop/components/shared/config/types.tsindex daae2b16bc..b555a6b738 100644--- a/frontend/editor/src/desktop/components/shared/config/types.ts+++ b/frontend/editor/src/desktop/components/shared/config/types.ts@@ -1,4 +1,7 @@-import type React from "react";+import type {+ ConfigNavItem as CoreConfigNavItem,+ ConfigNavSection as CoreConfigNavSection,+} from "@core/components/shared/config/types";import { VALID_NAV_KEYS as CORE_NAV_KEYS } from "@core/components/shared/config/types";export const VALID_NAV_KEYS = [@@ -9,20 +12,13 @@ export const VALID_NAV_KEYS = [export type NavKey = (typeof VALID_NAV_KEYS)[number];-// Mirrors the core shape over the widened desktop NavKey union — see the core-// module for why these live in types rather than configNavSections.-export interface ConfigNavItem {+// Core's item over this flavor's widened key union. Derived, not copied: a new+// field on the core shape must reach every flavor or the shared settings page+// stops compiling for one of them.+export interface ConfigNavItem extends Omit<CoreConfigNavItem, "key"> {key: NavKey;- label: string;- icon: string;- component: React.ReactNode;- disabled?: boolean;- disabledTooltip?: string;- badge?: string;- badgeColor?: string;}-export interface ConfigNavSection {- title: string;+export interface ConfigNavSection extends Omit<CoreConfigNavSection, "items"> {items: ConfigNavItem[];}diff --git a/frontend/editor/src/desktop/data/settingsSectionRegistry.ts b/frontend/editor/src/desktop/data/settingsSectionRegistry.tsindex dc55c927be..44dca8234f 100644--- a/frontend/editor/src/desktop/data/settingsSectionRegistry.ts+++ b/frontend/editor/src/desktop/data/settingsSectionRegistry.ts@@ -44,7 +44,7 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [labelKey: "settings.legal.label",labelFallback: "Legal",keywords: ["legal", "terms", "privacy", "licenses"],- groupLabelKey: "settings.legal.title",- groupLabelFallback: "Legal",+ groupLabelKey: "settings.about.title",+ groupLabelFallback: "About",},];diff --git a/frontend/editor/src/desktop/routes/Landing.tsx b/frontend/editor/src/desktop/routes/Landing.tsxindex ce48048951..9fd029fcc1 100644--- a/frontend/editor/src/desktop/routes/Landing.tsx+++ b/frontend/editor/src/desktop/routes/Landing.tsx@@ -1,4 +1,4 @@-import HomePage from "@app/pages/HomePage";+import { AppRoot } from "@app/components/layout/AppRoot";/*** Desktop override of Landing.@@ -8,5 +8,5 @@ import HomePage from "@app/pages/HomePage";* when authentication is required.*/export default function Landing() {- return <HomePage />;+ return <AppRoot />;}diff --git a/frontend/editor/src/portal-saas/components/sidebarGroups.test.ts b/frontend/editor/src/portal-saas/components/sidebarGroups.test.tsindex 75208a234b..ae39e7c304 100644--- a/frontend/editor/src/portal-saas/components/sidebarGroups.test.ts+++ b/frontend/editor/src/portal-saas/components/sidebarGroups.test.ts@@ -13,16 +13,11 @@ describe("sidebarGroups (SaaS)", () => {"pipelines","documents","review",+ "integrations",]);});- it("inherits the platform group unchanged from base", () => {- expect(GROUP_PLATFORM.map((e) => e.id)).toEqual([- "users",- "integrations",- "infrastructure",- "usage",- "docs",- ]);+ it("carries no platform group: server administration lives in settings", () => {+ expect(GROUP_PLATFORM).toEqual([]);});});diff --git a/frontend/editor/src/portal-saas/views/Infrastructure.test.tsx b/frontend/editor/src/portal-saas/views/Infrastructure.test.tsxdeleted file mode 100644index 4d6be47ae0..0000000000--- a/frontend/editor/src/portal-saas/views/Infrastructure.test.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";--vi.mock("react-i18next", () => ({- useTranslation: () => ({- t: (key: string, def?: string) => def ?? key,- i18n: { changeLanguage: vi.fn() },- }),-}));--const enterprise = { enabled: true, loading: false };-vi.mock("@portal/hooks/useEnterpriseEnabled", () => ({- useEnterpriseEnabled: () => enterprise,-}));--// Stub the live tab panels so the test doesn't pull their data dependencies.-vi.mock("@portal/components/infrastructure/ApiKeysTab", () => ({- ApiKeysTab: () => <div data-testid="api-keys-tab" />,-}));-vi.mock("@portal/components/infrastructure/AuditTab", () => ({- AuditTab: () => <div data-testid="audit-tab" />,-}));--import { Infrastructure } from "@portal/views/Infrastructure";--describe("Infrastructure (SaaS)", () => {- beforeEach(() => {- enterprise.enabled = true;- enterprise.loading = false;- });-- it("defaults to the live API keys tab", () => {- render(<Infrastructure />);- expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();- });-- it("renders the not-yet-shipped tabs as disabled 'coming soon'", () => {- render(<Infrastructure />);- for (const tab of ["deployments", "security", "models", "storage"]) {- const btn = screen.getByRole("button", {- name: new RegExp(`portal.infrastructure.tabs.${tab}`),- });- expect(btn).toBeDisabled();- }- // The live tabs are not disabled.- expect(- screen.getByRole("button", {- name: /portal.infrastructure.tabs.apiKeys/,- }),- ).toBeEnabled();- });-- it("disables the audit tab for non-enterprise tenants", () => {- enterprise.enabled = false;- render(<Infrastructure />);- expect(- screen.getByRole("button", {- name: /portal.infrastructure.tabs.audit/,- }),- ).toBeDisabled();- });-});diff --git a/frontend/editor/src/portal-saas/views/Infrastructure.tsx b/frontend/editor/src/portal-saas/views/Infrastructure.tsxdeleted file mode 100644index b0c3f316fd..0000000000--- a/frontend/editor/src/portal-saas/views/Infrastructure.tsx+++ /dev/null@@ -1,92 +0,0 @@-import { useState } from "react";-import { useTranslation } from "react-i18next";-import { Tabs, type TabItem } from "@app/ui";-import { useEnterpriseEnabled } from "@portal/hooks/useEnterpriseEnabled";-import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";-import { AuditTab } from "@portal/components/infrastructure/AuditTab";-import "@portal/views/Infrastructure.css";--// SaaS pre-release: only API keys + Audit are shipped. Deployments, Security,-// Models and Storage are shown as disabled "coming soon" tabs (greyed, to the-// right of the live ones). Selection is never one of the coming-soon keys — the-// Tabs primitive renders them as native-disabled buttons, so onChange can't fire.-type InfraTab =- | "api-keys"- | "audit"- | "deployments"- | "security"- | "models"- | "storage";--export function Infrastructure() {- const { t } = useTranslation();- const [tab, setTab] = useState<InfraTab>("api-keys");- // Audit is Enterprise-only; disabled (greyed, inert) for non-enterprise tenants.- const auditEnabled = useEnterpriseEnabled().enabled;-- const comingSoon = (labelKey: string) => (- <>- {t(labelKey)}{" "}- <span style={{ opacity: 0.6, fontWeight: 400, fontSize: "0.8em" }}>- · {t("portal.comingSoon", "Coming soon")}- </span>- </>- );-- const tabs: TabItem<InfraTab>[] = [- { key: "api-keys", label: t("portal.infrastructure.tabs.apiKeys") },- {- key: "audit",- label: t("portal.infrastructure.tabs.audit"),- disabled: !auditEnabled,- },- {- key: "deployments",- label: comingSoon("portal.infrastructure.tabs.deployments"),- disabled: true,- },- {- key: "security",- label: comingSoon("portal.infrastructure.tabs.security"),- disabled: true,- },- {- key: "models",- label: comingSoon("portal.infrastructure.tabs.models"),- disabled: true,- },- {- key: "storage",- label: comingSoon("portal.infrastructure.tabs.storage"),- disabled: true,- },- ];-- return (- <div className="portal-infra">- <header className="portal-infra__head">- <div className="portal-infra__head-text">- <h1 className="portal-infra__title">- {t("portal.infrastructure.title")}- </h1>- <p className="portal-infra__sub">- {t("portal.infrastructure.subtitle")}- </p>- </div>- </header>-- <Tabs<InfraTab>- items={tabs}- activeKey={tab}- onChange={setTab}- variant="underline"- ariaLabel={t("portal.infrastructure.sectionsAriaLabel")}- />-- <div className="portal-infra__panel">- {tab === "api-keys" && <ApiKeysTab />}- {tab === "audit" && <AuditTab />}- </div>- </div>- );-}diff --git a/frontend/editor/src/portal/ViewRouter.tsx b/frontend/editor/src/portal/ViewRouter.tsxindex 239104fef6..9d73259f56 100644--- a/frontend/editor/src/portal/ViewRouter.tsx+++ b/frontend/editor/src/portal/ViewRouter.tsx@@ -1,4 +1,4 @@-import { lazy, Suspense, useEffect } from "react";+import { useEffect } from "react";import {Navigate,Route,@@ -7,24 +7,21 @@ import {useNavigate,} from "react-router-dom";import { Home } from "@portal/views/Home";-import { Users } from "@portal/views/Users";import { Documents } from "@portal/views/Documents";import { Review } from "@portal/views/Review";import { Pipelines } from "@portal/views/Pipelines";import { PipelineBuilder } from "@portal/views/PipelineBuilder";import { Sources } from "@portal/views/Sources";import { Integrations } from "@portal/views/Integrations";-import { Infrastructure } from "@portal/views/Infrastructure";-import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";+import { DOCS_PATH } from "@app/routes/docsRoute";import { useUI } from "@portal/contexts/UIContext";-// Lazy so the generated docs manifest (bundled JSON) lands in its own chunk.-const DeveloperDocs = lazy(() =>- import("@portal/views/DeveloperDocs").then((m) => ({- default: m.DeveloperDocs,- })),-);+/** Keeps the query and hash a moved tab's deep links carry (?tab=, #doc-id). */+function MovedTo({ to }: { to: string }) {+ const { search, hash } = useLocation();+ return <Navigate to={`${to}${search}${hash}`} replace />;+}// The portal mounts as a route-set under /processor/* in the editor app, so these// child routes are relative to that base: strip the leading slash from the@@ -62,7 +59,6 @@ export function ViewRouter() {return (<Routes><Route index element={<Home />} />- <Route path={rel(VIEW_PATHS.users)} element={<Users />} /><Route path={rel(VIEW_PATHS.pipelines)} element={<Pipelines />} /><Routepath={`${rel(VIEW_PATHS.pipelines)}/new`}@@ -90,27 +86,28 @@ export function ViewRouter() {<Route path={rel(VIEW_PATHS.policies)} element={<PoliciesRedirect />} /><Route path={rel(VIEW_PATHS.documents)} element={<Documents />} /><Route path={rel(VIEW_PATHS.review)} element={<Review />} />+ {/* Server administration and the docs browser are product-wide, so they+ left the processor. Their old URLs still resolve. */}+ <Route+ path={rel(VIEW_PATHS.users)}+ element={<MovedTo to="/settings/users" />}+ /><Routepath={rel(VIEW_PATHS.infrastructure)}- element={<Infrastructure />}+ element={<MovedTo to="/settings/api-keys" />}/>- <Route path={rel(VIEW_PATHS.usage)} element={<PortalBillingGate />} /><Route- path={rel(VIEW_PATHS.docs)}- element={- <Suspense fallback={null}>- <DeveloperDocs />- </Suspense>- }+ path={rel(VIEW_PATHS.usage)}+ element={<MovedTo to="/settings/billing" />}/>+ <Route path={rel(VIEW_PATHS.docs)} element={<MovedTo to={DOCS_PATH} />} />{/* A bare path, not a VIEW_PATHS entry: nothing should list it as a view. */}<Route path="procurement" element={<ProcurementRedirect />} />- {/* Account-link is now a Settings panel; redirect legacy bookmarks home. */}+ {/* Account-link is a settings section now. */}<Routepath="account-link"- element={<Navigate to={toPortalPath(VIEW_PATHS.home)} replace />}+ element={<MovedTo to="/settings/account-link" />}/>- {/* Settings is a modal overlay, not a route (see AppShell + UIContext). */}{/* Unknown paths land on Home. */}<Routepath="*"diff --git a/frontend/editor/src/portal/api/usersCapabilities.ts b/frontend/editor/src/portal/api/usersCapabilities.tsindex 01f68ae283..e5981feb2c 100644--- a/frontend/editor/src/portal/api/usersCapabilities.ts+++ b/frontend/editor/src/portal/api/usersCapabilities.ts@@ -56,6 +56,8 @@ export interface UsersCapabilities {manageGrants: boolean;/** Whether "remove" takes the member out of the whole org or just the team. */removeScope: "org" | "team";+ /** Offer the remove action at all. Off for viewers who may only read. */+ removeMember: boolean;/*** Listing the roster needs the org-admin role. Self-hosted reads the* admin-only endpoints (`@PreAuthorize(hasRole('ADMIN'))`), which refusediff --git a/frontend/editor/src/portal/components/AppShell.tsx b/frontend/editor/src/portal/components/AppShell.tsxindex ec6c720297..0c1be174b6 100644--- a/frontend/editor/src/portal/components/AppShell.tsx+++ b/frontend/editor/src/portal/components/AppShell.tsx@@ -61,7 +61,7 @@ function MobileTopbar() {* prop-free.*/export function AppShell({ children }: { children: ReactNode }) {- const { mobileNavOpen, closeMobileNav, openSettings } = useUI();+ const { mobileNavOpen, closeMobileNav } = useUI();const { pathname } = useLocation();// Below this width the rail, and the bell it carries, is gone.const isPhone = useIsPhone();@@ -85,7 +85,7 @@ export function AppShell({ children }: { children: ReactNode }) {return (<div className="portal-shell">{/* portalAccess: being here is proof the processor is available. */}- <QuickNavHostBridge portalAccess onOpenSettings={() => openSettings()} />+ <QuickNavHostBridge portalAccess /><div className="workspace-frame"><Sidebar /></div>diff --git a/frontend/editor/src/portal/components/PortalChrome.tsx b/frontend/editor/src/portal/components/PortalChrome.tsxindex 87afd094cc..f77efab719 100644--- a/frontend/editor/src/portal/components/PortalChrome.tsx+++ b/frontend/editor/src/portal/components/PortalChrome.tsx@@ -3,7 +3,6 @@ import { AppConfigProvider } from "@app/contexts/AppConfigContext";import { ToolRegistryProvider } from "@app/contexts/ToolRegistryProvider";import { ErrorBoundary } from "@portal/components/ErrorBoundary";import { AppShell } from "@portal/components/AppShell";-import { PortalSettingsHost } from "@portal/components/PortalSettingsHost";import { ViewRouter } from "@portal/ViewRouter";/**@@ -29,8 +28,8 @@ function RoutedContent() {*/export function PortalChrome() {return (- // One app-config instance for every portal consumer (search gates, the- // settings modal) so they can't fetch twice or disagree.+ // One app-config instance for every portal consumer (the search gates, the+ // sidebar) so they can't fetch twice or disagree.<AppConfigProvider bootstrapMode="non-blocking">{/* The pipeline builder reads the tool registry to list and configure operations. */}<ToolRegistryProvider>@@ -38,7 +37,6 @@ export function PortalChrome() {<RoutedContent /></AppShell></ToolRegistryProvider>- <PortalSettingsHost /></AppConfigProvider>);}diff --git a/frontend/editor/src/portal/components/PortalSettingsHost.tsx b/frontend/editor/src/portal/components/PortalSettingsHost.tsxdeleted file mode 100644index 0aec29dd14..0000000000--- a/frontend/editor/src/portal/components/PortalSettingsHost.tsx+++ /dev/null@@ -1,102 +0,0 @@-import { useEffect, useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import AppConfigModalLazy from "@app/components/shared/AppConfigModalLazy";-import { AppConfigProvider } from "@app/contexts/AppConfigContext";-import { PreferencesProvider } from "@app/contexts/PreferencesContext";-import { ThemeProvider } from "@app/components/shared/ThemeProvider";-import { AuthProvider } from "@app/auth/UseSession";-import {- VALID_NAV_KEYS,- type ConfigNavSection,- type NavKey,-} from "@app/components/shared/config/types";-import { accountLinkSettings } from "@portal/components/settings/accountLinkSettings";-import { useUI } from "@portal/contexts/UIContext";--/**- * Settings sections the portal cannot host. Shared with the portal's search- * provider so these never surface as search results either.- *- * TODO: opening Keyboard Shortcuts in the portal white-screens the app (the- * section expects editor-only context). Hidden here as a stopgap; fix the- * section properly and drop this.- */-export const PORTAL_HIDDEN_SECTION_KEYS: NavKey[] = ["hotkeys"];--/**- * Mounts the editor's settings modal (the app-wide settings surface) inside the- * portal. The portal deliberately lives outside the editor's AppProviders, so- * this host supplies the contexts the settings tree needs: user preferences,- * the session provider the account sections read (flavor-resolved: Spring on- * self-hosted, Supabase on SaaS — same underlying session the portal is- * already signed in with), and the editor ThemeProvider (which also carries- * the Mantine theme + toasts the sections expect). App config comes from- * PortalChrome's shared provider. URL sync is off — the portal owns its own- * route subtree, so the modal keeps its section purely in state.- *- * Everything (providers included) mounts on first open and stays mounted, so- * the editor theme wiring never runs for portal sessions that never open- * settings.- */-export function PortalSettingsHost() {- const {- settingsOpen,- settingsInitialSection,- settingsInitialFocus,- closeSettings,- } = useUI();- const { t } = useTranslation();- const [everOpened, setEverOpened] = useState(false);-- useEffect(() => {- if (settingsOpen) setEverOpened(true);- }, [settingsOpen]);-- // Portal-only sections, appended after the build's registry sections. The- // account-link seam is self-hosted-only (the saas overlay shadows it to null).- const extraSections = useMemo<ConfigNavSection[]>(() => {- if (!accountLinkSettings) return [];- const { navKey, labelKey, icon, Body } = accountLinkSettings;- return [- {- title: t("portal.settings.groups.admin", "Admin"),- items: [- {- key: navKey,- label: t(labelKey, "Account link"),- icon,- component: <Body />,- },- ],- },- ];- }, [t]);-- const initialSection: NavKey | null =- settingsInitialSection &&- (VALID_NAV_KEYS as readonly string[]).includes(settingsInitialSection)- ? (settingsInitialSection as NavKey)- : null;-- if (!everOpened) return null;-- return (- <AppConfigProvider bootstrapMode="non-blocking">- <AuthProvider>- <PreferencesProvider>- <ThemeProvider>- <AppConfigModalLazy- opened={settingsOpen}- onClose={closeSettings}- urlSync={false}- initialSection={initialSection}- initialFocus={settingsInitialFocus}- extraSections={extraSections}- hiddenSectionKeys={PORTAL_HIDDEN_SECTION_KEYS}- />- </ThemeProvider>- </PreferencesProvider>- </AuthProvider>- </AppConfigProvider>- );-}diff --git a/frontend/editor/src/portal/components/ProcessorFlow.tsx b/frontend/editor/src/portal/components/ProcessorFlow.tsxindex 21f32d5d50..47249f2cfe 100644--- a/frontend/editor/src/portal/components/ProcessorFlow.tsx+++ b/frontend/editor/src/portal/components/ProcessorFlow.tsx@@ -48,9 +48,8 @@ export function ProcessorFlow({ dataOverride }: ProcessorFlowProps = {}) {`${toPortalPath(VIEW_PATHS.pipelines)}?setup=${encodeURIComponent(key)}`,);- /** Deep-link to Infrastructure with the audit-log tab open. */- const openAuditLog = () =>- navigate(`${toPortalPath(VIEW_PATHS.infrastructure)}?tab=audit`);+ /** Deep-link to the audit log in settings (a build-neutral key; see PORTAL_SECTION_ALIASES). */+ const openAuditLog = () => navigate("/settings/audit");const sources = data?.sources ?? [];const policies = data?.policies ?? [];diff --git a/frontend/editor/src/portal/components/Sidebar.tsx b/frontend/editor/src/portal/components/Sidebar.tsxindex dde5b01bfe..4d6942c3ae 100644--- a/frontend/editor/src/portal/components/Sidebar.tsx+++ b/frontend/editor/src/portal/components/Sidebar.tsx@@ -21,10 +21,12 @@ import {} from "@portal/components/sidebarGroups";import "@portal/components/Sidebar.css";+// Empty groups are dropped: a flavor (or a move to the settings page) can leave+// one with nothing in it, and an empty card is not a section.const NAV_SECTIONS: NavGroup[] = [{ labelKey: "portal.nav.section.processor", entries: GROUP_PROCESSOR },{ labelKey: "portal.nav.section.platform", entries: GROUP_PLATFORM },-];+].filter((section) => section.entries.length > 0);/** Must match the shell breakpoint in AppShell.css / Sidebar.css. */export const MOBILE_QUERY = "(max-width: 48rem)";diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsxindex 4854048ab8..603f7ade25 100644--- a/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsx+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectDoneSlide.tsx@@ -78,7 +78,7 @@ export function ConnectDoneSlide({ onNavigate }: Props) {"portal.accountLink.connect.done.switchOnProcessor","Switch on the Processor",),- path: toPortalPath(VIEW_PATHS.usage),+ path: "/settings/billing",},]: []),@@ -88,7 +88,7 @@ export function ConnectDoneSlide({ onNavigate }: Props) {"portal.accountLink.connect.done.inviteTeam","Invite your team",),- path: toPortalPath(VIEW_PATHS.users),+ path: "/settings/users",},{key: "pipeline",diff --git a/frontend/editor/src/portal/components/docs/AuthenticationSection.stories.tsx b/frontend/editor/src/portal/components/docs/AuthenticationSection.stories.tsxindex 6fa96e4555..ee389df052 100644--- a/frontend/editor/src/portal/components/docs/AuthenticationSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/AuthenticationSection.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { AuthenticationSection } from "@portal/components/docs/AuthenticationSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof AuthenticationSection> = {title: "Portal/DeveloperDocs/AuthenticationSection",diff --git a/frontend/editor/src/portal/components/docs/AuthenticationSection.tsx b/frontend/editor/src/portal/components/docs/AuthenticationSection.tsxindex 25481f8cf7..fcc95ab5db 100644--- a/frontend/editor/src/portal/components/docs/AuthenticationSection.tsx+++ b/frontend/editor/src/portal/components/docs/AuthenticationSection.tsx@@ -1,6 +1,6 @@import { useTranslation } from "react-i18next";import { Chip, CodeBlock } from "@app/ui";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function AuthenticationSection() {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/docs/ComponentsSection.stories.tsx b/frontend/editor/src/portal/components/docs/ComponentsSection.stories.tsxindex b4dedb366c..c450a6305c 100644--- a/frontend/editor/src/portal/components/docs/ComponentsSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/ComponentsSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { ComponentsSection } from "@portal/components/docs/ComponentsSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof ComponentsSection> = {title: "Portal/DeveloperDocs/ComponentsSection",diff --git a/frontend/editor/src/portal/components/docs/ComponentsSection.tsx b/frontend/editor/src/portal/components/docs/ComponentsSection.tsxindex 6bb9326ab8..4b9a6aaae5 100644--- a/frontend/editor/src/portal/components/docs/ComponentsSection.tsx+++ b/frontend/editor/src/portal/components/docs/ComponentsSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { Card, Chip, CodeBlock } from "@app/ui";import type { EmbedComponent } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function ComponentsSection({components,diff --git a/frontend/editor/src/portal/components/docs/DocsNav.stories.tsx b/frontend/editor/src/portal/components/docs/DocsNav.stories.tsxindex cbe474b102..f74930c257 100644--- a/frontend/editor/src/portal/components/docs/DocsNav.stories.tsx+++ b/frontend/editor/src/portal/components/docs/DocsNav.stories.tsx@@ -1,8 +1,8 @@import { useState } from "react";import type { Meta, StoryObj } from "@storybook/react-vite";import { buildDocsNav } from "@portal/mocks/docs";-import { DocsNav, DocsNavSkeleton } from "@portal/components/docs/DocsNav";-import "@portal/views/DeveloperDocs.css";+import { DocsNav, DocsNavSkeleton } from "@core/components/docs/DocsNav";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof DocsNav> = {title: "Portal/DeveloperDocs/DocsNav",diff --git a/frontend/editor/src/portal/components/docs/DocsSection.stories.tsx b/frontend/editor/src/portal/components/docs/DocsSection.stories.tsxindex e896af6e4a..806730b0c0 100644--- a/frontend/editor/src/portal/components/docs/DocsSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/DocsSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { Card } from "@app/ui";-import { DocsSection } from "@portal/components/docs/DocsSection";-import "@portal/views/DeveloperDocs.css";+import { DocsSection } from "@core/components/docs/DocsSection";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof DocsSection> = {title: "Portal/DeveloperDocs/DocsSection",diff --git a/frontend/editor/src/portal/components/docs/EndpointReferenceSection.stories.tsx b/frontend/editor/src/portal/components/docs/EndpointReferenceSection.stories.tsxindex c8a34f59a1..3b951aeee0 100644--- a/frontend/editor/src/portal/components/docs/EndpointReferenceSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/EndpointReferenceSection.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { EndpointReferenceSection } from "@portal/components/docs/EndpointReferenceSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof EndpointReferenceSection> = {title: "Portal/DeveloperDocs/EndpointReferenceSection",diff --git a/frontend/editor/src/portal/components/docs/EndpointReferenceSection.tsx b/frontend/editor/src/portal/components/docs/EndpointReferenceSection.tsxindex 0a54de7658..fe6be97029 100644--- a/frontend/editor/src/portal/components/docs/EndpointReferenceSection.tsx+++ b/frontend/editor/src/portal/components/docs/EndpointReferenceSection.tsx@@ -2,7 +2,7 @@ import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { MethodBadge, Tabs, type TabItem } from "@app/ui";import { VERTICALS, ALL_ENDPOINTS } from "@portal/data/endpoints";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";import "@portal/theme/surface.css";type VerticalFilter = "all" | (typeof VERTICALS)[number]["key"];diff --git a/frontend/editor/src/portal/components/docs/ErrorsSection.stories.tsx b/frontend/editor/src/portal/components/docs/ErrorsSection.stories.tsxindex 2437bc75bd..2b0af24d1b 100644--- a/frontend/editor/src/portal/components/docs/ErrorsSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/ErrorsSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { ErrorsSection } from "@portal/components/docs/ErrorsSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof ErrorsSection> = {title: "Portal/DeveloperDocs/ErrorsSection",diff --git a/frontend/editor/src/portal/components/docs/ErrorsSection.tsx b/frontend/editor/src/portal/components/docs/ErrorsSection.tsxindex 25f7f77198..5eab9fdb60 100644--- a/frontend/editor/src/portal/components/docs/ErrorsSection.tsx+++ b/frontend/editor/src/portal/components/docs/ErrorsSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { CodeBlock, StatusBadge } from "@app/ui";import type { ApiErrorRow } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function ErrorsSection({ errors }: { errors: ApiErrorRow[] }) {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/docs/GettingStartedSection.stories.tsx b/frontend/editor/src/portal/components/docs/GettingStartedSection.stories.tsxindex 18e8b3a289..e8d4d1c5cc 100644--- a/frontend/editor/src/portal/components/docs/GettingStartedSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/GettingStartedSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { GettingStartedSection } from "@portal/components/docs/GettingStartedSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const { quickstartSamples, quickstartResponse } = docsContentFor("pro");diff --git a/frontend/editor/src/portal/components/docs/GettingStartedSection.tsx b/frontend/editor/src/portal/components/docs/GettingStartedSection.tsxindex 50b34e264b..5a871956ce 100644--- a/frontend/editor/src/portal/components/docs/GettingStartedSection.tsx+++ b/frontend/editor/src/portal/components/docs/GettingStartedSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { Card, CodeBlock } from "@app/ui";import type { CodeSample } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";import { LangSnippet } from "@portal/components/docs/LangSnippet";export function GettingStartedSection({diff --git a/frontend/editor/src/portal/components/docs/LangSnippet.stories.tsx b/frontend/editor/src/portal/components/docs/LangSnippet.stories.tsxindex ea3d64d585..bb47ae4030 100644--- a/frontend/editor/src/portal/components/docs/LangSnippet.stories.tsx+++ b/frontend/editor/src/portal/components/docs/LangSnippet.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { LangSnippet } from "@portal/components/docs/LangSnippet";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const { quickstartSamples } = docsContentFor("pro");diff --git a/frontend/editor/src/portal/components/docs/PlaybooksSection.stories.tsx b/frontend/editor/src/portal/components/docs/PlaybooksSection.stories.tsxindex a914b22781..f5304d3ad8 100644--- a/frontend/editor/src/portal/components/docs/PlaybooksSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/PlaybooksSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { PlaybooksSection } from "@portal/components/docs/PlaybooksSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof PlaybooksSection> = {title: "Portal/DeveloperDocs/PlaybooksSection",diff --git a/frontend/editor/src/portal/components/docs/PlaybooksSection.tsx b/frontend/editor/src/portal/components/docs/PlaybooksSection.tsxindex bfeddbd827..3d6f3b3eb4 100644--- a/frontend/editor/src/portal/components/docs/PlaybooksSection.tsx+++ b/frontend/editor/src/portal/components/docs/PlaybooksSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { Button, Card, Chip } from "@app/ui";import type { Playbook } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function PlaybooksSection({ playbooks }: { playbooks: Playbook[] }) {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/docs/RateLimitsSection.stories.tsx b/frontend/editor/src/portal/components/docs/RateLimitsSection.stories.tsxindex e2a5b0bf60..e5c7f75f0a 100644--- a/frontend/editor/src/portal/components/docs/RateLimitsSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/RateLimitsSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { RateLimitsSection } from "@portal/components/docs/RateLimitsSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof RateLimitsSection> = {title: "Portal/DeveloperDocs/RateLimitsSection",diff --git a/frontend/editor/src/portal/components/docs/RateLimitsSection.tsx b/frontend/editor/src/portal/components/docs/RateLimitsSection.tsxindex 92a7f87696..723acea908 100644--- a/frontend/editor/src/portal/components/docs/RateLimitsSection.tsx+++ b/frontend/editor/src/portal/components/docs/RateLimitsSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { Card, CodeBlock } from "@app/ui";import type { RateLimit } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function RateLimitsSection({ rateLimit }: { rateLimit: RateLimit }) {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/docs/SdksSection.stories.tsx b/frontend/editor/src/portal/components/docs/SdksSection.stories.tsxindex b7e76c63dd..aa6283bc66 100644--- a/frontend/editor/src/portal/components/docs/SdksSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/SdksSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { SdksSection } from "@portal/components/docs/SdksSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const { sdks } = docsContentFor("pro");diff --git a/frontend/editor/src/portal/components/docs/SdksSection.tsx b/frontend/editor/src/portal/components/docs/SdksSection.tsxindex 331117af68..c1df517523 100644--- a/frontend/editor/src/portal/components/docs/SdksSection.tsx+++ b/frontend/editor/src/portal/components/docs/SdksSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { Card, CodeBlock, StatusBadge } from "@app/ui";import type { Sdk, SdkStatus } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";/** GA clients carry no badge; only non-stable maturity is called out. */const STATUS_BADGE: Partial<diff --git a/frontend/editor/src/portal/components/docs/SkillsSection.stories.tsx b/frontend/editor/src/portal/components/docs/SkillsSection.stories.tsxindex 2bec0fc448..26ba25dcba 100644--- a/frontend/editor/src/portal/components/docs/SkillsSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/SkillsSection.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { docsContentFor } from "@portal/mocks/docs";import { SkillsSection } from "@portal/components/docs/SkillsSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof SkillsSection> = {title: "Portal/DeveloperDocs/SkillsSection",diff --git a/frontend/editor/src/portal/components/docs/SkillsSection.tsx b/frontend/editor/src/portal/components/docs/SkillsSection.tsxindex e373fc25c3..130b67c389 100644--- a/frontend/editor/src/portal/components/docs/SkillsSection.tsx+++ b/frontend/editor/src/portal/components/docs/SkillsSection.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { Card } from "@app/ui";import type { AgentSkill } from "@portal/api/docs";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function SkillsSection({ skills }: { skills: AgentSkill[] }) {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/docs/WebhooksSection.stories.tsx b/frontend/editor/src/portal/components/docs/WebhooksSection.stories.tsxindex 34e352dfc2..baaa10da97 100644--- a/frontend/editor/src/portal/components/docs/WebhooksSection.stories.tsx+++ b/frontend/editor/src/portal/components/docs/WebhooksSection.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { WebhooksSection } from "@portal/components/docs/WebhooksSection";-import "@portal/views/DeveloperDocs.css";+import "@core/components/docs/DeveloperDocs.css";const meta: Meta<typeof WebhooksSection> = {title: "Portal/DeveloperDocs/WebhooksSection",diff --git a/frontend/editor/src/portal/components/docs/WebhooksSection.tsx b/frontend/editor/src/portal/components/docs/WebhooksSection.tsxindex 84ec30a6e0..78615ff66e 100644--- a/frontend/editor/src/portal/components/docs/WebhooksSection.tsx+++ b/frontend/editor/src/portal/components/docs/WebhooksSection.tsx@@ -1,6 +1,6 @@import { useTranslation } from "react-i18next";import { Card, CodeBlock } from "@app/ui";-import { DocsSection } from "@portal/components/docs/DocsSection";+import { DocsSection } from "@core/components/docs/DocsSection";export function WebhooksSection() {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/infrastructure/ApiKeyCard.stories.tsx b/frontend/editor/src/portal/components/infrastructure/ApiKeyCard.stories.tsxindex e95194e0d2..c562054c52 100644--- a/frontend/editor/src/portal/components/infrastructure/ApiKeyCard.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/ApiKeyCard.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { ApiKeyCard } from "@portal/components/infrastructure/ApiKeyCard";import type { ApiKey } from "@portal/api/infrastructure";-import "@portal/views/Infrastructure.css";+import "@portal/components/infrastructure/infrastructure.css";const BASE: ApiKey = {id: "key-1",diff --git a/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.stories.tsx b/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.stories.tsxindex 7b271f135d..bd4e9da2ae 100644--- a/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { http, HttpResponse, delay } from "msw";import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";-import "@portal/views/Infrastructure.css";+import "@portal/components/infrastructure/infrastructure.css";const meta: Meta<typeof ApiKeysTab> = {title: "Portal/Infrastructure/ApiKeysTab",diff --git a/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.tsx b/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.tsxindex a826e18caa..784b2655af 100644--- a/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.tsx+++ b/frontend/editor/src/portal/components/infrastructure/ApiKeysTab.tsx@@ -12,6 +12,7 @@ import { errorMessage } from "@portal/api/http";import { ApiKeyCard } from "@portal/components/infrastructure/ApiKeyCard";import { CreateKeyModal } from "@portal/components/infrastructure/CreateKeyModal";import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import "@portal/components/infrastructure/infrastructure.css";export function ApiKeysTab() {const { t } = useTranslation();diff --git a/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsx b/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsxindex dc12295a32..cf358431f4 100644--- a/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { http, HttpResponse } from "msw";import { AuditExportModal } from "@portal/components/infrastructure/AuditExportModal";-import "@portal/views/Infrastructure.css";+import "@portal/components/infrastructure/infrastructure.css";/*** Export modal for the Infrastructure → Audit tab. Rendered always-open here.diff --git a/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsx b/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsxindex 3733b2aca9..8d22cc53e6 100644--- a/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { http, HttpResponse, delay } from "msw";import { AuditTab } from "@portal/components/infrastructure/AuditTab";-import "@portal/views/Infrastructure.css";+import "@portal/components/infrastructure/infrastructure.css";const meta: Meta<typeof AuditTab> = {title: "Portal/Infrastructure/AuditTab",diff --git a/frontend/editor/src/portal/components/infrastructure/AuditTab.tsx b/frontend/editor/src/portal/components/infrastructure/AuditTab.tsxindex 548934d58a..a7724b2c3e 100644--- a/frontend/editor/src/portal/components/infrastructure/AuditTab.tsx+++ b/frontend/editor/src/portal/components/infrastructure/AuditTab.tsx@@ -26,6 +26,7 @@ import {AUDIT_STATUS_LABEL,AUDIT_TONE,} from "@portal/components/infrastructure/infraFormat";+import "@portal/components/infrastructure/infrastructure.css";type AuditFilter = "all" | AuditCategory;diff --git a/frontend/editor/src/portal/components/infrastructure/CreateKeyModal.stories.tsx b/frontend/editor/src/portal/components/infrastructure/CreateKeyModal.stories.tsxindex ba5e3bc6a5..b0df2e260b 100644--- a/frontend/editor/src/portal/components/infrastructure/CreateKeyModal.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/CreateKeyModal.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { CreateKeyModal } from "@portal/components/infrastructure/CreateKeyModal";-import "@portal/views/Infrastructure.css";+import "@portal/components/infrastructure/infrastructure.css";const meta: Meta<typeof CreateKeyModal> = {title: "Portal/Infrastructure/CreateKeyModal",diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsxindex 752e06dacb..2e6663cfb9 100644--- a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsx@@ -7,9 +7,9 @@ import type {MigrationStatus,StorageEncryptionStatus,} from "@portal/api/storageEncryption";-// SectionHeader's styles live in Infrastructure.css, and the real view loads it,-// so the stories load it too or they render larger than the app does.-import "@portal/views/Infrastructure.css";+// SectionHeader's styles live in infrastructure.css, which the panel loads too;+// without it the stories render larger than the app does.+import "@portal/components/infrastructure/infrastructure.css";const BASE = "/api/v1/admin/storage-encryption";diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsxindex b0a33d1ab3..9d9ff3cb6c 100644--- a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx@@ -32,6 +32,7 @@ import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";import { EncryptionKeyTable } from "@portal/components/infrastructure/EncryptionKeyTable";import { EncryptionMigrationCard } from "@portal/components/infrastructure/EncryptionMigrationCard";import { EncryptionRotationCard } from "@portal/components/infrastructure/EncryptionRotationCard";+import "@portal/components/infrastructure/infrastructure.css";import "@portal/components/infrastructure/EncryptionPanel.css";/** How often to re-read migration progress while a run is going. */diff --git a/frontend/editor/src/portal/components/infrastructure/SectionHeader.stories.tsx b/frontend/editor/src/portal/components/infrastructure/SectionHeader.stories.tsxindex b7f9a83019..997ce9f464 100644--- a/frontend/editor/src/portal/components/infrastructure/SectionHeader.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/SectionHeader.stories.tsx@@ -1,6 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";-import "@portal/views/Infrastructure.css";+import "@portal/components/infrastructure/infrastructure.css";const meta: Meta<typeof SectionHeader> = {title: "Portal/Infrastructure/SectionHeader",diff --git a/frontend/editor/src/portal/views/Infrastructure.css b/frontend/editor/src/portal/components/infrastructure/infrastructure.csssimilarity index 100%rename from frontend/editor/src/portal/views/Infrastructure.cssrename to frontend/editor/src/portal/components/infrastructure/infrastructure.cssdiff --git a/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx b/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsxindex 626cc8e9fb..af2a13b6e5 100644--- a/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx+++ b/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx@@ -1,4 +1,4 @@-import { useView } from "@portal/contexts/ViewContext";+import { useUI } from "@portal/contexts/UIContext";import { DealStatusHero } from "@portal/components/procurement/DealStatusHero";import type { ProcurementController } from "@portal/components/procurement/useProcurement";@@ -11,7 +11,7 @@ export function ControlledDealStatusHero({}: {controller: ProcurementController;}) {- const { setActiveView } = useView();+ const { openSettings } = useUI();if (!controller.data) return null;return (<DealStatusHero@@ -26,7 +26,7 @@ export function ControlledDealStatusHero({}onAcceptQuote={() => void controller.onAcceptQuote()}onLicense={() => controller.setExtra("license")}- onInvite={() => setActiveView("users")}+ onInvite={() => openSettings("users")}onSchedule={() => controller.setExtra("schedule")}onManageTrial={() => controller.setExtra("trial")}onDocuments={() => controller.setExtra("documents")}diff --git a/frontend/editor/src/portal/components/settings/BillingSettingsSection.css b/frontend/editor/src/portal/components/settings/BillingSettingsSection.cssnew file mode 100644index 0000000000..1fe2d7f7cf--- /dev/null+++ b/frontend/editor/src/portal/components/settings/BillingSettingsSection.css@@ -0,0 +1,6 @@+/* The ask sits where the wallet would, at the same measure as a settings section. */+.billing-settings__gate {+ max-width: 60rem;+ margin-inline: auto;+ padding: 3rem 2rem;+}diff --git a/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsx b/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsxnew file mode 100644index 0000000000..e69107907e--- /dev/null+++ b/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsx@@ -0,0 +1,56 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Button, EmptyState } from "@app/ui";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import { useApplyLinkFacts } from "@portal/contexts/LinkContext";+import { useUI } from "@portal/contexts/UIContext";+import { useConnectGate } from "@portal/hooks/useConnectGate";+import { Usage } from "@portal/views/Usage";+import type { Wallet } from "@portal/api/billing";+import "@portal/components/settings/BillingSettingsSection.css";++/**+ * Usage & Billing as a settings section. The processor's route used+ * ConnectGuardedRoute, which answers "not linked" by navigating to the+ * processor home - inside settings that would throw the user out of the page+ * they just opened. Here an unlinked instance gets the ask in place instead.+ *+ * Usage must not render while unlinked: its onWalletLoaded reports linked as a+ * fact, and a browser can hold a SaaS session with no link to this server.+ */+export function BillingSettingsSection() {+ const { t } = useTranslation();+ const { gated, loading, connect } = useConnectGate();+ const applyLinkFacts = useApplyLinkFacts();+ const { openLinkModal } = useUI();++ const onWalletLoaded = useCallback(+ (w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),+ [applyLinkFacts],+ );+ const onReauth = useCallback(() => openLinkModal("reauth"), [openLinkModal]);++ // Unknown is not gated: showing the ask first would flash it at a linked admin.+ if (loading) return <LoadingFallback />;++ if (gated) {+ return (+ <div className="billing-settings__gate">+ <EmptyState+ title={t("portal.nav.usage", "Usage & Billing")}+ description={t(+ "portal.accountLink.panel.sub",+ "Link this self-hosted org to its Stirling account so unattended processing bills against your org wallet.",+ )}+ actions={+ <Button variant="primary" onClick={connect}>+ {t("portal.shell.sidebar.linkAccount", "Link Stirling account")}+ </Button>+ }+ />+ </div>+ );+ }++ return <Usage onWalletLoaded={onWalletLoaded} onReauth={onReauth} />;+}diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.css b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.cssnew file mode 100644index 0000000000..e02dd9f2f8--- /dev/null+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.css@@ -0,0 +1,20 @@+/* Portal views assume the shell's full-height scroll column; as a settings+ section the page owns the scrolling, so their height goes back to content and+ their own max-width gives way to the pane's. */+.portal-settings-section {+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.portal-settings-section .portal-users {+ max-width: none;+}++/* Former tab panels: their host supplied the page gutter, so this does now. */+.portal-settings-section__padded {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+}diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsxnew file mode 100644index 0000000000..367e5054c1--- /dev/null+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx@@ -0,0 +1,58 @@+import { type ReactNode } from "react";+import { QueryClientProvider } from "@tanstack/react-query";+import { getPortalQueryClient } from "@portal/queryClient";+import { LinkProvider } from "@portal/contexts/LinkContext";+import { TierProvider } from "@portal/contexts/TierContext";+import { UIProvider } from "@portal/contexts/UIContext";+import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";+import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";+import { ErrorBoundary } from "@portal/components/ErrorBoundary";+import { useUI } from "@portal/contexts/UIContext";+import "@portal/theme/base.css";+import "@portal/components/settings/PortalSettingsSectionHost.css";++/** The one account-link dialog for this subtree, mounted only while open. */+function LinkModalHost() {+ const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =+ useUI();+ if (!linkModalOpen) return null;+ return (+ <LinkAccountModal+ open+ mode={linkModalMode}+ onClose={closeLinkModal}+ outcome={connectOutcome}+ />+ );+}++/**+ * Runs a portal-authored view inside the settings page. Those views are written+ * against the portal's own data and UI contexts and its scoped CSS reset, none+ * of which the editor tree provides — this host supplies exactly that much of+ * the portal, and nothing of its chrome. The query client is the portal's+ * shared singleton, so a view opened here and the same view opened in the+ * processor read one cache.+ */+export function PortalSettingsSectionHost({+ children,+}: {+ children: ReactNode;+}) {+ return (+ <QueryClientProvider client={getPortalQueryClient()}>+ <div className="portal-settings-section portal-scope">+ <LinkProvider initialState="unlinked">+ <TierProvider>+ <UIProvider>+ <AccountLinkProvider>+ <ErrorBoundary>{children}</ErrorBoundary>+ <LinkModalHost />+ </AccountLinkProvider>+ </UIProvider>+ </TierProvider>+ </LinkProvider>+ </div>+ </QueryClientProvider>+ );+}diff --git a/frontend/editor/src/portal/components/settings/portalSettingsSections.tsx b/frontend/editor/src/portal/components/settings/portalSettingsSections.tsxnew file mode 100644index 0000000000..45ac1d39c5--- /dev/null+++ b/frontend/editor/src/portal/components/settings/portalSettingsSections.tsx@@ -0,0 +1,82 @@+import { Suspense, lazy, type ComponentType } from "react";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import { useEnterpriseEnabled } from "@portal/hooks/useEnterpriseEnabled";+import { PortalSettingsSectionHost } from "@portal/components/settings/PortalSettingsSectionHost";+import { accountLinkSettings } from "@portal/components/settings/accountLinkSettings";++const Users = lazy(async () => {+ const m = await import("@portal/views/Users");+ return { default: m.Users };+});++const ApiKeys = lazy(async () => {+ const m = await import("@portal/components/infrastructure/ApiKeysTab");+ return { default: m.ApiKeysTab };+});++const Audit = lazy(async () => {+ const m = await import("@portal/components/infrastructure/AuditTab");+ return { default: m.AuditTab };+});++const EncryptionPanel = lazy(async () => {+ const m = await import("@portal/components/infrastructure/EncryptionPanel");+ return { default: m.EncryptionPanel };+});++/** Treat "still resolving" as available: flashing "your licence records no audit+ * trail" at an Enterprise operator is worse than the notice arriving a beat late. */+function Encryption() {+ const enterprise = useEnterpriseEnabled();+ return (+ <EncryptionPanel+ auditAvailable={enterprise.loading || enterprise.enabled}+ />+ );+}++const Billing = lazy(async () => {+ const m = await import("@portal/components/settings/BillingSettingsSection");+ return { default: m.BillingSettingsSection };+});++/** `padded`: for views that were tab panels and left the page gutter to their host. */+function hosted(View: ComponentType, { padded = false } = {}) {+ return function HostedPortalSection() {+ return (+ <PortalSettingsSectionHost>+ <Suspense fallback={<LoadingFallback />}>+ {padded ? (+ <div className="portal-settings-section__padded">+ <View />+ </div>+ ) : (+ <View />+ )}+ </Suspense>+ </PortalSettingsSectionHost>+ );+ };+}++/**+ * The processor's server administration as settings sections: the org roster,+ * API keys, audit, encryption at rest, and the account's billing. They+ * configure the whole deployment rather than a step in a document pipeline, so+ * they belong on the settings page and the processor keeps only its workflow.+ *+ * Each is a portal-authored view wrapped in {@link PortalSettingsSectionHost}+ * for the contexts it expects. The nav entries that mount these (labels, keys,+ * aliases) live in the proprietary layer, so a build without the processor+ * never pulls this module - and with it the portal chunk - into its graph.+ */+export const PortalUsersSection = hosted(Users);+export const PortalApiKeysSection = hosted(ApiKeys, { padded: true });+export const PortalAuditSection = hosted(Audit, { padded: true });+export const PortalEncryptionSection = hosted(Encryption, { padded: true });+export const PortalBillingSection = hosted(Billing);++/** Self-hosted only: on SaaS the signed-in account IS the account, so there is+ * no instance to link and the seam is null. */+export const PortalAccountLinkSection: ComponentType | null =+ accountLinkSettings ? hosted(accountLinkSettings.Body) : null;diff --git a/frontend/editor/src/portal/components/sidebarGroups.tsx b/frontend/editor/src/portal/components/sidebarGroups.tsxindex a72298e3be..cb48848b57 100644--- a/frontend/editor/src/portal/components/sidebarGroups.tsx+++ b/frontend/editor/src/portal/components/sidebarGroups.tsx@@ -2,15 +2,11 @@ import { type ReactNode } from "react";import { type ViewId } from "@portal/contexts/ViewContext";import {HomeIcon,- UsersIcon,SourcesIcon,IntegrationsIcon,PipelinesIcon,DocumentsIcon,ReviewIcon,- InfrastructureIcon,- UsageIcon,- DocsIcon,} from "@portal/components/icons";export interface NavEntry {@@ -31,21 +27,21 @@ export interface NavGroup {// Sidebar nav groups. This is a flavor seam: the SaaS build shadows this file to// drop sections not yet shipped there (see src/portal-saas/components/sidebarGroups).-// The processor's own workflow: home plus the pipeline it feeds. Policies were folded into-// Pipelines (a policy is a pipeline the org requires), so there's no separate Policies tab.+// The processor's own workflow: home, the pipeline it feeds, and what it connects out to.+// Policies were folded into Pipelines (a policy is a pipeline the org requires), so there's no+// separate Policies tab.export const GROUP_PROCESSOR: NavEntry[] = [{ id: "home", icon: <HomeIcon /> },{ id: "sources", icon: <SourcesIcon /> },{ id: "pipelines", icon: <PipelinesIcon /> },{ id: "documents", icon: <DocumentsIcon /> },{ id: "review", icon: <ReviewIcon /> },-];--// The wider platform around the processor: people, connections, infra, billing, docs.-export const GROUP_PLATFORM: NavEntry[] = [- { id: "users", icon: <UsersIcon /> },{ id: "integrations", icon: <IntegrationsIcon /> },- { id: "infrastructure", icon: <InfrastructureIcon /> },- { id: "usage", icon: <UsageIcon />, requiresAdmin: true },- { id: "docs", icon: <DocsIcon /> },];++/**+ * Empty on purpose, so the flavor seam and the shell keep their shape. Server+ * administration (users, infrastructure, billing) is product-wide and lives on+ * the settings page; the docs browser is reference material and lives at /docs.+ */+export const GROUP_PLATFORM: NavEntry[] = [];diff --git a/frontend/editor/src/portal/components/sources/SourceModal.tsx b/frontend/editor/src/portal/components/sources/SourceModal.tsxindex b79c908afc..db83b8fdfb 100644--- a/frontend/editor/src/portal/components/sources/SourceModal.tsx+++ b/frontend/editor/src/portal/components/sources/SourceModal.tsx@@ -19,7 +19,7 @@ import {isFolderAccessDeniedError,type Source,} from "@portal/api/sources";-import { useUI } from "@portal/contexts/UIContext";+import { getSettingsUrl } from "@app/utils/settingsNavigation";import { useQueryClient } from "@tanstack/react-query";import { qk } from "@portal/queries/keys";import { creatableSourceTypes } from "@portal/components/sources/creatableSourceTypes";@@ -119,7 +119,6 @@ export function SourceModal({onSaved,}: SourceModalProps) {const { t } = useTranslation();- const { openSettings } = useUI();const queryClient = useQueryClient();const isEdit = Boolean(sourceId);@@ -675,7 +674,15 @@ export function SourceModal({<Buttonvariant="secondary"size="sm"- onClick={() => openSettings("adminFolderAccess")}+ // A new tab: this dialog holds an unsaved draft, and+ // settings is a route now, not an overlay over it.+ onClick={() =>+ window.open(+ getSettingsUrl("adminFolderAccess"),+ "_blank",+ "noopener,noreferrer",+ )+ }>{t("portal.sources.builder.folderAccess.openSettings")}</Button>diff --git a/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsx b/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsxindex 75da086806..4382a3592a 100644--- a/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsx+++ b/frontend/editor/src/portal/components/users/UsersDirectory.stories.tsx@@ -23,6 +23,7 @@ const FULL_CAPS: UsersCapabilities = {seats: false,manageGrants: true,removeScope: "org",+ removeMember: true,listingRequiresAdmin: true,};@@ -45,6 +46,7 @@ const SAAS_CAPS: UsersCapabilities = {seats: true,manageGrants: false,removeScope: "team",+ removeMember: true,listingRequiresAdmin: false,};diff --git a/frontend/editor/src/portal/components/users/UsersDirectory.tsx b/frontend/editor/src/portal/components/users/UsersDirectory.tsxindex 7f979fbf56..aea7ba0487 100644--- a/frontend/editor/src/portal/components/users/UsersDirectory.tsx+++ b/frontend/editor/src/portal/components/users/UsersDirectory.tsx@@ -38,7 +38,8 @@ interface UsersDirectoryProps {processorTeamIds: Set<number>;onGrantTeamProcessor: (team: TeamGroup) => void;onRevokeTeamProcessor: (team: TeamGroup) => void;- onAddToTeam: (team: TeamGroup) => void;+ /** Null when the viewer may not add members; the control is then omitted. */+ onAddToTeam: ((team: TeamGroup) => void) | null;// Per-member admin actions (the row kebab).onResetPassword: (member: Member) => void;onMoveToTeam: (member: Member) => void;@@ -160,13 +161,15 @@ export function UsersDirectory({onClick: () => onDisableMfa(m),});}- items.push({- label: removeLabel,- tone: "danger",- disabled: m.isSelf,- onClick: () => onRemove(m),- dividerBefore: items.length > 0,- });+ if (capabilities.removeMember) {+ items.push({+ label: removeLabel,+ tone: "danger",+ disabled: m.isSelf,+ onClick: () => onRemove(m),+ dividerBefore: items.length > 0,+ });+ }return {label: t("users.rowActions", "Actions for {{name}}", { name: m.name }),glyph: "kebab",@@ -271,7 +274,16 @@ export function UsersDirectory({);}- cols.push(column.actions({ key: "actions", get: (m) => [rowKebab(m)] }));+ // A reader gets no kebab at all rather than an empty menu.+ cols.push(+ column.actions({+ key: "actions",+ get: (m) => {+ const kebab = rowKebab(m);+ return kebab.menu && kebab.menu.length > 0 ? [kebab] : [];+ },+ }),+ );return cols;}, [t,@@ -305,12 +317,15 @@ export function UsersDirectory({);}function teamActions(team: TeamGroup): CellAction[] {- const acts: CellAction[] = [- {- label: t("users.group.addToTeam", "Add to team"),- onClick: () => onAddToTeam(team),- },- ];+ const add = onAddToTeam;+ const acts: CellAction[] = add+ ? [+ {+ label: t("users.group.addToTeam", "Add to team"),+ onClick: () => add(team),+ },+ ]+ : [];if (teamKebabHasItems(team)) {const items: CellMenuItem[] = [];if (capabilities.manageGrants) {diff --git a/frontend/editor/src/portal/contexts/UIContext.tsx b/frontend/editor/src/portal/contexts/UIContext.tsxindex b4df9c5618..73c9d73307 100644--- a/frontend/editor/src/portal/contexts/UIContext.tsx+++ b/frontend/editor/src/portal/contexts/UIContext.tsx@@ -5,6 +5,8 @@ import {useState,type ReactNode,} from "react";+import { navigateToSettings } from "@app/utils/settingsNavigation";+import type { NavKey } from "@app/components/shared/config/types";import type { ConnectOutcome } from "@portal/components/account-link/ConnectCallbackView";/**@@ -28,23 +30,14 @@ interface UIContextValue {closeAssistant: () => void;toggleAssistant: () => void;- /** Settings is a modal overlay, not a route. */- settingsOpen: boolean;/**- * The section the Settings modal should land on when opened. `null` lets the- * modal pick its own default. Cleared back to `null` on close.+ * Leave for the settings page, optionally on a named section and scrolled to+ * one control. Settings is app-wide and lives outside the processor, so this+ * navigates rather than opening an overlay.*/- settingsInitialSection: string | null;- settingsInitialFocus: string | null;openSettings: (section?: string, focus?: string) => void;- closeSettings: () => void;- /**- * The account-link login modal. A single top-level instance — never nested in- * another overlay. Opening it from within Settings closes Settings first (no- * modal-in-modal) and reopens Settings on the account-link section once the- * login modal closes, so the admin returns to where they were.- */+ /** The account-link login modal. A single top-level instance. */linkModalOpen: boolean;linkModalMode: LinkModalMode;openLinkModal: (mode?: LinkModalMode) => void;@@ -91,25 +84,12 @@ export function UIProvider({ children }: { children: ReactNode }) {const [sidebarCollapsed, setSidebarCollapsed] =useState(readSidebarCollapsed);const [assistantOpen, setAssistantOpen] = useState(false);- const [settingsOpen, setSettingsOpen] = useState(false);- const [settingsInitialSection, setSettingsInitialSection] = useState<- string | null- >(null);- const [settingsInitialFocus, setSettingsInitialFocus] = useState<- string | null- >(null);const [linkModalOpen, setLinkModalOpen] = useState(false);const [trialSetupRequested, setTrialSetupRequested] = useState(false);const [linkModalMode, setLinkModalMode] = useState<LinkModalMode>("link");const [connectOutcome, setConnectOutcome] = useState<ConnectOutcome | null>(null,);- // When the link modal is opened from inside Settings, remember the section to- // restore so closing the modal returns the admin to where they were.- const [reopenSettingsAfterLink, setReopenSettingsAfterLink] = useState<- string | null- >(null);-const value = useMemo<UIContextValue>(() => ({// Opening any overlay (settings, link modal) dismisses the mobile nav@@ -132,19 +112,9 @@ export function UIProvider({ children }: { children: ReactNode }) {closeAssistant: () => setAssistantOpen(false),toggleAssistant: () => setAssistantOpen((o) => !o),- settingsOpen,- settingsInitialSection,- settingsInitialFocus,openSettings: (section?: string, focus?: string) => {setMobileNavOpen(false);- setSettingsInitialSection(section ?? null);- setSettingsInitialFocus(focus ?? null);- setSettingsOpen(true);- },- closeSettings: () => {- setSettingsOpen(false);- setSettingsInitialSection(null);- setSettingsInitialFocus(null);+ navigateToSettings(section as NavKey | undefined, focus);},linkModalOpen,@@ -152,14 +122,6 @@ export function UIProvider({ children }: { children: ReactNode }) {openLinkModal: (mode: LinkModalMode = "link") => {setMobileNavOpen(false);setLinkModalMode(mode);- // Never stack on Settings: close it first, and remember to reopen it on- // the account-link section once the login modal closes.- if (settingsOpen) {- setReopenSettingsAfterLink("account-link");- setSettingsOpen(false);- setSettingsInitialSection(null);- setSettingsInitialFocus(null);- }setLinkModalOpen(true);},trialSetupRequested,@@ -181,24 +143,14 @@ export function UIProvider({ children }: { children: ReactNode }) {setLinkModalMode("link");// A reopen from a CTA is a fresh flow, not a handshake already dismissed.setConnectOutcome(null);- if (reopenSettingsAfterLink) {- setSettingsInitialSection(reopenSettingsAfterLink);- setSettingsInitialFocus(null);- setSettingsOpen(true);- setReopenSettingsAfterLink(null);- }},}),[mobileNavOpen,sidebarCollapsed,assistantOpen,- settingsOpen,- settingsInitialSection,- settingsInitialFocus,linkModalOpen,linkModalMode,- reopenSettingsAfterLink,trialSetupRequested,connectOutcome,],diff --git a/frontend/editor/src/portal/hooks/useOpenPlan.ts b/frontend/editor/src/portal/hooks/useOpenPlan.tsindex 57b30c91d0..2cd4181382 100644--- a/frontend/editor/src/portal/hooks/useOpenPlan.ts+++ b/frontend/editor/src/portal/hooks/useOpenPlan.ts@@ -1,13 +1,12 @@import { useCallback } from "react";-import { useView } from "@portal/contexts/ViewContext";+import { useUI } from "@portal/contexts/UIContext";/**- * Self-hosted processor: settings carries no Plan section (it is a cloud- * surface, and this build's registry has none), so the footer's credits row- * opens the portal's own Usage & Billing view instead — the same figures, on- * the surface this flavor actually owns.+ * Self-hosted processor: settings carries no cloud Plan section, so the+ * footer's credits row opens the Usage & Billing settings section — the same+ * figures, on the surface this flavor actually owns.*/export function useOpenPlan(): (() => void) | null {- const { setActiveView } = useView();- return useCallback(() => setActiveView("usage"), [setActiveView]);+ const { openSettings } = useUI();+ return useCallback(() => openSettings("billing"), [openSettings]);}diff --git a/frontend/editor/src/portal/hooks/usePortalSearchResults.tsx b/frontend/editor/src/portal/hooks/usePortalSearchResults.tsxindex b839d980d6..e1ec6c1f6f 100644--- a/frontend/editor/src/portal/hooks/usePortalSearchResults.tsx+++ b/frontend/editor/src/portal/hooks/usePortalSearchResults.tsx@@ -5,7 +5,6 @@ import { useQuery } from "@tanstack/react-query";import { getToolUrlPath } from "@app/data/toolsTaxonomy";import { isPortalEntityScopeAccessible } from "@app/data/processorSearchIndex";import { useAppConfig } from "@app/contexts/AppConfigContext";-import { PORTAL_HIDDEN_SECTION_KEYS } from "@portal/components/PortalSettingsHost";import { useToolRegistry } from "@app/contexts/ToolRegistryContext";import {assembleSuperSearchGroups,@@ -236,6 +235,8 @@ export function usePortalSearchResults(? {isAdmin: config.isAdmin ?? false,loginEnabled: config.enableLogin ?? false,+ // Being in the processor is proof of access to it.+ portalAccessible: true,showSettingsWhenNoLogin: config.showSettingsWhenNoLogin ?? true,}: null,@@ -255,14 +256,7 @@ export function usePortalSearchResults(const settingsGroups = assembleSuperSearchGroups({settings: scopeEnabled("settings")- ? rankSettingsResults(- trimmed,- t,- gates,- openSettingsSection,- undefined,- PORTAL_HIDDEN_SECTION_KEYS,- )+ ? rankSettingsResults(trimmed, t, gates, openSettingsSection): [],},t,diff --git a/frontend/editor/src/portal/search/entitySearch.tsx b/frontend/editor/src/portal/search/entitySearch.tsxindex f0338bd620..98ef8b9b76 100644--- a/frontend/editor/src/portal/search/entitySearch.tsx+++ b/frontend/editor/src/portal/search/entitySearch.tsx@@ -31,8 +31,9 @@ import {} from "@portal/components/icons";import type { Tier } from "@portal/contexts/TierContext";import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";-import { allDocs, loadDocsNav } from "@portal/docs/manifest/registry";-import { searchDocs, toPlainText, type SearchDoc } from "@portal/docs/search";+import { DOCS_PATH } from "@app/routes/docsRoute";+import { allDocs, loadDocsNav } from "@core/docs/manifest/registry";+import { searchDocs, toPlainText, type SearchDoc } from "@core/docs/search";/*** The Processor's entity search: users, policies, pipelines and sources,@@ -124,7 +125,7 @@ export function rankDocsResults(.trim() || result.sectionLabel,icon: <DocsIcon />,score: result.score,- onSelect: () => navigate(`${toPortalPath(VIEW_PATHS.docs)}#${result.id}`),+ onSelect: () => navigate(`${DOCS_PATH}#${result.id}`),}));}@@ -294,9 +295,7 @@ export function buildProcessorEntityGroups(icon: <UsersIcon />,score,onSelect: () =>- navigate(- `${toPortalPath(VIEW_PATHS.users)}?member=${encodeURIComponent(item.id)}`,- ),+ navigate(`/settings/users?member=${encodeURIComponent(item.id)}`),})): [];if (users.length > 0) {diff --git a/frontend/editor/src/portal/views/Infrastructure.test.tsx b/frontend/editor/src/portal/views/Infrastructure.test.tsxdeleted file mode 100644index e1473f7186..0000000000--- a/frontend/editor/src/portal/views/Infrastructure.test.tsx+++ /dev/null@@ -1,142 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";-import { MemoryRouter } from "react-router-dom";-import { MantineProvider } from "@mantine/core";--vi.mock("react-i18next", () => ({- useTranslation: () => ({- t: (key: string) => key,- i18n: { changeLanguage: vi.fn() },- }),-}));--vi.mock("@portal/contexts/ViewContext", () => ({- useView: () => ({ setActiveView: vi.fn() }),-}));--const enterprise = { enabled: true, loading: false };-vi.mock("@portal/hooks/useEnterpriseEnabled", () => ({- useEnterpriseEnabled: () => enterprise,-}));--vi.mock("@portal/components/infrastructure/ApiKeysTab", () => ({- ApiKeysTab: () => <div data-testid="api-keys-tab" />,-}));-vi.mock("@portal/components/infrastructure/AuditTab", () => ({- AuditTab: () => <div data-testid="audit-tab" />,-}));-vi.mock("@portal/components/infrastructure/EncryptionPanel", () => ({- EncryptionPanel: () => <div data-testid="storage-tab" />,-}));--import { Infrastructure } from "@portal/views/Infrastructure";--const T = "portal.infrastructure.tabs";--function renderView(initialPath = "/infrastructure") {- return render(- <MantineProvider>- <MemoryRouter initialEntries={[initialPath]}>- <Infrastructure />- </MemoryRouter>- </MantineProvider>,- );-}--function tabButtons() {- return screen- .getAllByRole("button")- .filter((b) => b.className.includes("sui-tabs__tab"));-}--describe("Infrastructure view", () => {- beforeEach(() => {- enterprise.enabled = true;- enterprise.loading = false;- });-- it("orders the working tabs first and defaults to API keys", () => {- renderView();-- expect(tabButtons().map((b) => b.textContent)).toEqual([- `${T}.apiKeys`,- `${T}.audit`,- `${T}.deployments`,- `${T}.security`,- `${T}.models`,- `${T}.storage`,- ]);- expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();- });-- it("renders the backend-less tabs as inert: disabled, aria-disabled, never active", () => {- renderView();-- // Storage is no longer in this list: it reads a real backend now.- const byLabel = new Map(tabButtons().map((b) => [b.textContent, b]));- for (const key of ["deployments", "security", "models"]) {- const btn = byLabel.get(`${T}.${key}`) as HTMLButtonElement;- expect(btn).toBeDisabled();- expect(btn).toHaveAttribute("aria-disabled", "true");- expect(btn).toHaveAttribute("aria-pressed", "false");-- fireEvent.click(btn);- expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();- }- });-- it("switches to the audit tab when clicked", () => {- renderView();-- fireEvent.click(screen.getByRole("button", { name: `${T}.audit` }));- expect(screen.getByTestId("audit-tab")).toBeInTheDocument();- expect(screen.queryByTestId("api-keys-tab")).not.toBeInTheDocument();- });-- it("honours ?tab=audit deep links (used by the home visualiser)", () => {- renderView("/infrastructure?tab=audit");-- expect(screen.getByTestId("audit-tab")).toBeInTheDocument();- });-- it("ignores a deep link to a disabled tab and stays on the default", () => {- renderView("/infrastructure?tab=models");-- expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();- expect(screen.queryByTestId("audit-tab")).not.toBeInTheDocument();- });-- it("switches to the storage tab when clicked", () => {- renderView();-- fireEvent.click(screen.getByRole("button", { name: `${T}.storage` }));- expect(screen.getByTestId("storage-tab")).toBeInTheDocument();- expect(screen.queryByTestId("api-keys-tab")).not.toBeInTheDocument();- });-- it("honours ?tab=storage deep links", () => {- renderView("/infrastructure?tab=storage");-- expect(screen.getByTestId("storage-tab")).toBeInTheDocument();- });-- it("disables the audit tab (inert, never opens) for non-enterprise users", () => {- enterprise.enabled = false;- renderView();-- const auditBtn = screen.getByRole("button", { name: `${T}.audit` });- expect(auditBtn).toBeDisabled();-- fireEvent.click(auditBtn);- expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();- expect(screen.queryByTestId("audit-tab")).not.toBeInTheDocument();- });-- it("ignores a ?tab=audit deep link when not enterprise", () => {- enterprise.enabled = false;- renderView("/infrastructure?tab=audit");-- expect(screen.getByTestId("api-keys-tab")).toBeInTheDocument();- expect(screen.queryByTestId("audit-tab")).not.toBeInTheDocument();- });-});diff --git a/frontend/editor/src/portal/views/Infrastructure.tsx b/frontend/editor/src/portal/views/Infrastructure.tsxdeleted file mode 100644index fb42188e98..0000000000--- a/frontend/editor/src/portal/views/Infrastructure.tsx+++ /dev/null@@ -1,109 +0,0 @@-import { useCallback, useEffect, useState } from "react";-import { useSearchParams } from "react-router-dom";-import { useTranslation } from "react-i18next";-import { Tabs, type TabItem } from "@app/ui";-import { useEnterpriseEnabled } from "@portal/hooks/useEnterpriseEnabled";-import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";-import { AuditTab } from "@portal/components/infrastructure/AuditTab";-import { EncryptionPanel } from "@portal/components/infrastructure/EncryptionPanel";-import "@portal/views/Infrastructure.css";--type InfraTab = "api-keys" | "audit" | "storage";--/** Shown but inert: no backend behind these screens yet. */-type DisabledInfraTab = "deployments" | "security" | "models";--export function Infrastructure() {- const { t } = useTranslation();- const [tab, setTab] = useState<InfraTab>("api-keys");- const [searchParams, setSearchParams] = useSearchParams();- // Audit is Enterprise-only; disabled (greyed, inert) on non-enterprise instances.- const enterprise = useEnterpriseEnabled();- const auditEnabled = enterprise.enabled;-- const canOpenTab = useCallback(- (key: string) =>- key === "api-keys" ||- key === "storage" ||- (key === "audit" && auditEnabled),- [auditEnabled],- );-- // Deep-link (?tab=<key>) from elsewhere (e.g. the home visualiser's outcome- // cards → audit log): open that tab, then drop the param.- useEffect(() => {- const requested = searchParams.get("tab");- if (!requested) return;- if (canOpenTab(requested)) {- setTab(requested as InfraTab);- }- const next = new URLSearchParams(searchParams);- next.delete("tab");- setSearchParams(next, { replace: true });- }, [searchParams, setSearchParams, canOpenTab]);-- const tabs: TabItem<InfraTab | DisabledInfraTab>[] = [- { key: "api-keys", label: t("portal.infrastructure.tabs.apiKeys") },- {- key: "audit",- label: t("portal.infrastructure.tabs.audit"),- disabled: !auditEnabled,- },- {- key: "deployments",- label: t("portal.infrastructure.tabs.deployments"),- disabled: true,- },- {- key: "security",- label: t("portal.infrastructure.tabs.security"),- disabled: true,- },- {- key: "models",- label: t("portal.infrastructure.tabs.models"),- disabled: true,- },- // Enabled again: unlike the mock-backed tabs removed in #7497, this one- // reads the real /api/v1/admin/storage-encryption surface.- { key: "storage", label: t("portal.infrastructure.tabs.storage") },- ];-- return (- <div className="portal-infra">- <header className="portal-infra__head">- <div className="portal-infra__head-text">- <h1 className="portal-infra__title">- {t("portal.infrastructure.title")}- </h1>- <p className="portal-infra__sub">- {t("portal.infrastructure.subtitle")}- </p>- </div>- </header>-- <Tabs<InfraTab | DisabledInfraTab>- items={tabs}- activeKey={tab}- onChange={(key) => {- if (canOpenTab(key)) setTab(key as InfraTab);- }}- variant="underline"- ariaLabel={t("portal.infrastructure.sectionsAriaLabel")}- />-- <div className="portal-infra__panel">- {tab === "api-keys" && <ApiKeysTab />}- {tab === "audit" && <AuditTab />}- {tab === "storage" && (- // Treat "still resolving" as available: flashing "your licence records- // no audit trail" at an Enterprise operator is worse than the notice- // arriving a beat late.- <EncryptionPanel- auditAvailable={enterprise.loading || enterprise.enabled}- />- )}- </div>- </div>- );-}diff --git a/frontend/editor/src/portal/views/Users.tsx b/frontend/editor/src/portal/views/Users.tsxindex 3795444c97..4f8a855d97 100644--- a/frontend/editor/src/portal/views/Users.tsx+++ b/frontend/editor/src/portal/views/Users.tsx@@ -20,7 +20,8 @@ import {} from "@portal/api/access";import { deleteTeam as apiDeleteTeam } from "@portal/api/teams";import { errorMessage } from "@portal/api/http";-import { usersCapabilities as caps } from "@app/portal/usersCapabilities";+import { usersCapabilities as buildCaps } from "@app/portal/usersCapabilities";+import type { UsersCapabilities } from "@portal/api/usersCapabilities";import { UsersDirectory } from "@portal/components/users/UsersDirectory";import { PendingInvitations } from "@portal/components/users/PendingInvitations";import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";@@ -49,6 +50,41 @@ export function Users() {const { usersState, grantsState, teamsState, authState, refresh } =useUsersData();+ // Who the viewer is, read off their own row in the roster the backend just+ // returned. Only an org owner or a team lead may change anything here; for+ // everyone else the roster is a directory, so the management controls come+ // off rather than standing there returning 403.+ const viewer = usersState.data?.members.find((m) => m.isSelf) ?? null;+ const canManage =+ viewer !== null+ ? viewer.role === "admin" || viewer.teamLead === true+ : // Not in the roster we were served: only an empty one is safe to offer+ // controls for, so the first member can still be invited.+ (usersState.data?.members.length ?? 0) === 0;+ const caps = useMemo<UsersCapabilities>(+ () =>+ canManage+ ? buildCaps+ : {+ ...buildCaps,+ changeRole: false,+ createTeam: false,+ deleteTeam: false,+ renameTeam: false,+ emailInvite: false,+ manageInvitations: false,+ directCreate: false,+ resetPassword: false,+ unlock: false,+ resetMfa: false,+ suspend: false,+ moveTeam: false,+ manageGrants: false,+ removeMember: false,+ },+ [canManage],+ );+const [actionError, setActionError] = useState<string | null>(null);const [inviteOpen, setInviteOpen] = useState(false);const [inviteTeamId, setInviteTeamId] = useState<number | null>(null);@@ -147,6 +183,9 @@ export function Users() {(caps.directCreate? (usersState.data?.emailInvitesEnabled ?? false): true);+ // Either route to a new member: an emailed invite, or creating the account+ // outright. With neither, the invite controls have nothing to open.+ const canAddMembers = canEmailInvite || caps.directCreate;const loading = usersState.loading && usersState.data === null;const loadError = !usersState.loading && usersState.error !== null;const isEmpty = !usersState.loading && !loadError && members.length === 0;@@ -290,9 +329,11 @@ export function Users() {{t("users.newTeam.action", "+ New team")}</Button>)}- <Button fat onClick={() => openInvite(null)}>- {t("users.invite.action", "Invite people")}- </Button>+ {canAddMembers && (+ <Button fat onClick={() => openInvite(null)}>+ {t("users.invite.action", "Invite people")}+ </Button>+ )}</div></header>@@ -333,9 +374,11 @@ export function Users() {"Invite your team to start collaborating.",)}actions={- <Button onClick={() => openInvite(null)}>- {t("users.invite.action", "Invite people")}- </Button>+ canAddMembers ? (+ <Button onClick={() => openInvite(null)}>+ {t("users.invite.action", "Invite people")}+ </Button>+ ) : undefined}/>)}@@ -356,7 +399,7 @@ export function Users() {processorTeamIds={processorTeamIds}onGrantTeamProcessor={grantTeamProcessor}onRevokeTeamProcessor={revokeTeamProcessor}- onAddToTeam={(team) => openInvite(team.id)}+ onAddToTeam={canAddMembers ? (team) => openInvite(team.id) : null}onResetPassword={setResetPwMember}onMoveToTeam={setMoveMember}onToggleEnabled={toggleEnabled}diff --git a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsxnew file mode 100644index 0000000000..04c0420de1--- /dev/null+++ b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx@@ -0,0 +1,204 @@+import { Suspense, lazy, type ComponentType } from "react";+import type { TFunction } from "i18next";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import type {+ ConfigNavItem,+ ConfigNavSection,+ NavKey,+} from "@app/components/shared/config/types";+import { HAS_PORTAL } from "@app/routes/hasPortal";++// Only the components come from the portal, and only through `lazy` behind the+// build flag: a static value import here would drag the portal chunk into every+// proprietary bundle, including ones built without the processor. The nav+// metadata stays static so the sidebar can be laid out without loading them.+type PortalSectionModule =+ typeof import("@portal/components/settings/portalSettingsSections");++function portalSection(+ pick: (m: PortalSectionModule) => ComponentType | null,+): ComponentType | null {+ if (!HAS_PORTAL) return null;+ const Lazy = lazy(async () => {+ const m =+ await import("@portal/components/settings/portalSettingsSections");+ const Picked = pick(m);+ return { default: Picked ?? (() => null) };+ });+ return function PortalSection() {+ return (+ <Suspense fallback={<LoadingFallback />}>+ <Lazy />+ </Suspense>+ );+ };+}++const UsersSection = portalSection((m) => m.PortalUsersSection);+const ApiKeysSection = portalSection((m) => m.PortalApiKeysSection);+const AuditSection = portalSection((m) => m.PortalAuditSection);+const EncryptionSection = portalSection((m) => m.PortalEncryptionSection);+const BillingSection = portalSection((m) => m.PortalBillingSection);+const AccountLinkSection = portalSection((m) => m.PortalAccountLinkSection);++/**+ * The processor's Users / Infrastructure / Usage & Billing views as settings+ * sections: administration of the whole deployment rather than a pipeline+ * step. Empty in builds without the portal.+ *+ * @param includeAccountLink self-hosted links the instance to a Stirling+ * account; SaaS has nothing to link, so it passes false.+ * @param includeAudit SaaS has no other audit surface; self-hosted has the+ * admin one under Monitoring and passes false.+ * @param includeEncryption encryption at rest is deployment-wide server+ * configuration, so only a self-hosted admin can act on it. SaaS operates+ * the storage itself and passes false for every user.+ * @param includeBilling what the deployment spends is the operator's business,+ * not every member's, so self-hosted passes its admin flag. On SaaS the+ * signed-in account owns the wallet, so it stays on.+ *+ * These flags only decide what is offered: the endpoints behind each section+ * enforce the same rule server-side.+ */+export function buildPortalSettingsSections(+ t: TFunction<"translation", undefined>,+ {+ includeAccountLink = true,+ includeAudit = false,+ includeEncryption = false,+ includeBilling = true,+ }: {+ includeAccountLink?: boolean;+ includeAudit?: boolean;+ includeEncryption?: boolean;+ includeBilling?: boolean;+ } = {},+): ConfigNavSection[] {+ if (!UsersSection || !ApiKeysSection || !AuditSection || !BillingSection) {+ return [];+ }+ const workspace: ConfigNavItem[] = [+ {+ key: "users",+ label: t("portal.nav.users", "Users"),+ description: t(+ "users.subtitle2",+ "Your people, teams, and access levels.",+ ),+ icon: "group-rounded",+ component: <UsersSection />,+ fullBleed: true,+ },+ ];+ if (includeBilling) {+ workspace.push({+ key: "billing",+ label: t("portal.nav.usage", "Usage & Billing"),+ icon: "payments-rounded",+ component: <BillingSection />,+ fullBleed: true,+ });+ }+ if (includeAccountLink && AccountLinkSection) {+ workspace.push({+ key: "account-link",+ label: t("portal.settings.sections.account-link", "Account link"),+ description: t(+ "portal.accountLink.panel.sub",+ "Link this self-hosted org to its Stirling account so unattended processing bills against your org wallet.",+ ),+ icon: "link-rounded",+ component: <AccountLinkSection />,+ });+ }+ const groups: ConfigNavSection[] = [+ {+ id: "workspace",+ title: t("settings.workspace.title", "Workspace"),+ items: workspace,+ },+ // Keys belong to you, not to the server, so they join your own settings+ // rather than standing alone under a heading of their own.+ {+ id: "preferences",+ title: t("settings.preferences.title", "Preferences"),+ mergeAt: "append",+ items: [+ {+ key: "api-keys",+ label: t("settings.developer.apiKeys", "API Keys"),+ description: t(+ "settings.developer.apiKeysDescription",+ "Personal keys for calling the Stirling API from scripts and integrations.",+ ),+ icon: "key-rounded",+ component: <ApiKeysSection />,+ fullBleed: true,+ },+ ],+ },+ ];+ if (includeEncryption && EncryptionSection) {+ groups.push({+ id: "server",+ title: t("settings.server.title", "Server"),+ mergeAt: "append",+ items: [+ {+ key: "storage",+ label: t(+ "portal.infrastructure.encryption.heading",+ "Encryption at rest",+ ),+ description: t(+ "portal.infrastructure.encryption.subheading",+ "Stored files are encrypted before they reach disk, the database or object storage.",+ ),+ icon: "encrypted-rounded",+ component: <EncryptionSection />,+ fullBleed: true,+ },+ ],+ });+ }+ if (includeAudit) {+ groups.push({+ id: "monitoring",+ title: t("settings.monitoring.title", "Monitoring"),+ mergeAt: "append",+ items: [+ {+ key: "audit",+ label: t("settings.licensingAnalytics.audit", "Audit log"),+ description: t(+ "settings.licensingAnalytics.auditDescription",+ "Who did what on this server, and how long that record is kept.",+ ),+ icon: "fact-check-rounded",+ component: <AuditSection />,+ fullBleed: true,+ },+ ],+ });+ }+ return groups;+}++/** Settings sections the portal ones supersede; dropped when they are shown. */+export const PORTAL_SUPERSEDED_SECTION_KEYS: readonly NavKey[] = [+ "people",+ "teams",+ // The cloud builds carry their own roster under this key; the processor's is+ // the superset, so it replaces rather than duplicates it.+ "users",+ "api-keys",+];++/** Where a superseded section's bookmarks and search results now land. */+export const PORTAL_SECTION_ALIASES: Partial<Record<string, NavKey>> = {+ people: "users",+ teams: "users",+ infrastructure: "api-keys",+ // The processor links to a build-neutral "audit"; self-hosted's is the admin one.+ audit: "adminAudit",+};diff --git a/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsxnew file mode 100644index 0000000000..fb79da4d2e--- /dev/null+++ b/frontend/editor/src/proprietary/components/settings/useSettingsNav.tsx@@ -0,0 +1,67 @@+import { useMemo } from "react";+import { useTranslation } from "react-i18next";+import { useSettingsNav as useCoreSettingsNav } from "@core/components/settings/useSettingsNav";+import type { SettingsNav } from "@app/components/settings/settingsNavTypes";+import { usePortalAccessState } from "@app/hooks/usePortalAccess";+import { useAuth } from "@app/auth/context";+import { mergeSettingsGroups } from "@app/components/settings/mergeSettingsGroups";+import {+ buildPortalSettingsSections,+ PORTAL_SECTION_ALIASES,+ PORTAL_SUPERSEDED_SECTION_KEYS,+} from "@app/components/settings/portalSettingsNav";++export type { SettingsNav };++/**+ * Self-hosted settings: the build's own sections, plus the processor's server+ * administration (Team / Infrastructure / Usage & Billing). Where the two+ * overlap the processor's view wins — it is a superset (roles, teams,+ * processor access, audit) — so the narrower section is dropped rather than+ * shown twice, and its key aliases across.+ *+ * Encryption at rest, what the deployment spends, and the link to the Stirling+ * account are all operator concerns, so they are offered to admins only;+ * portal access alone is not enough to reach them.+ */+export function useSettingsNav(onLeave: () => void): SettingsNav {+ const { t } = useTranslation();+ const base = useCoreSettingsNav(onLeave);+ const { granted: portalAccess, settled: accessSettled } =+ usePortalAccessState();+ const { isAdmin } = useAuth();++ const portalSections = useMemo(+ () =>+ portalAccess+ ? buildPortalSettingsSections(t, {+ includeEncryption: isAdmin,+ includeBilling: isAdmin,+ includeAccountLink: isAdmin,+ })+ : [],+ [portalAccess, isAdmin, t],+ );++ const sections = useMemo(+ () =>+ portalSections.length === 0+ ? base.sections+ : mergeSettingsGroups(+ base.sections,+ portalSections,+ PORTAL_SUPERSEDED_SECTION_KEYS,+ ),+ [base.sections, portalSections],+ );++ return {+ ...base,+ sections,+ pending: !accessSettled,+ aliases:+ portalSections.length > 0+ ? { ...base.aliases, ...PORTAL_SECTION_ALIASES }+ : base.aliases,+ };+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx b/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsxindex 9ed036aacd..46f607fbe9 100644--- a/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configNavSections.tsx@@ -1,3 +1,4 @@+import { lazy, Suspense } from "react";import React from "react";import { useTranslation } from "react-i18next";import {@@ -6,30 +7,51 @@ import {} from "@core/components/shared/config/configNavSections";import PeopleSection from "@app/components/shared/config/configSections/PeopleSection";import TeamsSection from "@app/components/shared/config/configSections/TeamsSection";-import AdminGeneralSection from "@app/components/shared/config/configSections/AdminGeneralSection";-import AdminSecuritySection from "@app/components/shared/config/configSections/AdminSecuritySection";-import AdminConnectionsSection from "@app/components/shared/config/configSections/AdminConnectionsSection";-import AdminPrivacySection from "@app/components/shared/config/configSections/AdminPrivacySection";-import AdminDatabaseSection from "@app/components/shared/config/configSections/AdminDatabaseSection";-import AdminAdvancedSection from "@app/components/shared/config/configSections/AdminAdvancedSection";-import AdminLegalSection from "@app/components/shared/config/configSections/AdminLegalSection";import AdminPlanSection from "@app/components/shared/config/configSections/AdminPlanSection";-import AdminFeaturesSection from "@app/components/shared/config/configSections/AdminFeaturesSection";-import AdminEndpointsSection from "@app/components/shared/config/configSections/AdminEndpointsSection";-import AdminMcpSection from "@app/components/shared/config/configSections/AdminMcpSection";-import AdminAiGeneralSection from "@app/components/shared/config/configSections/AdminAiGeneralSection";-import AdminAiModelsSection from "@app/components/shared/config/configSections/AdminAiModelsSection";-import AdminAiDocumentsSection from "@app/components/shared/config/configSections/AdminAiDocumentsSection";-import AdminAiLimitsSection from "@app/components/shared/config/configSections/AdminAiLimitsSection";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import PreferencesSection from "@core/components/shared/config/configSections/preferences/PreferencesSection";++// Lazy, and rendered inside one Suspense below: these five pages are the bulk of+// the settings tree, and pulling them all eagerly starved the i18n fetch on a+// cold load, which left the whole page suspended.+const AdminSystemSection = lazy(+ () =>+ import("@app/components/shared/config/configSections/server/AdminSystemSection"),+);+const AdminSecurityPage = lazy(+ () =>+ import("@app/components/shared/config/configSections/security/AdminSecurityPage"),+);+const AdminAdvancedPage = lazy(+ () =>+ import("@app/components/shared/config/configSections/advanced/AdminAdvancedPage"),+);+const AdminDatabasePage = lazy(+ () =>+ import("@app/components/shared/config/configSections/advanced/AdminDatabasePage"),+);+const AdminIntegrationsPage = lazy(+ () =>+ import("@app/components/shared/config/configSections/security/AdminIntegrationsPage"),+);+const AdminLegalPrivacyPage = lazy(+ () =>+ import("@app/components/shared/config/configSections/security/AdminLegalPrivacyPage"),+);+const AdminAiSection = lazy(+ () => import("@app/components/shared/config/configSections/AdminAiSection"),+);+import AccountCards from "@core/components/shared/config/configSections/preferences/AccountCards";import AdminAuditSection from "@app/components/shared/config/configSections/AdminAuditSection";import AdminUsageSection from "@app/components/shared/config/configSections/AdminUsageSection";-import AdminStorageSharingSection from "@app/components/shared/config/configSections/AdminStorageSharingSection";-import AdminFolderAccessSection from "@app/components/shared/config/configSections/AdminFolderAccessSection";import ApiKeys from "@app/components/shared/config/configSections/ApiKeys";-import AccountSection from "@app/components/shared/config/configSections/AccountSection";/**- * Hook version of proprietary config nav sections with proper i18n support+ * Self-hosted settings, grouped by who reaches for them and what they do there:+ * your own settings and keys, then the people and money of the workspace, then+ * what configures the server, then what only reports on it. Admin groups appear+ * for admins, and as a read-only preview when login is off and+ * system.showSettingsWhenNoLogin allows it.*/export const useConfigNavSections = (isAdmin: boolean = false,@@ -40,279 +62,247 @@ export const useConfigNavSections = (): ConfigNavSection[] => {const { t } = useTranslation();- // Get the core sections (Preferences + Help)- const sections = useCoreConfigNavSections(+ // Core ships Preferences and About; About is the small print and stays last.+ const coreSections = useCoreConfigNavSections(isAdmin,runningEE,loginEnabled,onRequestClose,showSettingsWhenNoLogin,);+ const about = coreSections.filter((s) => s.id === "about");+ const sections = coreSections.filter((s) => s.id !== "about");- // Add account management under Preferences- const preferencesSection = sections.find((section) =>- section.items.some((item) => item.key === "general"),- );- if (preferencesSection && loginEnabled) {- preferencesSection.items.push({- key: "account",- label: t("account.accountSettings", "Account"),- icon: "person-rounded",- component: <AccountSection />,- });+ const preferences = sections.find((s) => s.id === "preferences");+ if (preferences) {+ // Core owns the page; the flavor supplies what core has no concept of.+ preferences.items = preferences.items.map((item) =>+ item.key === "general"+ ? {+ ...item,+ component: (+ <PreferencesSection+ accountSlot={loginEnabled ? <AccountCards /> : undefined}+ />+ ),+ }+ : item,+ );+ // Keys belong to you, not to the server, so they sit with your own+ // settings rather than alone under a heading of their own.+ if (loginEnabled) {+ preferences.items.push({+ key: "api-keys",+ label: t("settings.developer.apiKeys", "API Keys"),+ description: t(+ "settings.developer.apiKeysDescription",+ "Personal keys for calling the Stirling API from scripts and integrations.",+ ),+ icon: "key-rounded",+ component: <ApiKeys />,+ });+ }}- // Add Admin sections for admins. When login is disabled, keep the historical- // read-only admin preview only if system.showSettingsWhenNoLogin allows it.- if (isAdmin || (!loginEnabled && showSettingsWhenNoLogin)) {- const requiresLogin = !loginEnabled;- const enableLoginTooltip = t(- "settings.tooltips.enableLoginFirst",- "Enable login mode first",- );+ const showAdmin = isAdmin || (!loginEnabled && showSettingsWhenNoLogin);+ const requiresLogin = !loginEnabled;+ const enableLoginTooltip = t(+ "settings.tooltips.enableLoginFirst",+ "Enable login mode first",+ );+ const gated = {+ disabled: requiresLogin,+ disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,+ };- // Workspace+ if (showAdmin) {sections.push({+ id: "workspace",title: t("settings.workspace.title", "Workspace"),items: [{key: "people",label: t("settings.workspace.people", "People"),+ description: t(+ "workspace.people.description",+ "Everyone with an account on this server, their role and their team.",+ ),icon: "group-rounded",component: <PeopleSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,+ ...gated,},{key: "teams",label: t("settings.workspace.teams", "Teams"),+ description: t(+ "workspace.teams.description",+ "Group people into teams and manage who belongs where.",+ ),icon: "groups-rounded",component: <TeamsSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- ],- });-- // Configuration- sections.push({- title: t("settings.configuration.title", "Configuration"),- items: [- {- key: "adminGeneral",- label: t("settings.configuration.systemSettings", "System Settings"),- icon: "settings-rounded",- component: <AdminGeneralSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminFeatures",- label: t("settings.configuration.features", "Features"),- icon: "extension-rounded",- component: <AdminFeaturesSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminStorageSharing",- label: t(- "settings.configuration.storageSharing",- "File Storage & Sharing",- ),- icon: "storage-rounded",- component: <AdminStorageSharingSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- badge: t("toolPanel.alpha", "Alpha"),- badgeColor: "orange",- },- {- key: "adminFolderAccess",- label: t("settings.configuration.folderAccess", "Folder Access"),- icon: "folder-rounded",- component: <AdminFolderAccessSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminEndpoints",- label: t("settings.configuration.endpoints", "Endpoints"),- icon: "api-rounded",- component: <AdminEndpointsSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminMcp",- label: t("settings.configuration.mcp", "MCP Server"),- icon: "smart-toy-rounded",- component: <AdminMcpSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminDatabase",- label: t("settings.configuration.database", "Database"),- icon: "storage-rounded",- component: <AdminDatabaseSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminAdvanced",- label: t("settings.configuration.advanced", "Advanced"),- icon: "tune-rounded",- component: <AdminAdvancedSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- ],- });-- // AI- sections.push({- title: t("settings.ai.title", "AI"),- items: [- {- key: "adminAiGeneral",- label: t("settings.ai.general", "General"),- icon: "smart-toy-rounded",- component: <AdminAiGeneralSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminAiModels",- label: t("settings.ai.models", "Models & Providers"),- icon: "psychology",- component: <AdminAiModelsSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,+ ...gated,},- {- key: "adminAiDocuments",- label: t("settings.ai.documents", "Documents & RAG"),- icon: "description",- component: <AdminAiDocumentsSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminAiLimits",- label: t("settings.ai.limits", "Limits & Performance"),- icon: "speed",- component: <AdminAiLimitsSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- ],- });-- // Security & Authentication- sections.push({- title: t("settings.securityAuth.title", "Security & Authentication"),- items: [- {- key: "adminSecurity",- label: t("settings.securityAuth.security", "Security"),- icon: "shield-rounded",- component: <AdminSecuritySection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminConnections",- label: t("settings.securityAuth.connections", "Connections"),- icon: "link-rounded",- component: <AdminConnectionsSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- ],- });-- // Licensing & Analytics- sections.push({- title: t("settings.licensingAnalytics.title", "Licensing & Analytics"),- items: [{key: "adminPlan",label: t("settings.licensingAnalytics.plan", "Plan"),+ description: t(+ "settings.licensingAnalytics.planDescription",+ "Your licence, seats and what the current plan unlocks.",+ ),icon: "star-rounded",component: <AdminPlanSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminAudit",- label: t("settings.licensingAnalytics.audit", "Audit"),- icon: "fact-check-rounded",- component: <AdminAuditSection />,- // Non-Enterprise users can still click in: AdminAuditSection- // renders a demo preview when `!hasEnterpriseLicense`.- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminUsage",- label: t(- "settings.licensingAnalytics.usageAnalytics",- "Usage Analytics",- ),- icon: "analytics-rounded",- component: <AdminUsageSection />,- // Same demo-preview story as adminAudit above.- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- ],- });-- // Policies & Privacy- sections.push({- title: t("settings.policiesPrivacy.title", "Policies & Privacy"),- items: [- {- key: "adminLegal",- label: t("settings.policiesPrivacy.legal", "Legal"),- icon: "gavel-rounded",- component: <AdminLegalSection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,- },- {- key: "adminPrivacy",- label: t("settings.policiesPrivacy.privacy", "Privacy"),- icon: "visibility-rounded",- component: <AdminPrivacySection />,- disabled: requiresLogin,- disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,+ ...gated,},],});}- // Add Developer section if login is enabled- if (loginEnabled) {- const developerSection: ConfigNavSection = {- title: t("settings.developer.title", "Developer"),- items: [- {- key: "api-keys",- label: t("settings.developer.apiKeys", "API Keys"),- icon: "key-rounded",- component: <ApiKeys />,- },- ],- };-- // Add Developer section after Preferences (or Workspace if it exists)- const insertIndex = isAdmin ? 2 : 1;- sections.splice(insertIndex, 0, developerSection);+ if (showAdmin) {+ sections.push(+ {+ id: "server",+ title: t("settings.server.title", "Server"),+ items: [+ {+ key: "adminGeneral",+ label: t("settings.server.system", "System"),+ description: t(+ "admin.settings.general.description",+ "How this server runs: branding, storage, the tools it exposes, and the paths it may touch.",+ ),+ icon: "settings-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminSystemSection />+ </Suspense>+ ),+ ...gated,+ },+ {+ key: "adminSecurity",+ label: t("settings.securityAuth.security", "Sign-in & security"),+ description: t(+ "admin.settings.security.description",+ "How people sign in, how sessions are held, and what this server discloses about itself.",+ ),+ icon: "shield-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminSecurityPage />+ </Suspense>+ ),+ ...gated,+ },+ {+ key: "adminConnections",+ label: t("settings.configuration.integrations", "Integrations"),+ description: t(+ "admin.settings.connections.description",+ "Mail, Telegram, Drive, and uploading from a phone.",+ ),+ icon: "hub-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminIntegrationsPage />+ </Suspense>+ ),+ ...gated,+ },+ {+ key: "adminAi",+ label: t("settings.ai.general", "AI Engine"),+ description: t(+ "admin.settings.ai.description",+ "Connect Stirling to the Python AI engine, choose its models, and set the guardrails it runs under.",+ ),+ icon: "smart-toy-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminAiSection />+ </Suspense>+ ),+ ...gated,+ },+ {+ key: "adminDatabase",+ label: t("settings.configuration.database", "Database"),+ description: t(+ "admin.settings.database.description",+ "Connect a custom database, and back up or restore the one in use.",+ ),+ icon: "database-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminDatabasePage />+ </Suspense>+ ),+ ...gated,+ },+ {+ key: "adminAdvanced",+ label: t("settings.configuration.advanced", "Advanced"),+ description: t(+ "admin.settings.advanced.description",+ "Feature flags, processing limits, temp files and the database. Set once at install, if ever.",+ ),+ icon: "tune-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminAdvancedPage />+ </Suspense>+ ),+ ...gated,+ },+ {+ key: "adminLegal",+ label: t("settings.policiesPrivacy.title", "Legal & privacy"),+ description: t(+ "admin.settings.legal.description",+ "Configure links to legal documents and policies.",+ ),+ icon: "gavel-rounded",+ component: (+ <Suspense fallback={<LoadingFallback />}>+ <AdminLegalPrivacyPage />+ </Suspense>+ ),+ ...gated,+ },+ ],+ },+ // Split from Server because you read these rather than set them.+ {+ id: "monitoring",+ title: t("settings.monitoring.title", "Monitoring"),+ items: [+ {+ key: "adminUsage",+ label: t("settings.licensingAnalytics.usage", "Usage Analytics"),+ description: t(+ "settings.licensingAnalytics.usageDescription",+ "Endpoint usage and activity for this server.",+ ),+ icon: "monitoring",+ component: <AdminUsageSection />,+ ...gated,+ },+ {+ key: "adminAudit",+ label: t("settings.licensingAnalytics.audit", "Audit log"),+ description: t(+ "settings.licensingAnalytics.auditDescription",+ "Who did what on this server, and how long that record is kept.",+ ),+ icon: "fact-check-rounded",+ component: <AdminAuditSection />,+ ...gated,+ },+ ],+ },+ );}- return sections;+ return [...sections, ...about];};// Re-export types for conveniencediff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AccountSection.stories.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AccountSection.stories.tsxdeleted file mode 100644index 213df8951c..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AccountSection.stories.tsx+++ /dev/null@@ -1,101 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import AccountSection from "@app/components/shared/config/configSections/AccountSection";-import { AuthContext } from "@app/auth/context";-import type { AuthContextValue } from "@app/auth/types";-import { accountService } from "@app/services/accountService";--/**- * Account settings panel shown inside the app config modal: password /- * username management and two-factor authentication setup.- */-const meta: Meta<typeof AccountSection> = {- title: "Config/AccountSection",- component: AccountSection,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof meta>;--// AccountSection gets its user from useAuth() and its MFA/account data from-// accountService on mount rather than via props, so stories set those directly.-const standardAuth: AuthContextValue = {- session: null,- user: {- id: "user-1",- email: "[email protected]",- username: "jane.doe",- role: "ROLE_USER",- },- displayName: "jane.doe",- isAnonymous: false,- isAdmin: false,- portalAccess: false,- role: "ROLE_USER",- loading: false,- error: null,- signOut: async () => {},- refreshSession: async () => {},-};--const ssoAuth: AuthContextValue = {- ...standardAuth,- user: {- ...standardAuth.user!,- email: "[email protected]",- authenticationType: "sso",- },-};--accountService.getAccountData = async () => ({- username: "jane.doe",- role: "ROLE_USER",- settings: "{}",- changeCredsFlag: false,- oAuth2Login: false,- saml2Login: false,- mfaEnabled: false,-});--/** Standard account with password/username management and 2FA available to enable. */-export const Default: Story = {- decorators: [- (Story) => (- <AuthContext.Provider value={standardAuth}>- <Story />- </AuthContext.Provider>- ),- ],-};--/** Two-factor authentication already enabled: shows the disable action instead. */-export const MfaEnabled: Story = {- decorators: [- (Story) => {- accountService.getAccountData = async () => ({- username: "jane.doe",- role: "ROLE_USER",- settings: "{}",- changeCredsFlag: false,- oAuth2Login: false,- saml2Login: false,- mfaEnabled: true,- });- return (- <AuthContext.Provider value={standardAuth}>- <Story />- </AuthContext.Provider>- );- },- ],-};--/** SSO-managed account: password/username changes and 2FA are hidden behind identity-provider notices. */-export const SsoUser: Story = {- decorators: [- (Story) => (- <AuthContext.Provider value={ssoAuth}>- <Story />- </AuthContext.Provider>- ),- ],-};diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAdvancedSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAdvancedSection.tsxdeleted file mode 100644index f1831c5b48..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAdvancedSection.tsx+++ /dev/null@@ -1,1793 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from "react";-import { isAxiosError } from "axios";-import { useTranslation } from "react-i18next";-import {- NumberInput,- Switch,- Stack,- Paper,- Text,- Loader,- Group,- Accordion,- TextInput,- MultiSelect,-} from "@mantine/core";-import { Button } from "@app/ui/Button";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";--interface AdvancedSettingsData {- enableAlphaFunctionality?: boolean;- maxDPI?: number;- enableUrlToPDF?: boolean;- tessdataDir?: string;- disableSanitize?: boolean;- tempFileManagement?: {- baseTmpDir?: string;- libreofficeDir?: string;- systemTempDir?: string;- prefix?: string;- maxAgeHours?: number;- cleanupIntervalMinutes?: number;- startupCleanup?: boolean;- cleanupSystemTemp?: boolean;- };- processExecutor?: {- sessionLimit?: {- libreOfficeSessionLimit?: number;- pdfToHtmlSessionLimit?: number;- qpdfSessionLimit?: number;- tesseractSessionLimit?: number;- pythonOpenCvSessionLimit?: number;- weasyPrintSessionLimit?: number;- installAppSessionLimit?: number;- calibreSessionLimit?: number;- ghostscriptSessionLimit?: number;- ocrMyPdfSessionLimit?: number;- };- timeoutMinutes?: {- libreOfficetimeoutMinutes?: number;- pdfToHtmltimeoutMinutes?: number;- pythonOpenCvtimeoutMinutes?: number;- weasyPrinttimeoutMinutes?: number;- installApptimeoutMinutes?: number;- calibretimeoutMinutes?: number;- tesseractTimeoutMinutes?: number;- qpdfTimeoutMinutes?: number;- ghostscriptTimeoutMinutes?: number;- ocrMyPdfTimeoutMinutes?: number;- };- };-}--export default function AdminAdvancedSection() {- const { t } = useTranslation();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();- const { loginEnabled, validateLoginEnabled, getDisabledStyles } =- useLoginRequired();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<AdvancedSettingsData>({- sectionName: "advanced",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- AdvancedSettingsData & { _pending?: Record<string, unknown> }- > => {- const [systemResponse, processExecutorResponse] = await Promise.all([- apiClient.get("/api/v1/admin/settings/section/system"),- apiClient.get("/api/v1/admin/settings/section/processExecutor"),- ]);-- const systemData = systemResponse.data || {};- const processExecutorData = processExecutorResponse.data || {};-- const result: AdvancedSettingsData & {- _pending?: Record<string, unknown>;- } = {- enableAlphaFunctionality: systemData.enableAlphaFunctionality || false,- maxDPI: systemData.maxDPI || 0,- enableUrlToPDF: systemData.enableUrlToPDF || false,- tessdataDir: systemData.tessdataDir || "",- disableSanitize: systemData.disableSanitize || false,- tempFileManagement: systemData.tempFileManagement || {- baseTmpDir: "",- libreofficeDir: "",- systemTempDir: "",- prefix: "stirling-pdf-",- maxAgeHours: 24,- cleanupIntervalMinutes: 30,- startupCleanup: true,- cleanupSystemTemp: false,- },- processExecutor: processExecutorData || {},- };-- // Merge pending blocks from both endpoints- const pendingBlock: Record<string, unknown> = {};- if (systemData._pending?.enableAlphaFunctionality !== undefined) {- pendingBlock.enableAlphaFunctionality =- systemData._pending.enableAlphaFunctionality;- }- if (systemData._pending?.maxDPI !== undefined) {- pendingBlock.maxDPI = systemData._pending.maxDPI;- }- if (systemData._pending?.enableUrlToPDF !== undefined) {- pendingBlock.enableUrlToPDF = systemData._pending.enableUrlToPDF;- }- if (systemData._pending?.tessdataDir !== undefined) {- pendingBlock.tessdataDir = systemData._pending.tessdataDir;- }- if (systemData._pending?.disableSanitize !== undefined) {- pendingBlock.disableSanitize = systemData._pending.disableSanitize;- }- if (systemData._pending?.tempFileManagement) {- pendingBlock.tempFileManagement =- systemData._pending.tempFileManagement;- }- if (processExecutorData._pending) {- pendingBlock.processExecutor = processExecutorData._pending;- }-- if (Object.keys(pendingBlock).length > 0) {- result._pending = pendingBlock;- }-- return result;- },- saveTransformer: (settings) => {- const deltaSettings: Record<string, unknown> = {- "system.enableAlphaFunctionality": settings.enableAlphaFunctionality,- "system.maxDPI": settings.maxDPI,- "system.enableUrlToPDF": settings.enableUrlToPDF,- "system.tessdataDir": settings.tessdataDir,- "system.disableSanitize": settings.disableSanitize,- };-- // Add temp file management settings- if (settings.tempFileManagement) {- deltaSettings["system.tempFileManagement.baseTmpDir"] =- settings.tempFileManagement.baseTmpDir;- deltaSettings["system.tempFileManagement.libreofficeDir"] =- settings.tempFileManagement.libreofficeDir;- deltaSettings["system.tempFileManagement.systemTempDir"] =- settings.tempFileManagement.systemTempDir;- deltaSettings["system.tempFileManagement.prefix"] =- settings.tempFileManagement.prefix;- deltaSettings["system.tempFileManagement.maxAgeHours"] =- settings.tempFileManagement.maxAgeHours;- deltaSettings["system.tempFileManagement.cleanupIntervalMinutes"] =- settings.tempFileManagement.cleanupIntervalMinutes;- deltaSettings["system.tempFileManagement.startupCleanup"] =- settings.tempFileManagement.startupCleanup;- deltaSettings["system.tempFileManagement.cleanupSystemTemp"] =- settings.tempFileManagement.cleanupSystemTemp;- }-- // Add process executor settings- if (settings.processExecutor?.sessionLimit) {- Object.entries(settings.processExecutor.sessionLimit).forEach(- ([key, value]) => {- deltaSettings[`processExecutor.sessionLimit.${key}`] = value;- },- );- }- if (settings.processExecutor?.timeoutMinutes) {- Object.entries(settings.processExecutor.timeoutMinutes).forEach(- ([key, value]) => {- deltaSettings[`processExecutor.timeoutMinutes.${key}`] = value;- },- );- }-- return {- sectionData: {},- deltaSettings,- };- },- });-- const [tessdataLanguages, setTessdataLanguages] = useState<string[]>([]);- const [remoteTessdataLanguages, setRemoteTessdataLanguages] = useState<- string[]- >([]);- const [tessdataDirWritable, setTessdataDirWritable] = useState<boolean>(true);- const [manualDownloadLinks, setManualDownloadLinks] = useState<string[]>([]);- const [tessdataLanguagesLoading, setTessdataLanguagesLoading] =- useState(false);- const [downloadLanguagesLoading, setDownloadLanguagesLoading] =- useState(false);- const [selectedDownloadLanguages, setSelectedDownloadLanguages] = useState<- string[]- >([]);-- useEffect(() => {- if (!loginEnabled) return;-- const fetchTessdataLanguages = async () => {- setTessdataLanguagesLoading(true);- try {- const { data } = await apiClient.get<{- installed: string[];- available: string[];- writable?: boolean;- }>("/api/v1/ui-data/tessdata-languages", {- suppressErrorToast: true,- });- const installed = data.installed || [];- const available = data.available || [];- setTessdataLanguages(installed);- setRemoteTessdataLanguages(- available.filter((lang) => !installed.includes(lang)),- );- setTessdataDirWritable(data.writable !== false);- setManualDownloadLinks([]);- } catch (error) {- console.error(- "[AdminAdvancedSection] Failed to load tessdata languages",- error,- );- setTessdataLanguages([]);- setRemoteTessdataLanguages([]);- setTessdataDirWritable(true);- setManualDownloadLinks([]);- } finally {- setTessdataLanguagesLoading(false);- }- };-- fetchTessdataLanguages();- }, [loginEnabled]);-- const refreshTessdataWithRetry = async (retries = 3, delayMs = 400) => {- for (let attempt = 0; attempt < retries; attempt++) {- try {- const { data } = await apiClient.get<{- installed: string[];- available: string[];- writable?: boolean;- }>("/api/v1/ui-data/tessdata-languages", { suppressErrorToast: true });- const installed = data.installed || [];- const available = data.available || [];- setTessdataLanguages(installed);- setRemoteTessdataLanguages(- available.filter((lang) => !installed.includes(lang)),- );- setTessdataDirWritable(data.writable !== false);- setManualDownloadLinks([]);- return;- } catch (err) {- if (attempt === retries - 1) {- console.error(- "[AdminAdvancedSection] Retry refresh tessdata failed",- err,- );- return;- }- await new Promise((resolve) => setTimeout(resolve, delayMs));- }- }- };-- const safeLangRegex = useMemo(() => new RegExp("[^A-Za-z0-9_+\\-]", "g"), []);-- const handleDownloadTessdataLanguages = async () => {- if (!loginEnabled) return;- if (selectedDownloadLanguages.length === 0) {- alert({- alertType: "warning",- title: t(- "admin.settings.advanced.tessdataDir.downloadMissingTitle",- "No language selected",- ),- body: t(- "admin.settings.advanced.tessdataDir.downloadMissingBody",- "Please select at least one language to download.",- ),- expandable: false,- });- return;- }- // Ensure selection is a subset of remote languages to prevent invalid requests- const remoteSet = new Set(remoteTessdataLanguages);- const invalidSelection = selectedDownloadLanguages.filter(- (lang) => !remoteSet.has(lang),- );- if (invalidSelection.length > 0) {- alert({- alertType: "warning",- title: t(- "admin.settings.advanced.tessdataDir.downloadInvalidTitle",- "Invalid selection",- ),- body: t(- "admin.settings.advanced.tessdataDir.downloadInvalidBody",- "Some selected languages are not available to download. Please refresh and choose from the list.",- ),- expandable: false,- });- return;- }- setDownloadLanguagesLoading(true);- try {- await apiClient.post(- "/api/v1/ui-data/tessdata/download",- { languages: selectedDownloadLanguages },- {- suppressErrorToast: true,- },- );- alert({- alertType: "success",- title: t(- "admin.settings.advanced.tessdataDir.downloadSuccessTitle",- "Languages downloaded",- ),- body: t(- "admin.settings.advanced.tessdataDir.downloadSuccessBody",- "The selected tessdata languages have been saved.",- ),- });- // Refresh installed list with retry in case filesystem sync is delayed- await refreshTessdataWithRetry();- setSelectedDownloadLanguages([]);- setManualDownloadLinks([]);- } catch (error) {- console.error(- "[AdminAdvancedSection] Download tessdata languages failed",- error,- );- const status = isAxiosError(error) ? error.response?.status : undefined;- const serverMessage = isAxiosError(error)- ? error.response?.data?.message- : undefined;-- if (status === 403) {- console.warn(- "[AdminAdvancedSection] Tessdata directory not writable, falling back to manual download:",- serverMessage,- );- setTessdataDirWritable(false);- setManualDownloadLinks(- selectedDownloadLanguages.map((lang) => {- const safeLang = lang.replace(safeLangRegex, "");- return `https://raw.githubusercontent.com/tesseract-ocr/tessdata/main/${safeLang}.traineddata`;- }),- );- const message = t(- "admin.settings.advanced.tessdataDir.downloadErrorPermission",- {- defaultValue:- "Tessdata directory is not writable: {{message}}. Please choose a writable directory (e.g. under the application data folder) or adjust permissions.",- message:- serverMessage ?? settings.tessdataDir ?? "unknown location",- },- );- alert({- alertType: "error",- title: t(- "admin.settings.advanced.tessdataDir.downloadErrorTitle",- "Download Failed",- ),- body: message,- expandable: false,- });- return;- }-- let message: string;- if (!isAxiosError(error) || !error.response) {- message = t(- "admin.settings.advanced.tessdataDir.downloadErrorNetwork",- "Download failed due to a network error. Please check your connection and try again.",- );- } else if (status !== undefined && status >= 500) {- message = t(- "admin.settings.advanced.tessdataDir.downloadErrorServer",- "The server encountered an error while downloading tessdata languages. Please try again later.",- );- } else {- message = t(- "admin.settings.advanced.tessdataDir.downloadErrorGeneric",- {- defaultValue:- "Download failed: {{message}}. Please try again later.",- message:- serverMessage ?? settings.tessdataDir ?? "unknown location",- },- );- }- alert({- alertType: "error",- title: t(- "admin.settings.advanced.tessdataDir.downloadErrorTitle",- "Download Failed",- ),- body: message,- expandable: false,- });- } finally {- setDownloadLanguagesLoading(false);- }- };-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }- try {- markSaved();- await saveSettings();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- const actualLoading = loginEnabled ? loading : false;-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Text fw={600} size="lg">- {t("admin.settings.advanced.title", "Advanced")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.advanced.description",- "Configure advanced features and experimental functionality.",- )}- </Text>- </div>-- {/* Feature Flags */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.advanced.features", "Feature Flags")}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.advanced.enableAlphaFunctionality.label",- "Enable Alpha Features",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.advanced.enableAlphaFunctionality.description",- "Enable experimental and alpha-stage features (may be unstable)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.enableAlphaFunctionality || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- enableAlphaFunctionality: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge- show={isFieldPending("enableAlphaFunctionality")}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.advanced.enableUrlToPDF.label",- "Enable URL to PDF",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.advanced.enableUrlToPDF.description",- "Allow conversion of web pages to PDF documents (internal use only)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.enableUrlToPDF || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- enableUrlToPDF: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("enableUrlToPDF")} />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.advanced.disableSanitize.label",- "Disable HTML Sanitization",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.advanced.disableSanitize.description",- "Disable HTML sanitization (WARNING: Security risk - can lead to XSS injections)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.disableSanitize || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- disableSanitize: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("disableSanitize")} />- </Group>- </div>- </Stack>- </Paper>-- {/* Processing Settings */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.advanced.processing", "Processing")}- </Text>-- <div>- <NumberInput- label={- <Group gap="xs">- <span>- {t("admin.settings.advanced.maxDPI.label", "Maximum DPI")}- </span>- <PendingBadge show={isFieldPending("maxDPI")} />- </Group>- }- description={t(- "admin.settings.advanced.maxDPI.description",- "Maximum DPI for image processing (0 = unlimited)",- )}- value={settings.maxDPI || 0}- onChange={(value) =>- setSettings({ ...settings, maxDPI: Number(value) })- }- min={0}- max={3000}- disabled={!loginEnabled}- />- </div>-- {/* Tessdata Directory */}- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.advanced.tessdataDir.label",- "Tessdata Directory",- )}- </span>- <PendingBadge show={isFieldPending("tessdataDir")} />- </Group>- }- description={t(- "admin.settings.advanced.tessdataDir.description",- "Path to the directory containing Tessdata files for OCR",- )}- value={settings.tessdataDir || ""}- onChange={(e) =>- setSettings({ ...settings, tessdataDir: e.target.value })- }- placeholder="/usr/share/tessdata"- disabled={!loginEnabled}- />- {tessdataLanguagesLoading ? (- <Group gap="xs" mt={6}>- <Loader size="xs" />- <Text size="xs">- {t(- "admin.settings.advanced.tessdataDir.loadingLanguages",- "Loading installed tessdata languages...",- )}- </Text>- </Group>- ) : (- <Text size="xs" c="dimmed" mt={6}>- {tessdataLanguages.length > 0- ? `${t("admin.settings.advanced.tessdataDir.installedLanguages", "Installed tessdata languages")}: ${tessdataLanguages.join(", ")}`- : t(- "admin.settings.advanced.tessdataDir.noLanguages",- "No tessdata languages found in the configured directory",- )}- </Text>- )}- <Stack gap="xs" mt="sm">- <MultiSelect- label={t(- "admin.settings.advanced.tessdataDir.downloadLabel",- "Download additional tessdata languages",- )}- placeholder={t(- "admin.settings.advanced.tessdataDir.downloadPlaceholder",- "Select languages",- )}- data={remoteTessdataLanguages.map((lang) => ({- value: lang,- label: lang,- }))}- searchable- disabled={- !loginEnabled || remoteTessdataLanguages.length === 0- }- value={selectedDownloadLanguages}- onChange={setSelectedDownloadLanguages}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- nothingFoundMessage={t(- "admin.settings.advanced.tessdataDir.downloadNothingFound",- "No additional languages found",- )}- />- {!tessdataDirWritable && (- <Text size="xs" c="yellow.4">- {t(- "admin.settings.advanced.tessdataDir.permissionNotice",- "The tessdata path is not writable. Downloads will be opened in the browser; please save the .traineddata files manually into the tessdata folder.",- )}- </Text>- )}- {!tessdataDirWritable && manualDownloadLinks.length > 0 && (- <Stack gap="xs">- <Text size="xs" c="dimmed">- {t(- "admin.settings.advanced.tessdataDir.manualLinks",- "Manual downloads: click the links and place the files into the tessdata folder.",- )}- </Text>- <Stack gap={4}>- {manualDownloadLinks.map((link) => (- <a- key={link}- href={link}- target="_blank"- rel="noreferrer"- style={{ fontSize: "12px" }}- >- {link}- </a>- ))}- </Stack>- </Stack>- )}- <Group justify="flex-end">- <Button- size="sm"- variant="secondary"- onClick={handleDownloadTessdataLanguages}- loading={downloadLanguagesLoading}- disabled={- !loginEnabled || remoteTessdataLanguages.length === 0- }- >- {t(- "admin.settings.advanced.tessdataDir.downloadButton",- "Download selected languages",- )}- </Button>- </Group>- </Stack>- </div>- </Stack>- </Paper>-- {/* Temp File Management */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Text fw={600} size="sm" mb="xs">- {t(- "admin.settings.advanced.tempFileManagement.label",- "Temp File Management",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.advanced.tempFileManagement.description",- "Configure temporary file storage and cleanup behavior",- )}- </Text>- </div>-- <div>- <TextInput- label={t(- "admin.settings.advanced.tempFileManagement.baseTmpDir.label",- "Base Temp Directory",- )}- description={t(- "admin.settings.advanced.tempFileManagement.baseTmpDir.description",- "Base directory for temporary files (leave empty for default: java.io.tmpdir/stirling-pdf)",- )}- value={settings.tempFileManagement?.baseTmpDir || ""}- onChange={(e) =>- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- baseTmpDir: e.target.value,- },- })- }- placeholder={t(- "admin.settings.advanced.tempFileManagement.baseTmpDir.placeholder",- "Default: java.io.tmpdir/stirling-pdf",- )}- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={t(- "admin.settings.advanced.tempFileManagement.libreofficeDir.label",- "LibreOffice Temp Directory",- )}- description={t(- "admin.settings.advanced.tempFileManagement.libreofficeDir.description",- "Directory for LibreOffice temp files (leave empty for default: baseTmpDir/libreoffice)",- )}- value={settings.tempFileManagement?.libreofficeDir || ""}- onChange={(e) =>- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- libreofficeDir: e.target.value,- },- })- }- placeholder={t(- "admin.settings.advanced.tempFileManagement.libreofficeDir.placeholder",- "Default: baseTmpDir/libreoffice",- )}- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={t(- "admin.settings.advanced.tempFileManagement.systemTempDir.label",- "System Temp Directory",- )}- description={t(- "admin.settings.advanced.tempFileManagement.systemTempDir.description",- "System temp directory to clean (only used if cleanupSystemTemp is enabled)",- )}- value={settings.tempFileManagement?.systemTempDir || ""}- onChange={(e) =>- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- systemTempDir: e.target.value,- },- })- }- placeholder={t(- "admin.settings.advanced.tempFileManagement.systemTempDir.placeholder",- "System temp directory path",- )}- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={t(- "admin.settings.advanced.tempFileManagement.prefix.label",- "Temp File Prefix",- )}- description={t(- "admin.settings.advanced.tempFileManagement.prefix.description",- "Prefix for temp file names",- )}- value={settings.tempFileManagement?.prefix || "stirling-pdf-"}- onChange={(e) =>- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- prefix: e.target.value,- },- })- }- placeholder="stirling-pdf-"- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- label={t(- "admin.settings.advanced.tempFileManagement.maxAgeHours.label",- "Max Age (hours)",- )}- description={t(- "admin.settings.advanced.tempFileManagement.maxAgeHours.description",- "Maximum age in hours before temp files are cleaned up",- )}- value={settings.tempFileManagement?.maxAgeHours ?? 24}- onChange={(value) =>- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- maxAgeHours: Number(value),- },- })- }- min={1}- max={720}- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- label={t(- "admin.settings.advanced.tempFileManagement.cleanupIntervalMinutes.label",- "Cleanup Interval (minutes)",- )}- description={t(- "admin.settings.advanced.tempFileManagement.cleanupIntervalMinutes.description",- "How often to run cleanup (in minutes)",- )}- value={- settings.tempFileManagement?.cleanupIntervalMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- cleanupIntervalMinutes: Number(value),- },- })- }- min={1}- max={1440}- disabled={!loginEnabled}- />- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.advanced.tempFileManagement.startupCleanup.label",- "Startup Cleanup",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.advanced.tempFileManagement.startupCleanup.description",- "Clean up old temp files on application startup",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.tempFileManagement?.startupCleanup ?? true}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- startupCleanup: e.target.checked,- },- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge- show={isFieldPending("tempFileManagement.startupCleanup")}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.advanced.tempFileManagement.cleanupSystemTemp.label",- "Cleanup System Temp",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.advanced.tempFileManagement.cleanupSystemTemp.description",- "Whether to clean broader system temp directory (use with caution)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={- settings.tempFileManagement?.cleanupSystemTemp ?? false- }- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- tempFileManagement: {- ...settings.tempFileManagement,- cleanupSystemTemp: e.target.checked,- },- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge- show={isFieldPending("tempFileManagement.cleanupSystemTemp")}- />- </Group>- </div>- </Stack>- </Paper>-- {/* Process Executor Limits */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm">- {t(- "admin.settings.advanced.processExecutor.label",- "Process Executor Limits",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.advanced.processExecutor.description",- "Configure session limits and timeouts for each process executor",- )}- </Text>-- <Accordion variant="separated">- {/* LibreOffice */}- <Accordion.Item value="libreOffice">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.libreOffice",- "LibreOffice",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.libreOfficeSessionLimit ?? 1- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- libreOfficeSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.libreOfficetimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- libreOfficetimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* PDF to HTML */}- <Accordion.Item value="pdfToHtml">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.pdfToHtml",- "PDF to HTML",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.pdfToHtmlSessionLimit ?? 1- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- pdfToHtmlSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.pdfToHtmltimeoutMinutes ?? 20- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- pdfToHtmltimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* QPDF */}- <Accordion.Item value="qpdf">- <Accordion.Control>- {t("admin.settings.advanced.processExecutor.qpdf", "QPDF")}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.qpdfSessionLimit ?? 4- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- qpdfSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.qpdfTimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- qpdfTimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* Tesseract OCR */}- <Accordion.Item value="tesseract">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.tesseract",- "Tesseract OCR",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.tesseractSessionLimit ?? 1- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- tesseractSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.tesseractTimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- tesseractTimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* Python OpenCV */}- <Accordion.Item value="pythonOpenCv">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.pythonOpenCv",- "Python OpenCV",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.pythonOpenCvSessionLimit ?? 8- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- pythonOpenCvSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.pythonOpenCvtimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- pythonOpenCvtimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* WeasyPrint */}- <Accordion.Item value="weasyPrint">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.weasyPrint",- "WeasyPrint",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.weasyPrintSessionLimit ?? 16- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- weasyPrintSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.weasyPrinttimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- weasyPrinttimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* Install App */}- <Accordion.Item value="installApp">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.installApp",- "Install App",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.installAppSessionLimit ?? 1- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- installAppSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.installApptimeoutMinutes ?? 60- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- installApptimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* Calibre */}- <Accordion.Item value="calibre">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.calibre",- "Calibre",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.calibreSessionLimit ?? 1- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- calibreSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.calibretimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- calibretimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* Ghostscript */}- <Accordion.Item value="ghostscript">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.ghostscript",- "Ghostscript",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.ghostscriptSessionLimit ?? 8- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- ghostscriptSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.ghostscriptTimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- ghostscriptTimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>-- {/* OCRmyPDF */}- <Accordion.Item value="ocrMyPdf">- <Accordion.Control>- {t(- "admin.settings.advanced.processExecutor.ocrMyPdf",- "OCRmyPDF",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="sm">- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.sessionLimit.label",- "Session Limit",- )}- description={t(- "admin.settings.advanced.processExecutor.sessionLimit.description",- "Maximum concurrent instances",- )}- value={- settings.processExecutor?.sessionLimit- ?.ocrMyPdfSessionLimit ?? 2- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- sessionLimit: {- ...settings.processExecutor?.sessionLimit,- ocrMyPdfSessionLimit: Number(value),- },- },- })- }- min={1}- max={100}- disabled={!loginEnabled}- />- <NumberInput- label={t(- "admin.settings.advanced.processExecutor.timeout.label",- "Timeout (minutes)",- )}- description={t(- "admin.settings.advanced.processExecutor.timeout.description",- "Maximum execution time",- )}- value={- settings.processExecutor?.timeoutMinutes- ?.ocrMyPdfTimeoutMinutes ?? 30- }- onChange={(value) =>- setSettings({- ...settings,- processExecutor: {- ...settings.processExecutor,- timeoutMinutes: {- ...settings.processExecutor?.timeoutMinutes,- ocrMyPdfTimeoutMinutes: Number(value),- },- },- })- }- min={1}- max={240}- disabled={!loginEnabled}- />- </Stack>- </Accordion.Panel>- </Accordion.Item>- </Accordion>- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiDocumentsSection.stories.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiDocumentsSection.stories.tsxdeleted file mode 100644index c0ba0c34cb..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiDocumentsSection.stories.tsx+++ /dev/null@@ -1,98 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse, delay } from "msw";-import AdminAiDocumentsSection from "@app/components/shared/config/configSections/AdminAiDocumentsSection";-import { AppConfigProvider } from "@app/contexts/AppConfigContext";-import { UnsavedChangesProvider } from "@app/contexts/UnsavedChangesContext";-import {- AiEngineApiResponse,- MASKED_SECRET,-} from "@app/components/shared/config/configSections/aiEngineSettings";--// AdminAiDocumentsSection takes no props: it fetches the shared aiEngine settings-// blob via apiClient on mount and reads login state through useAppConfig(), so-// each variant mocks the GET response and wraps in a fixed AppConfigProvider-// (autoFetch off, so stories never hit the real API). It also tracks dirty state-// through useSettingsDirty()/useUnsavedChanges(), which isn't part of Storybook's-// global provider stack, so that needs wrapping here too or the hook throws.-const baseSettings: AiEngineApiResponse = {- rag: {- embeddingProvider: "voyageai",- embeddingModel: "voyage-4",- embeddingApiKey: MASKED_SECRET,- topK: 5,- maxSearches: 3,- },-};--const handlerFor = (data: AiEngineApiResponse) =>- http.get("*/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json(data),- );--const meta = {- title: "Config/AdminAiDocumentsSection",- component: AdminAiDocumentsSection,- parameters: {- layout: "padded",- msw: {- handlers: [- handlerFor(baseSettings),- http.put("*/api/v1/admin/settings", () => HttpResponse.json({})),- http.put("*/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json({}),- ),- ],- },- },- decorators: [- (Story) => (- <AppConfigProvider- autoFetch={false}- bootstrapMode="non-blocking"- initialConfig={{ enableLogin: true }}- >- <UnsavedChangesProvider>- <Story />- </UnsavedChangesProvider>- </AppConfigProvider>- ),- ],-} satisfies Meta<typeof AdminAiDocumentsSection>;-export default meta;-type Story = StoryObj<typeof meta>;--/** VoyageAI embeddings with a saved (masked) API key and default retrieval settings. */-export const Default: Story = {};--/** Ollama needs a base URL instead of an API key: the key field is hidden. */-export const OllamaProvider: Story = {- parameters: {- msw: {- handlers: [- handlerFor({- rag: {- embeddingProvider: "ollama",- embeddingModel: "nomic-embed-text",- embeddingBaseUrl: "http://ollama:11434/v1",- topK: 5,- maxSearches: 3,- },- }),- ],- },- },-};--/** While the settings request is in flight, a centered loader replaces the form. */-export const Loading: Story = {- parameters: {- msw: {- handlers: [- http.get("*/api/v1/admin/settings/section/aiEngine", async () => {- await delay("infinite");- return HttpResponse.json(baseSettings);- }),- ],- },- },-};diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiDocumentsSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiDocumentsSection.tsxdeleted file mode 100644index eee54a9520..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiDocumentsSection.tsx+++ /dev/null@@ -1,378 +0,0 @@-import { useCallback, useState } from "react";-import { useTranslation } from "react-i18next";-import {- NumberInput,- PasswordInput,- Autocomplete,- Select,- TextInput,- Stack,- Paper,- Text,- Loader,- Group,- Alert,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import LocalIcon from "@app/components/shared/LocalIcon";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";-import {- AiEngineSettingsData,- AiEngineRag,- AiEngineApiResponse,- EMBEDDING_MODEL_SUGGESTIONS,- MASKED_SECRET,- clampMin,- savedToastBody,-} from "@app/components/shared/config/configSections/aiEngineSettings";--export default function AdminAiDocumentsSection() {- const { t } = useTranslation();- const { loginEnabled } = useLoginRequired();-- // Track edits to the masked secret so we never send "********" back.- const [embeddingApiKeyDirty, setEmbeddingApiKeyDirty] = useState(false);-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<AiEngineSettingsData>({- sectionName: "aiEngine",- fetchTransformer: async (): Promise<- AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }- > => {- const response = await apiClient.get<AiEngineApiResponse>(- "/api/v1/admin/settings/section/aiEngine",- );- return response.data || {};- },- // Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.- saveTransformer: (s: AiEngineSettingsData) => {- const prov = s.rag?.embeddingProvider || "voyageai";- const usesBaseUrl = prov === "ollama" || prov === "custom";- const usesApiKey = prov !== "ollama";- const deltaSettings: Record<string, unknown> = {- "aiEngine.rag.embeddingProvider": prov,- "aiEngine.rag.embeddingModel": s.rag?.embeddingModel ?? "",- // Never send a base URL for a provider that doesn't use one.- "aiEngine.rag.embeddingBaseUrl": usesBaseUrl- ? (s.rag?.embeddingBaseUrl ?? "")- : "",- "aiEngine.rag.topK": clampMin(s.rag?.topK, 1),- "aiEngine.rag.maxSearches": clampMin(s.rag?.maxSearches, 0),- };- // Send the key when the user typed one, or a provider switch cleared it; the explicit- // "" wipes the previous provider's stored key.- if (embeddingApiKeyDirty) {- deltaSettings["aiEngine.rag.embeddingApiKey"] = usesApiKey- ? (s.rag?.embeddingApiKey ?? "")- : "";- }- return { sectionData: {}, deltaSettings };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- try {- await saveSettings();- setEmbeddingApiKeyDirty(false);- markSaved();- // Pushed to the engine live (the embedder is hot-swapped), but documents embedded with the- // previous model must be re-indexed, so the toast flags that caveat.- alert({- alertType: "success",- title: t("admin.settings.ai.saved.title", "AI settings saved"),- body: `${savedToastBody(settings, t)} ${t(- "admin.settings.ai.documents.saved.reindexNote",- "If you changed the embedding model, re-index existing documents so search uses the new model.",- )}`,- });- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- setEmbeddingApiKeyDirty(false);- setSettings(resetToSnapshot());- }, [resetToSnapshot, setSettings]);-- const setRag = (patch: Partial<AiEngineRag>) =>- setSettings({ ...settings, rag: { ...(settings.rag || {}), ...patch } });-- if (loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- const embeddingProvider = settings.rag?.embeddingProvider || "voyageai";- const embeddingSuggestions =- EMBEDDING_MODEL_SUGGESTIONS[embeddingProvider] || [];- const showEmbeddingBaseUrl =- embeddingProvider === "ollama" || embeddingProvider === "custom";- // Ollama's embeddings endpoint needs no API key, mirroring the Models page.- const showEmbeddingApiKey = embeddingProvider !== "ollama";- const embeddingApiKeyLabel =- embeddingProvider === "voyageai"- ? t(- "admin.settings.ai.documents.embeddingApiKey.voyageai",- "VoyageAI API key",- )- : embeddingProvider === "openai"- ? t(- "admin.settings.ai.documents.embeddingApiKey.openai",- "OpenAI API key",- )- : t(- "admin.settings.ai.documents.embeddingApiKey.generic",- "Embedding API key",- );- const embeddingApiKeyPlaceholder =- embeddingProvider === "voyageai"- ? "pa-..."- : embeddingProvider === "openai"- ? "sk-..."- : "";-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <div>- <Text fw={600} size="lg">- {t("admin.settings.ai.documents.title", "Documents & RAG")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.ai.documents.description",- "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved.",- )}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Select- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.documents.embeddingProvider.label",- "Embedding provider",- )}- </span>- <PendingBadge- show={isFieldPending("rag.embeddingProvider")}- />- </Group>- }- description={t(- "admin.settings.ai.documents.embeddingProvider.description",- "Provider used to turn document text into vector embeddings.",- )}- data={[- { value: "voyageai", label: "VoyageAI" },- { value: "openai", label: "OpenAI" },- { value: "ollama", label: "Ollama" },- { value: "custom", label: "Custom (OpenAI-compatible)" },- ]}- value={embeddingProvider}- onChange={(v) => {- const next = v || "voyageai";- const patch: Partial<AiEngineRag> = { embeddingProvider: next };- // Clear fields the new provider doesn't use so a stale hidden value can't- // leak into the payload.- if (next !== "ollama" && next !== "custom")- patch.embeddingBaseUrl = "";- if (next !== embeddingProvider) {- // One stored key, issued for one provider: carrying it across a switch- // would 401 while the field still read "Saved". Require a re-entry.- patch.embeddingApiKey = "";- setEmbeddingApiKeyDirty(true);- }- setRag(patch);- }}- allowDeselect={false}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />-- <Autocomplete- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.documents.embeddingModel.label",- "Embedding model",- )}- </span>- <PendingBadge show={isFieldPending("rag.embeddingModel")} />- </Group>- }- description={t(- "admin.settings.ai.documents.embeddingModel.description",- "Embedding model name. Free text; suggestions are hints only.",- )}- data={embeddingSuggestions}- value={settings.rag?.embeddingModel || ""}- onChange={(value) => setRag({ embeddingModel: value })}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />-- {showEmbeddingApiKey && (- <PasswordInput- label={- <Group gap="xs">- <span>{embeddingApiKeyLabel}</span>- <PendingBadge- show={isFieldPending("rag.embeddingApiKey")}- />- </Group>- }- description={t(- "admin.settings.ai.documents.embeddingApiKey.description",- "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments.",- )}- // Blank when a key is already stored (returned masked as "********") so- // appending to the sentinel can't corrupt the saved key.- value={- embeddingApiKeyDirty- ? (settings.rag?.embeddingApiKey ?? "")- : ""- }- onChange={(e) => {- setEmbeddingApiKeyDirty(true);- setRag({ embeddingApiKey: e.target.value });- }}- placeholder={- !embeddingApiKeyDirty &&- settings.rag?.embeddingApiKey === MASKED_SECRET- ? t(- "admin.settings.ai.documents.embeddingApiKey.setPlaceholder",- "Saved - leave blank to keep the current key",- )- : embeddingApiKeyPlaceholder- }- />- )}-- {showEmbeddingBaseUrl && (- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.documents.embeddingBaseUrl.label",- "Embedding base URL",- )}- </span>- <PendingBadge- show={isFieldPending("rag.embeddingBaseUrl")}- />- </Group>- }- description={t(- "admin.settings.ai.documents.embeddingBaseUrl.description",- "Base URL of the OpenAI-compatible / Ollama embeddings endpoint, e.g. http://ollama:11434/v1. Must point at a trusted internal endpoint (SSRF-sensitive).",- )}- value={settings.rag?.embeddingBaseUrl || ""}- onChange={(e) => setRag({ embeddingBaseUrl: e.target.value })}- placeholder="http://ollama:11434/v1"- />- )}-- <NumberInput- label={- <Group gap="xs">- <span>- {t("admin.settings.ai.documents.topK.label", "Top K")}- </span>- <PendingBadge show={isFieldPending("rag.topK")} />- </Group>- }- description={t(- "admin.settings.ai.documents.topK.description",- "Number of most-relevant chunks retrieved per search.",- )}- value={settings.rag?.topK ?? 0}- onChange={(value) => setRag({ topK: Number(value) })}- min={1}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.documents.maxSearches.label",- "Max searches",- )}- </span>- <PendingBadge show={isFieldPending("rag.maxSearches")} />- </Group>- }- description={t(- "admin.settings.ai.documents.maxSearches.description",- "Maximum number of retrieval searches the agent may run per request.",- )}- value={settings.rag?.maxSearches ?? 0}- onChange={(value) => setRag({ maxSearches: Number(value) })}- min={0}- />- </Stack>- </Paper>-- <Alert- variant="light"- color="orange"- title={t(- "admin.settings.ai.documents.reindexNote.title",- "Re-index required",- )}- icon={<LocalIcon icon="warning-rounded" width="1rem" height="1rem" />}- >- <Text size="xs">- {t(- "admin.settings.ai.documents.reindexNote.body",- "Changing the embedding model takes effect immediately, but documents indexed with the previous model must be re-indexed for search to return correct results.",- )}- </Text>- </Alert>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiGeneralSection.stories.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiGeneralSection.stories.tsxdeleted file mode 100644index 4061f52fd8..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiGeneralSection.stories.tsx+++ /dev/null@@ -1,82 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse } from "msw";-import AdminAiGeneralSection from "@app/components/shared/config/configSections/AdminAiGeneralSection";-import { AppConfigProvider } from "@app/contexts/AppConfigContext";-import { UnsavedChangesProvider } from "@app/contexts/UnsavedChangesContext";-import type { AiEngineApiResponse } from "@app/components/shared/config/configSections/aiEngineSettings";--// AdminAiGeneralSection fetches the shared aiEngine settings blob on mount via-// apiClient (no service seam to stub), so each variant supplies its own MSW-// handler for GET .../admin/settings/section/aiEngine. Saves PUT back to the-// same section plus the generic /admin/settings delta endpoint; the smoke-// test never clicks Save, so those aren't stubbed here.-const baseSettings: AiEngineApiResponse = {- enabled: true,- url: "http://stirling-pdf-engine:5001",- timeoutSeconds: 30,- longRunningTimeoutSeconds: 120,- streamTimeoutSeconds: 60,- features: {- chat: true,- documentQuestions: true,- createPdf: false,- mathAuditor: false,- pdfComment: false,- classify: true,- },-};--const handlerFor = (data: AiEngineApiResponse) =>- http.get("*/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json(data),- );--const meta = {- title: "Config/AdminAiGeneralSection",- component: AdminAiGeneralSection,- parameters: {- layout: "padded",- msw: { handlers: [handlerFor(baseSettings)] },- },- // useSettingsDirty() reads UnsavedChangesContext and the section reads login- // state via useAppConfig(), neither of which the global preview supplies.- decorators: [- (Story) => (- <AppConfigProvider- autoFetch={false}- bootstrapMode="non-blocking"- initialConfig={{ enableLogin: true }}- >- <UnsavedChangesProvider>- <Story />- </UnsavedChangesProvider>- </AppConfigProvider>- ),- ],-} satisfies Meta<typeof AdminAiGeneralSection>;-export default meta;-type Story = StoryObj<typeof meta>;--/** AI enabled, connected to an engine, with a mix of capabilities toggled on. */-export const Default: Story = {};--/** Master switch off: the URL, timeouts, and capability switches are all disabled. */-export const Disabled: Story = {- parameters: {- msw: { handlers: [handlerFor({ ...baseSettings, enabled: false })] },- },-};--/** The engine URL was changed and saved but awaits a restart to take effect. */-export const PendingRestart: Story = {- parameters: {- msw: {- handlers: [- handlerFor({- ...baseSettings,- _pending: { url: "http://stirling-pdf-engine:6001" },- }),- ],- },- },-};diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiGeneralSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiGeneralSection.tsxdeleted file mode 100644index f28803fcc5..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiGeneralSection.tsx+++ /dev/null@@ -1,506 +0,0 @@-import { useCallback, useState } from "react";-import { useTranslation } from "react-i18next";-import {- TextInput,- NumberInput,- Switch,- Stack,- Paper,- Text,- Loader,- Group,- Alert,- Code,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import LocalIcon from "@app/components/shared/LocalIcon";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import { Button } from "@app/ui/Button";-import {- AiEngineSettingsData,- AiEngineFeatures,- AiEngineApiResponse,- clampMin,-} from "@app/components/shared/config/configSections/aiEngineSettings";--export default function AdminAiGeneralSection() {- const { t } = useTranslation();- const { loginEnabled } = useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<AiEngineSettingsData>({- sectionName: "aiEngine",- fetchTransformer: async (): Promise<- AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }- > => {- const response = await apiClient.get<AiEngineApiResponse>(- "/api/v1/admin/settings/section/aiEngine",- );- return response.data || {};- },- // Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.- saveTransformer: (s: AiEngineSettingsData) => ({- sectionData: {},- deltaSettings: {- "aiEngine.enabled": s.enabled ?? false,- "aiEngine.url": s.url ?? "",- // Timeouts must be >= 1s; a 0 would make every engine call fail/deadlock.- "aiEngine.timeoutSeconds": clampMin(s.timeoutSeconds, 1),- "aiEngine.longRunningTimeoutSeconds": clampMin(- s.longRunningTimeoutSeconds,- 1,- ),- "aiEngine.streamTimeoutSeconds": clampMin(s.streamTimeoutSeconds, 1),- "aiEngine.features.chat": s.features?.chat ?? false,- "aiEngine.features.documentQuestions":- s.features?.documentQuestions ?? false,- "aiEngine.features.createPdf": s.features?.createPdf ?? false,- "aiEngine.features.mathAuditor": s.features?.mathAuditor ?? false,- "aiEngine.features.pdfComment": s.features?.pdfComment ?? false,- "aiEngine.features.classify": s.features?.classify ?? false,- },- }),- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- try {- await saveSettings();- markSaved();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- setSettings(resetToSnapshot());- }, [resetToSnapshot, setSettings]);-- const [testingConnection, setTestingConnection] = useState(false);-- // Probe the RUNNING configuration (the Java bean), not unsaved form values -- // after enabling AI or changing the URL, save + restart first, then test.- const handleTestConnection = async () => {- setTestingConnection(true);- try {- await apiClient.get("/api/v1/ai/health");- alert({- alertType: "success",- title: t(- "admin.settings.ai.general.test.okTitle",- "AI engine reachable",- ),- body: t(- "admin.settings.ai.general.test.okBody",- "The AI engine responded to a health check.",- ),- });- } catch (error) {- const detail =- (error as { response?: { data?: { message?: string } } })?.response- ?.data?.message ||- t(- "admin.settings.ai.general.test.failBody",- "The AI engine did not respond. Check the URL, that the engine container is running, and that AI is enabled (a restart is needed after enabling).",- );- alert({- alertType: "error",- title: t(- "admin.settings.ai.general.test.failTitle",- "AI engine unreachable",- ),- body: detail,- });- } finally {- setTestingConnection(false);- }- };-- const setFeatures = (patch: Partial<AiEngineFeatures>) =>- setSettings({- ...settings,- features: { ...(settings.features || {}), ...patch },- });-- if (loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- const enabled = settings.enabled || false;-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <div>- <Text fw={600} size="lg">- {t("admin.settings.ai.general.title", "AI Engine")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.ai.general.description",- "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart.",- )}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Text fw={500} size="sm">- {t("admin.settings.ai.general.enabled.label", "Enable AI")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.ai.general.enabled.description",- "Master switch. When off, no AI tools, agents, or engine calls are available.",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={enabled}- onChange={(e) =>- setSettings({ ...settings, enabled: e.target.checked })- }- aria-label={t(- "admin.settings.ai.general.enabled.label",- "Enable AI",- )}- />- <PendingBadge show={isFieldPending("enabled")} />- </Group>- </Group>-- <TextInput- label={- <Group gap="xs">- <span>- {t("admin.settings.ai.general.url.label", "AI engine URL")}- </span>- <PendingBadge show={isFieldPending("url")} />- </Group>- }- description={t(- "admin.settings.ai.general.url.description",- "Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001.",- )}- value={settings.url || ""}- onChange={(e) =>- setSettings({ ...settings, url: e.target.value })- }- placeholder="http://stirling-pdf-engine:5001"- disabled={!enabled}- />-- <Group justify="flex-end">- <Button- variant="secondary"- size="sm"- loading={testingConnection}- onClick={handleTestConnection}- >- {t("admin.settings.ai.general.test.button", "Test connection")}- </Button>- </Group>-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.general.timeoutSeconds.label",- "Request timeout (seconds)",- )}- </span>- <PendingBadge show={isFieldPending("timeoutSeconds")} />- </Group>- }- description={t(- "admin.settings.ai.general.timeoutSeconds.description",- "Timeout for standard AI requests to the engine.",- )}- value={settings.timeoutSeconds ?? 0}- onChange={(value) =>- setSettings({ ...settings, timeoutSeconds: Number(value) })- }- min={1}- disabled={!enabled}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.general.longRunningTimeoutSeconds.label",- "Long-running timeout (seconds)",- )}- </span>- <PendingBadge- show={isFieldPending("longRunningTimeoutSeconds")}- />- </Group>- }- description={t(- "admin.settings.ai.general.longRunningTimeoutSeconds.description",- "Timeout for heavier agent operations such as document generation.",- )}- value={settings.longRunningTimeoutSeconds ?? 0}- onChange={(value) =>- setSettings({- ...settings,- longRunningTimeoutSeconds: Number(value),- })- }- min={1}- disabled={!enabled}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.general.streamTimeoutSeconds.label",- "Stream timeout (seconds)",- )}- </span>- <PendingBadge show={isFieldPending("streamTimeoutSeconds")} />- </Group>- }- description={t(- "admin.settings.ai.general.streamTimeoutSeconds.description",- "Timeout for streamed (token-by-token) chat responses.",- )}- value={settings.streamTimeoutSeconds ?? 0}- onChange={(value) =>- setSettings({- ...settings,- streamTimeoutSeconds: Number(value),- })- }- min={1}- disabled={!enabled}- />- </Stack>- </Paper>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Text fw={600} size="sm">- {t(- "admin.settings.ai.general.capabilities.title",- "Capabilities",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.ai.general.capabilities.description",- "Turn individual AI features on or off. Disabled features are hidden in the app.",- )}- </Text>- </div>-- <FeatureSwitch- label={t(- "admin.settings.ai.general.features.chat.label",- "Chat assistant",- )}- description={t(- "admin.settings.ai.general.features.chat.description",- "Conversational assistant for working with PDFs.",- )}- checked={settings.features?.chat ?? false}- onChange={(checked) => setFeatures({ chat: checked })}- pending={isFieldPending("features.chat")}- disabled={!enabled}- />- <FeatureSwitch- label={t(- "admin.settings.ai.general.features.documentQuestions.label",- "Document questions",- )}- description={t(- "admin.settings.ai.general.features.documentQuestions.description",- "Ask questions and get answers grounded in an uploaded document.",- )}- checked={settings.features?.documentQuestions ?? false}- onChange={(checked) =>- setFeatures({ documentQuestions: checked })- }- pending={isFieldPending("features.documentQuestions")}- disabled={!enabled}- />- <FeatureSwitch- label={t(- "admin.settings.ai.general.features.createPdf.label",- "Create PDF from prompt",- )}- description={t(- "admin.settings.ai.general.features.createPdf.description",- "Generate a new PDF (e.g. from HTML) via an AI agent.",- )}- checked={settings.features?.createPdf ?? false}- onChange={(checked) => setFeatures({ createPdf: checked })}- pending={isFieldPending("features.createPdf")}- disabled={!enabled}- />- <FeatureSwitch- label={t(- "admin.settings.ai.general.features.mathAuditor.label",- "Math auditor",- )}- description={t(- "admin.settings.ai.general.features.mathAuditor.description",- "Review documents for mathematical and numerical errors.",- )}- checked={settings.features?.mathAuditor ?? false}- onChange={(checked) => setFeatures({ mathAuditor: checked })}- pending={isFieldPending("features.mathAuditor")}- disabled={!enabled}- />- <FeatureSwitch- label={t(- "admin.settings.ai.general.features.pdfComment.label",- "PDF comment agent",- )}- description={t(- "admin.settings.ai.general.features.pdfComment.description",- "Add AI-authored review comments and annotations to a PDF.",- )}- checked={settings.features?.pdfComment ?? false}- onChange={(checked) => setFeatures({ pdfComment: checked })}- pending={isFieldPending("features.pdfComment")}- disabled={!enabled}- />- <FeatureSwitch- label={t(- "admin.settings.ai.general.features.classify.label",- "Document classification",- )}- description={t(- "admin.settings.ai.general.features.classify.description",- "Automatically categorise documents by type or content.",- )}- checked={settings.features?.classify ?? false}- onChange={(checked) => setFeatures({ classify: checked })}- pending={isFieldPending("features.classify")}- disabled={!enabled}- />- </Stack>- </Paper>-- <Alert- variant="light"- color="blue"- title={t(- "admin.settings.ai.general.note.title",- "About the AI engine",- )}- icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}- >- <Text size="xs">- {t(- "admin.settings.ai.general.note.body",- "The AI engine runs as a separate service. Its shared secret",- )}{" "}- <Code>STIRLING_ENGINE_SHARED_SECRET</Code>{" "}- {t(- "admin.settings.ai.general.note.body2",- "is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved.",- )}- </Text>- </Alert>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}--interface FeatureSwitchProps {- label: string;- description: string;- checked: boolean;- onChange: (checked: boolean) => void;- pending: boolean;- disabled: boolean;-}--function FeatureSwitch({- label,- description,- checked,- onChange,- pending,- disabled,-}: FeatureSwitchProps) {- return (- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Text fw={500} size="sm">- {label}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {description}- </Text>- </div>- <Group gap="xs">- <Switch- checked={checked}- onChange={(e) => onChange(e.target.checked)}- disabled={disabled}- // The visible label is a sibling Text, so the control needs its own name.- aria-label={label}- />- <PendingBadge show={pending} />- </Group>- </Group>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiLimitsSection.stories.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiLimitsSection.stories.tsxdeleted file mode 100644index 3caae46a25..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiLimitsSection.stories.tsx+++ /dev/null@@ -1,85 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse, delay } from "msw";-import AdminAiLimitsSection from "@app/components/shared/config/configSections/AdminAiLimitsSection";-import { AppConfigProvider } from "@app/contexts/AppConfigContext";-import { UnsavedChangesProvider } from "@app/contexts/UnsavedChangesContext";-import type { AiEngineApiResponse } from "@app/components/shared/config/configSections/aiEngineSettings";--// AdminAiLimitsSection takes no props: it fetches the shared aiEngine settings-// blob via apiClient on mount and reads login state through useAppConfig(), so-// each variant mocks the GET response and wraps in a fixed AppConfigProvider-// (autoFetch off, so stories never hit the real API).-const baseSettings: AiEngineApiResponse = {- limits: {- maxPages: 50,- maxCharacters: 200000,- modelMaxConcurrency: 4,- },-};--const meta = {- title: "Config/AdminAiLimitsSection",- component: AdminAiLimitsSection,- parameters: {- layout: "padded",- msw: {- handlers: [- http.get("/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json(baseSettings),- ),- http.put("/api/v1/admin/settings", () => HttpResponse.json({})),- http.put("/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json({}),- ),- ],- },- },- decorators: [- (Story) => (- <AppConfigProvider- autoFetch={false}- bootstrapMode="non-blocking"- initialConfig={{ enableLogin: true }}- >- <UnsavedChangesProvider>- <Story />- </UnsavedChangesProvider>- </AppConfigProvider>- ),- ],-} satisfies Meta<typeof AdminAiLimitsSection>;-export default meta;-type Story = StoryObj<typeof meta>;--/** Loaded limits with login enabled, so the sticky footer can appear once edited. */-export const Default: Story = {};--/** While the settings request is in flight, a centered loader replaces the form. */-export const Loading: Story = {- parameters: {- msw: {- handlers: [- http.get("/api/v1/admin/settings/section/aiEngine", async () => {- await delay("infinite");- return HttpResponse.json(baseSettings);- }),- ],- },- },-};--/** A pending (restart-required) change on max pages shows the pending badge next to its label. */-export const PendingChange: Story = {- parameters: {- msw: {- handlers: [- http.get("/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json({- ...baseSettings,- _pending: { limits: { maxPages: 100 } },- } satisfies AiEngineApiResponse),- ),- ],- },- },-};diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiLimitsSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiLimitsSection.tsxdeleted file mode 100644index 72de03ade0..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiLimitsSection.tsx+++ /dev/null@@ -1,193 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import { NumberInput, Stack, Paper, Text, Loader, Group } from "@mantine/core";-import { alert } from "@app/components/toast";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import {- AiEngineSettingsData,- AiEngineLimits,- AiEngineApiResponse,- clampMin,- savedToastBody,-} from "@app/components/shared/config/configSections/aiEngineSettings";--export default function AdminAiLimitsSection() {- const { t } = useTranslation();- const { loginEnabled } = useLoginRequired();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<AiEngineSettingsData>({- sectionName: "aiEngine",- fetchTransformer: async (): Promise<- AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }- > => {- const response = await apiClient.get<AiEngineApiResponse>(- "/api/v1/admin/settings/section/aiEngine",- );- return response.data || {};- },- // Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.- saveTransformer: (s: AiEngineSettingsData) => ({- sectionData: {},- deltaSettings: {- // All must be >= 1; a 0 page/char cap or 0 concurrency breaks or deadlocks the engine.- "aiEngine.limits.maxPages": clampMin(s.limits?.maxPages, 1),- "aiEngine.limits.maxCharacters": clampMin(s.limits?.maxCharacters, 1),- "aiEngine.limits.modelMaxConcurrency": clampMin(- s.limits?.modelMaxConcurrency,- 1,- ),- },- }),- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- try {- await saveSettings();- markSaved();- // Engine-facing values are pushed to the AI engine live on save; no restart needed.- alert({- alertType: "success",- title: t("admin.settings.ai.saved.title", "AI settings saved"),- body: savedToastBody(settings, t),- });- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- setSettings(resetToSnapshot());- }, [resetToSnapshot, setSettings]);-- const setLimits = (patch: Partial<AiEngineLimits>) =>- setSettings({- ...settings,- limits: { ...(settings.limits || {}), ...patch },- });-- if (loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <div>- <Text fw={600} size="lg">- {t("admin.settings.ai.limits.title", "Limits & Performance")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.ai.limits.description",- "Guardrails for how much work AI requests may do and how many run concurrently. Applied to the AI engine when saved.",- )}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.limits.maxPages.label",- "Max pages per request",- )}- </span>- <PendingBadge show={isFieldPending("limits.maxPages")} />- </Group>- }- description={t(- "admin.settings.ai.limits.maxPages.description",- "Guardrail: reject AI requests over this many PDF pages.",- )}- value={settings.limits?.maxPages ?? 0}- onChange={(value) => setLimits({ maxPages: Number(value) })}- min={1}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.limits.maxCharacters.label",- "Max characters per request",- )}- </span>- <PendingBadge show={isFieldPending("limits.maxCharacters")} />- </Group>- }- description={t(- "admin.settings.ai.limits.maxCharacters.description",- "Guardrail: reject AI requests whose extracted text exceeds this length.",- )}- value={settings.limits?.maxCharacters ?? 0}- onChange={(value) => setLimits({ maxCharacters: Number(value) })}- min={1}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.limits.modelMaxConcurrency.label",- "Model max concurrency",- )}- </span>- <PendingBadge- show={isFieldPending("limits.modelMaxConcurrency")}- />- </Group>- }- description={t(- "admin.settings.ai.limits.modelMaxConcurrency.description",- "Maximum simultaneous in-flight model calls across the whole engine.",- )}- value={settings.limits?.modelMaxConcurrency ?? 0}- onChange={(value) =>- setLimits({ modelMaxConcurrency: Number(value) })- }- min={1}- />- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiModelsSection.stories.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiModelsSection.stories.tsxdeleted file mode 100644index 2a1a5f96eb..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiModelsSection.stories.tsx+++ /dev/null@@ -1,106 +0,0 @@-import type React from "react";-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse } from "msw";-import AdminAiModelsSection from "@app/components/shared/config/configSections/AdminAiModelsSection";-import { AppConfigProvider } from "@app/contexts/AppConfigContext";-import { UnsavedChangesProvider } from "@app/contexts/UnsavedChangesContext";-import {- AiEngineApiResponse,- MASKED_SECRET,-} from "@app/components/shared/config/configSections/aiEngineSettings";--/**- * AdminAiModelsSection fetches its settings via apiClient on mount (through- * useAdminSettings) rather than taking props, so each story mocks the GET- * with MSW. It also reads useAppConfig()/useSettingsDirty(), which throw- * without their providers, so every story wraps in both.- */-function withProviders(Story: () => React.JSX.Element) {- return (- <AppConfigProvider autoFetch={false} initialConfig={{ enableLogin: true }}>- <UnsavedChangesProvider>- <Story />- </UnsavedChangesProvider>- </AppConfigProvider>- );-}--function aiEngineHandler(response: AiEngineApiResponse) {- return http.get("/api/v1/admin/settings/section/aiEngine", () =>- HttpResponse.json(response),- );-}--const meta = {- title: "Config/AdminAiModelsSection",- component: AdminAiModelsSection,- parameters: { layout: "padded" },- decorators: [withProviders],-} satisfies Meta<typeof AdminAiModelsSection>;-export default meta;-type Story = StoryObj<typeof meta>;--/** Anthropic provider with a saved (masked) API key and no base URL field. */-export const Default: Story = {- parameters: {- msw: {- handlers: [- aiEngineHandler({- models: {- provider: "anthropic",- smartModel: "claude-sonnet-5",- fastModel: "claude-haiku-4-5",- smartMaxTokens: 8192,- fastMaxTokens: 2048,- apiKey: MASKED_SECRET,- },- }),- ],- },- },-};--/** Ollama provider: no API key field, but a base URL input and an SSRF warning banner instead. */-export const OllamaProvider: Story = {- parameters: {- msw: {- handlers: [- aiEngineHandler({- models: {- provider: "ollama",- smartModel: "llama3.1",- fastModel: "qwen2.5",- smartMaxTokens: 4096,- fastMaxTokens: 1024,- baseUrl: "http://ollama:11434/v1",- },- }),- ],- },- },-};--/** Some fields are pending a config-management rollout — each shows a PendingBadge next to its label. */-export const PendingChanges: Story = {- parameters: {- msw: {- handlers: [- aiEngineHandler({- models: {- provider: "anthropic",- smartModel: "claude-sonnet-5",- fastModel: "claude-haiku-4-5",- smartMaxTokens: 8192,- fastMaxTokens: 2048,- apiKey: MASKED_SECRET,- },- _pending: {- models: {- smartModel: "claude-opus-4-8",- },- },- }),- ],- },- },-};diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiModelsSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiModelsSection.tsxdeleted file mode 100644index 8a5621fec3..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiModelsSection.tsx+++ /dev/null@@ -1,403 +0,0 @@-import { useCallback, useState } from "react";-import { useTranslation } from "react-i18next";-import {- TextInput,- NumberInput,- PasswordInput,- Autocomplete,- Select,- Stack,- Paper,- Text,- Loader,- Group,- Alert,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import LocalIcon from "@app/components/shared/LocalIcon";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";-import {- AiEngineSettingsData,- AiEngineModels,- AiEngineApiResponse,- MODEL_SUGGESTIONS,- MASKED_SECRET,- clampMin,- savedToastBody,-} from "@app/components/shared/config/configSections/aiEngineSettings";--export default function AdminAiModelsSection() {- const { t } = useTranslation();- const { loginEnabled } = useLoginRequired();-- // Track whether the user actually edited the masked secret. If not, we omit- // it from the delta entirely so we never send "********" back to the server.- const [apiKeyDirty, setApiKeyDirty] = useState(false);-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<AiEngineSettingsData>({- sectionName: "aiEngine",- fetchTransformer: async (): Promise<- AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }- > => {- const response = await apiClient.get<AiEngineApiResponse>(- "/api/v1/admin/settings/section/aiEngine",- );- return response.data || {};- },- // Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.- saveTransformer: (s: AiEngineSettingsData) => {- const prov = s.models?.provider || "anthropic";- const usesBaseUrl = prov === "ollama" || prov === "custom";- const usesApiKey = prov !== "ollama";- const deltaSettings: Record<string, unknown> = {- "aiEngine.models.provider": prov,- "aiEngine.models.smartModel": s.models?.smartModel ?? "",- "aiEngine.models.fastModel": s.models?.fastModel ?? "",- "aiEngine.models.smartMaxTokens": clampMin(s.models?.smartMaxTokens, 1),- "aiEngine.models.fastMaxTokens": clampMin(s.models?.fastMaxTokens, 1),- // Never send a base URL for a provider that doesn't use one (avoids leaking a- // stale value left over from a previous Ollama/Custom selection).- "aiEngine.models.baseUrl": usesBaseUrl ? (s.models?.baseUrl ?? "") : "",- };- // Send the key when the user typed one or a provider switch cleared it; the explicit- // "" wipes the old provider's stored key (and is forced for providers with no key field).- if (apiKeyDirty) {- deltaSettings["aiEngine.models.apiKey"] = usesApiKey- ? (s.models?.apiKey ?? "")- : "";- }- return { sectionData: {}, deltaSettings };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- try {- await saveSettings();- setApiKeyDirty(false);- markSaved();- // Engine-facing values are pushed to the AI engine live on save; no restart needed.- alert({- alertType: "success",- title: t("admin.settings.ai.saved.title", "AI settings saved"),- body: savedToastBody(settings, t),- });- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- setApiKeyDirty(false);- setSettings(resetToSnapshot());- }, [resetToSnapshot, setSettings]);-- const setModels = (patch: Partial<AiEngineModels>) =>- setSettings({- ...settings,- models: { ...(settings.models || {}), ...patch },- });-- if (loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- const provider = settings.models?.provider || "anthropic";- const showApiKey = provider !== "ollama";- const showBaseUrl = provider === "ollama" || provider === "custom";- const modelSuggestions = MODEL_SUGGESTIONS[provider] || [];-- const apiKeyLabel =- provider === "anthropic"- ? t("admin.settings.ai.models.apiKey.anthropic", "Anthropic API key")- : provider === "openai"- ? t("admin.settings.ai.models.apiKey.openai", "OpenAI API key")- : t("admin.settings.ai.models.apiKey.generic", "API key");- const apiKeyPlaceholder =- provider === "anthropic"- ? "sk-ant-..."- : provider === "openai"- ? "sk-..."- : "";-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <div>- <Text fw={600} size="lg">- {t("admin.settings.ai.models.title", "Models & Providers")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.ai.models.description",- "Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved.",- )}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Select- label={- <Group gap="xs">- <span>- {t("admin.settings.ai.models.provider.label", "Provider")}- </span>- <PendingBadge show={isFieldPending("models.provider")} />- </Group>- }- description={t(- "admin.settings.ai.models.provider.description",- "Which LLM provider the engine talks to.",- )}- data={[- { value: "anthropic", label: "Anthropic" },- { value: "openai", label: "OpenAI" },- { value: "ollama", label: "Ollama" },- { value: "custom", label: "Custom (OpenAI-compatible)" },- ]}- value={provider}- onChange={(v) => {- const next = v || "anthropic";- const patch: Partial<AiEngineModels> = { provider: next };- // Clear fields the new provider doesn't use so a stale hidden value can't- // leak into the payload (e.g. an Ollama base URL after switching to Anthropic).- if (next !== "ollama" && next !== "custom") patch.baseUrl = "";- if (next !== provider) {- // Only one key is stored and it belongs to its provider; carrying it across a- // switch would 401 every call while the field still read "Saved", so clear it.- patch.apiKey = "";- setApiKeyDirty(true);- }- setModels(patch);- }}- allowDeselect={false}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />-- <Autocomplete- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.models.smartModel.label",- "Smart model",- )}- </span>- <PendingBadge show={isFieldPending("models.smartModel")} />- </Group>- }- description={t(- "admin.settings.ai.models.smartModel.description",- "High-capability model for complex reasoning. Free text; suggestions are hints only.",- )}- data={modelSuggestions}- value={settings.models?.smartModel || ""}- onChange={(value) => setModels({ smartModel: value })}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />-- <Autocomplete- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.models.fastModel.label",- "Fast model",- )}- </span>- <PendingBadge show={isFieldPending("models.fastModel")} />- </Group>- }- description={t(- "admin.settings.ai.models.fastModel.description",- "Cheaper, faster model for lightweight tasks. Free text; suggestions are hints only.",- )}- data={modelSuggestions}- value={settings.models?.fastModel || ""}- onChange={(value) => setModels({ fastModel: value })}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.models.smartMaxTokens.label",- "Smart model max tokens",- )}- </span>- <PendingBadge- show={isFieldPending("models.smartMaxTokens")}- />- </Group>- }- description={t(- "admin.settings.ai.models.smartMaxTokens.description",- "Maximum output tokens for the smart model.",- )}- value={settings.models?.smartMaxTokens ?? 0}- onChange={(value) => setModels({ smartMaxTokens: Number(value) })}- min={1}- />-- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.models.fastMaxTokens.label",- "Fast model max tokens",- )}- </span>- <PendingBadge show={isFieldPending("models.fastMaxTokens")} />- </Group>- }- description={t(- "admin.settings.ai.models.fastMaxTokens.description",- "Maximum output tokens for the fast model.",- )}- value={settings.models?.fastMaxTokens ?? 0}- onChange={(value) => setModels({ fastMaxTokens: Number(value) })}- min={1}- />-- {showApiKey && (- <PasswordInput- label={- <Group gap="xs">- <span>{apiKeyLabel}</span>- <PendingBadge show={isFieldPending("models.apiKey")} />- </Group>- }- description={t(- "admin.settings.ai.models.apiKey.description",- "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments.",- )}- // Keep the field blank when a key is already stored (returned masked as "********");- // a pre-filled sentinel would corrupt the key on append, so bind the real value only once typed.- value={apiKeyDirty ? (settings.models?.apiKey ?? "") : ""}- onChange={(e) => {- setApiKeyDirty(true);- setModels({ apiKey: e.target.value });- }}- placeholder={- !apiKeyDirty && settings.models?.apiKey === MASKED_SECRET- ? t(- "admin.settings.ai.models.apiKey.setPlaceholder",- "Saved - leave blank to keep the current key",- )- : apiKeyPlaceholder- }- />- )}-- {showBaseUrl && (- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.models.baseUrl.label",- "Provider base URL",- )}- </span>- <PendingBadge show={isFieldPending("models.baseUrl")} />- </Group>- }- description={t(- "admin.settings.ai.models.baseUrl.description",- "Base URL of the OpenAI-compatible / Ollama endpoint, e.g. http://ollama:11434/v1.",- )}- value={settings.models?.baseUrl || ""}- onChange={(e) => setModels({ baseUrl: e.target.value })}- placeholder="http://ollama:11434/v1"- />- )}-- {showBaseUrl && (- <Alert- variant="light"- color="orange"- icon={- <LocalIcon- icon="warning-rounded"- width="1rem"- height="1rem"- />- }- >- <Text size="xs">- {t(- "admin.settings.ai.models.baseUrl.warning",- "The base URL must point at a trusted internal endpoint. The engine will make server-side requests to it, so an untrusted value is SSRF-sensitive.",- )}- </Text>- </Alert>- )}-- {showBaseUrl && (- <Alert- variant="light"- color="blue"- icon={- <LocalIcon icon="info-rounded" width="1rem" height="1rem" />- }- >- <Text size="xs">- {t(- "admin.settings.ai.models.baseUrl.contextWindow",- "Use a context window of at least 16,384 tokens. Smaller windows silently drop part of the prompt. Ollama defaults to 4,096 - raise OLLAMA_CONTEXT_LENGTH.",- )}- </Text>- </Alert>- )}- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsxnew file mode 100644index 0000000000..2027559ae5--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsx@@ -0,0 +1,298 @@+import { useCallback, useState } from "react";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { Stack, Loader } from "@mantine/core";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import apiClient from "@app/services/apiClient";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import {+ AiEngineSettingsData,+ AiEngineApiResponse,+ clampMin,+ savedToastBody,+} from "@app/components/shared/config/configSections/aiEngineSettings";+import { AiConnectionCard } from "@app/components/shared/config/configSections/ai/AiConnectionCard";+import { AiCapabilitiesCard } from "@app/components/shared/config/configSections/ai/AiCapabilitiesCard";+import { AiModelsCard } from "@app/components/shared/config/configSections/ai/AiModelsCard";+import { AiDocumentsCard } from "@app/components/shared/config/configSections/ai/AiDocumentsCard";+import { AiLimitsCard } from "@app/components/shared/config/configSections/ai/AiLimitsCard";+import "@app/components/shared/config/configSections/ai/AdminAiSection.css";++/** Keys the backend applies only on restart; everything else is pushed live. */+const RESTART_KEYS = [+ "enabled",+ "url",+ "timeoutSeconds",+ "longRunningTimeoutSeconds",+ "streamTimeoutSeconds",+ "features",+] as const;++/**+ * The AI engine's settings, previously four nav rows. They were never four+ * pages: all four declared `sectionName: "aiEngine"`, so they shared one query+ * key and any save reseeded its siblings' drafts from the server. One page, one+ * draft, one save.+ *+ * The two API-key flags stay separate on purpose. A single shared flag would put+ * the masked sentinel into whichever key the user did not touch and wipe it.+ */+export default function AdminAiSection() {+ const { t } = useTranslation();+ const { loginEnabled } = useLoginRequired();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();+ const [apiKeyDirty, setApiKeyDirty] = useState(false);+ const [embeddingApiKeyDirty, setEmbeddingApiKeyDirty] = useState(false);++ const {+ settings,+ setSettings,+ loading,+ saving,+ saveSettings,+ isFieldPending,+ } = useAdminSettings<AiEngineSettingsData>({+ sectionName: "aiEngine",+ enabled: loginEnabled,+ fetchTransformer: async (): Promise<+ AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }+ > => {+ const response = await apiClient.get<AiEngineApiResponse>(+ "/api/v1/admin/settings/section/aiEngine",+ );+ return response.data || {};+ },+ // The four pages' key sets were disjoint, so the merged transformer is their+ // union - no key is written by two cards.+ saveTransformer: (s: AiEngineSettingsData) => {+ const provider = s.models?.provider || "anthropic";+ const embeddingProvider = s.rag?.embeddingProvider || "voyageai";+ const modelsUseBaseUrl = provider === "ollama" || provider === "custom";+ const ragUsesBaseUrl =+ embeddingProvider === "ollama" || embeddingProvider === "custom";++ const deltaSettings: Record<string, unknown> = {+ "aiEngine.enabled": s.enabled ?? false,+ "aiEngine.url": s.url ?? "",+ // Timeouts must be >= 1s; a 0 would make every engine call fail/deadlock.+ "aiEngine.timeoutSeconds": clampMin(s.timeoutSeconds, 1),+ "aiEngine.longRunningTimeoutSeconds": clampMin(+ s.longRunningTimeoutSeconds,+ 1,+ ),+ "aiEngine.streamTimeoutSeconds": clampMin(s.streamTimeoutSeconds, 1),+ "aiEngine.features.chat": s.features?.chat ?? false,+ "aiEngine.features.documentQuestions":+ s.features?.documentQuestions ?? false,+ "aiEngine.features.createPdf": s.features?.createPdf ?? false,+ "aiEngine.features.mathAuditor": s.features?.mathAuditor ?? false,+ "aiEngine.features.pdfComment": s.features?.pdfComment ?? false,+ "aiEngine.features.classify": s.features?.classify ?? false,++ "aiEngine.models.provider": provider,+ "aiEngine.models.smartModel": s.models?.smartModel ?? "",+ "aiEngine.models.fastModel": s.models?.fastModel ?? "",+ "aiEngine.models.smartMaxTokens": clampMin(s.models?.smartMaxTokens, 1),+ "aiEngine.models.fastMaxTokens": clampMin(s.models?.fastMaxTokens, 1),+ // Never send a base URL for a provider that doesn't use one (avoids leaking a+ // stale value left over from a previous Ollama/Custom selection).+ "aiEngine.models.baseUrl": modelsUseBaseUrl+ ? (s.models?.baseUrl ?? "")+ : "",++ "aiEngine.rag.embeddingProvider": embeddingProvider,+ "aiEngine.rag.embeddingModel": s.rag?.embeddingModel ?? "",+ "aiEngine.rag.embeddingBaseUrl": ragUsesBaseUrl+ ? (s.rag?.embeddingBaseUrl ?? "")+ : "",+ "aiEngine.rag.topK": clampMin(s.rag?.topK, 1),+ // Zero is a real value here, unlike every other clamp on this page.+ "aiEngine.rag.maxSearches": clampMin(s.rag?.maxSearches, 0),++ // All must be >= 1; a 0 page/char cap or 0 concurrency breaks the engine.+ "aiEngine.limits.maxPages": clampMin(s.limits?.maxPages, 1),+ "aiEngine.limits.maxCharacters": clampMin(s.limits?.maxCharacters, 1),+ "aiEngine.limits.modelMaxConcurrency": clampMin(+ s.limits?.modelMaxConcurrency,+ 1,+ ),+ };++ // Send a key only once the user has typed one, or a provider switch has+ // cleared it; the explicit "" wipes the previous provider's stored key.+ if (apiKeyDirty) {+ deltaSettings["aiEngine.models.apiKey"] =+ provider !== "ollama" ? (s.models?.apiKey ?? "") : "";+ }+ if (embeddingApiKeyDirty) {+ deltaSettings["aiEngine.rag.embeddingApiKey"] =+ embeddingProvider !== "ollama" ? (s.rag?.embeddingApiKey ?? "") : "";+ }+ return { sectionData: {}, deltaSettings };+ },+ });++ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ settings,+ loading,+ );++ // resetToSnapshot only reads the saved copy, so the warning can compare+ // against what the server has actually indexed with.+ const saved = resetToSnapshot();+ const embeddingModelChanged =+ saved.rag?.embeddingModel !== settings.rag?.embeddingModel ||+ saved.rag?.embeddingProvider !== settings.rag?.embeddingProvider;++ const handleSave = async () => {+ // Read the pre-save state first: markSaved and the refetch both move the+ // snapshot, and the branches below need to know what actually changed.+ const before = resetToSnapshot();+ const changed = (pick: (s: AiEngineSettingsData) => unknown) =>+ JSON.stringify(pick(before)) !== JSON.stringify(pick(settings));+ const needsRestart = RESTART_KEYS.some((k) => changed((s) => s[k]));+ const reindex =+ changed((s) => s.rag?.embeddingModel) ||+ changed((s) => s.rag?.embeddingProvider);++ try {+ await saveSettings();+ setApiKeyDirty(false);+ setEmbeddingApiKeyDirty(false);+ markSaved();+ if (needsRestart) {+ showRestartModal();+ return;+ }+ alert({+ alertType: "success",+ title: t("admin.settings.ai.saved.title", "AI settings saved"),+ body: reindex+ ? `${savedToastBody(settings, t)} ${t(+ "admin.settings.ai.documents.saved.reindexNote",+ "If you changed the embedding model, re-index existing documents so search uses the new model.",+ )}`+ : savedToastBody(settings, t),+ });+ } catch (_error) {+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ }+ };++ const handleDiscard = useCallback(() => {+ setSettings(resetToSnapshot());+ setApiKeyDirty(false);+ setEmbeddingApiKeyDirty(false);+ }, [resetToSnapshot, setSettings]);++ if (loginEnabled && loading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ const card = { settings, setSettings, isFieldPending, loginEnabled };++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminAiGeneral"+ title={t("admin.settings.ai.general.connection", "Connection")}+ description={t(+ "admin.settings.ai.general.description",+ "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart.",+ )}+ >+ <AiConnectionCard {...card} />+ </SettingsCard>++ <SettingsCard+ id="adminAiCapabilities"+ title={t(+ "admin.settings.ai.general.capabilities.title",+ "Capabilities",+ )}+ description={t(+ "admin.settings.ai.general.capabilities.description",+ "Turn individual AI features on or off. Disabled features are hidden in the app.",+ )}+ >+ <AiCapabilitiesCard {...card} />+ </SettingsCard>++ <SettingsCard+ id="adminAiModels"+ title={t("settings.ai.models", "Models & Providers")}+ description={t(+ "admin.settings.ai.models.description",+ "Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved.",+ )}+ >+ <AiModelsCard+ {...card}+ apiKeyDirty={apiKeyDirty}+ setApiKeyDirty={setApiKeyDirty}+ />+ </SettingsCard>++ <SettingsCard+ id="adminAiDocuments"+ title={t("settings.ai.documents", "Documents & RAG")}+ description={t(+ "admin.settings.ai.documents.description",+ "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved.",+ )}+ >+ <AiDocumentsCard+ {...card}+ embeddingModelChanged={embeddingModelChanged}+ embeddingApiKeyDirty={embeddingApiKeyDirty}+ setEmbeddingApiKeyDirty={setEmbeddingApiKeyDirty}+ />+ </SettingsCard>++ <SettingsCard+ id="adminAiLimits"+ title={t("settings.ai.limits", "Limits & Performance")}+ description={t(+ "admin.settings.ai.limits.description",+ "Guardrails for how much work AI requests may do and how many run concurrently. Applied to the AI engine when saved.",+ )}+ >+ <AiLimitsCard {...card} />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={saving}+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsxindex fe1fcb725d..e2c60872a6 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAuditSection.tsx@@ -1,4 +1,5 @@import React, { Suspense, lazy, useState, useEffect } from "react";+import { SettingsEmptyState } from "@app/components/shared/config/SettingsEmptyState";import { isAxiosError } from "axios";import {Tabs,@@ -29,7 +30,6 @@ import AuditEventsTable from "@app/components/shared/config/configSections/auditimport AuditExportSection from "@app/components/shared/config/configSections/audit/AuditExportSection";import AuditClearDataSection from "@app/components/shared/config/configSections/audit/AuditClearDataSection";import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";import { useAppConfig } from "@app/contexts/AppConfigContext";import EnterpriseRequiredBanner from "@app/components/shared/config/EnterpriseRequiredBanner";import LocalIcon from "@app/components/shared/LocalIcon";@@ -136,15 +136,15 @@ const AdminAuditSection: React.FC = () => {if (!systemStatus) {return (- <Alert- color="yellow"- title={t("audit.notAvailable", "Audit system not available")}+ <SettingsEmptyState+ icon="fact-check"+ title={t("audit.notAvailable", "Audit logging is off")}>{t("audit.notAvailableMessage",- "The audit system is not configured or not available.",+ "Turn it on in Sign-in & security to start recording activity.",)}- </Alert>+ </SettingsEmptyState>);}@@ -152,7 +152,6 @@ const AdminAuditSection: React.FC = () => {return (<Stack gap="lg">- <LoginRequiredBanner show={!loginEnabled} /><EnterpriseRequiredBannershow={!hasEnterpriseLicense}featureName={t("settings.licensingAnalytics.audit", "Audit")}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminConnectionsSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminConnectionsSection.tsxdeleted file mode 100644index fb914fae13..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminConnectionsSection.tsx+++ /dev/null@@ -1,999 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import { useNavigate } from "react-router-dom";-import {- Stack,- Text,- Loader,- Group,- Divider,- Paper,- Switch,- Badge,- Anchor,- Select,- Collapse,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import LocalIcon from "@app/components/shared/LocalIcon";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";-import ProviderCard from "@app/components/shared/config/configSections/ProviderCard";-import {- Provider,- useAllProviders,-} from "@app/components/shared/config/configSections/providerDefinitions";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";--interface FeedbackFlags {- noValidDocument?: boolean;- errorProcessing?: boolean;- errorMessage?: boolean;-}--interface FeedbackSettings {- general?: { enabled?: boolean };- channel?: FeedbackFlags;- user?: FeedbackFlags;-}--interface TelegramSettingsData {- enabled?: boolean;- botToken?: string;- botUsername?: string;- pipelineInboxFolder?: string;- customFolderSuffix?: boolean;- enableAllowUserIDs?: boolean;- allowUserIDs?: number[];- enableAllowChannelIDs?: boolean;- allowChannelIDs?: number[];- processingTimeoutSeconds?: number;- pollingIntervalMillis?: number;- feedback?: FeedbackSettings;-}--interface MailSettings {- enabled?: boolean;- enableInvites?: boolean;- host?: string;- port?: number;- username?: string;- password?: string;- from?: string;-}--interface GoogleDriveSettings {- enabled?: boolean;- clientId?: string;- apiKey?: string;- appId?: string;-}--interface OAuth2GenericSettings {- enabled?: boolean;- provider?: string;- issuer?: string;- clientId?: string;- clientSecret?: string;- scopes?: string;- useAsUsername?: string;- autoCreateUser?: boolean;- blockRegistration?: boolean;-}--interface Saml2Settings {- enabled?: boolean;- provider?: string;- registrationId?: string;- idpMetadataUri?: string;- idpSingleLoginUrl?: string;- idpSingleLogoutUrl?: string;- idpIssuer?: string;- idpCert?: string;- privateKey?: string;- spCert?: string;- autoCreateUser?: boolean;- blockRegistration?: boolean;-}--interface OAuth2ClientSettings {- clientId?: string;- clientSecret?: string;- scopes?: string;- useAsUsername?: string;- issuer?: string;-}--type ProviderSettings =- | MailSettings- | TelegramSettingsData- | GoogleDriveSettings- | OAuth2GenericSettings- | Saml2Settings- | OAuth2ClientSettings;--interface ConnectionsSettingsData {- oauth2?: {- enabled?: boolean;- issuer?: string;- clientId?: string;- clientSecret?: string;- provider?: string;- autoCreateUser?: boolean;- blockRegistration?: boolean;- useAsUsername?: string;- scopes?: string;- client?: Record<string, OAuth2ClientSettings>;- };- saml2?: Saml2Settings;- mail?: MailSettings;- telegram?: TelegramSettingsData;- ssoAutoLogin?: boolean;- enableMobileScanner?: boolean;- mobileScannerConvertToPdf?: boolean;- mobileScannerImageResolution?: string;- mobileScannerPageFormat?: string;- mobileScannerStretchToFit?: boolean;- googleDriveEnabled?: boolean;- googleDriveClientId?: string;- googleDriveApiKey?: string;- googleDriveAppId?: string;-}--export default function AdminConnectionsSection() {- const { t } = useTranslation();- const navigate = useNavigate();- const { loginEnabled, getDisabledStyles } = useLoginRequired();- const { restartModalOpened, closeRestartModal, restartServer } =- useRestartServer();- const allProviders = useAllProviders();-- const adminSettings = useAdminSettings<ConnectionsSettingsData>({- sectionName: "connections",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- ConnectionsSettingsData & { _pending?: Record<string, unknown> }- > => {- // Fetch security settings (oauth2, saml2)- const securityResponse = await apiClient.get(- "/api/v1/admin/settings/section/security",- );- const securityData = securityResponse.data || {};-- // Fetch mail settings- const mailResponse = await apiClient.get(- "/api/v1/admin/settings/section/mail",- );- const mailData = mailResponse.data || {};-- // Fetch premium settings for SSO Auto Login- const premiumResponse = await apiClient.get(- "/api/v1/admin/settings/section/premium",- );- const premiumData = premiumResponse.data || {};-- // Fetch Telegram settings- const telegramResponse = await apiClient.get(- "/api/v1/admin/settings/section/telegram",- );- const telegramData = telegramResponse.data || {};-- // Fetch system settings for enableMobileScanner- const systemResponse = await apiClient.get(- "/api/v1/admin/settings/section/system",- );- const systemData = systemResponse.data || {};-- const result: ConnectionsSettingsData & {- _pending?: Record<string, unknown>;- } = {- oauth2: securityData.oauth2 || {},- saml2: securityData.saml2 || {},- mail: mailData || {},- telegram: telegramData || {},- ssoAutoLogin: premiumData.proFeatures?.ssoAutoLogin || false,- enableMobileScanner: systemData.enableMobileScanner || false,- mobileScannerConvertToPdf:- systemData.mobileScannerSettings?.convertToPdf !== false,- mobileScannerImageResolution:- systemData.mobileScannerSettings?.imageResolution || "full",- mobileScannerPageFormat:- systemData.mobileScannerSettings?.pageFormat || "A4",- mobileScannerStretchToFit:- systemData.mobileScannerSettings?.stretchToFit || false,- googleDriveEnabled:- premiumData.proFeatures?.googleDrive?.enabled || false,- googleDriveClientId:- premiumData.proFeatures?.googleDrive?.clientId || "",- googleDriveApiKey: premiumData.proFeatures?.googleDrive?.apiKey || "",- googleDriveAppId: premiumData.proFeatures?.googleDrive?.appId || "",- };-- // Merge pending blocks from all endpoints- const pendingBlock: Record<string, unknown> = {};- if (securityData._pending?.oauth2) {- pendingBlock.oauth2 = securityData._pending.oauth2;- }- if (securityData._pending?.saml2) {- pendingBlock.saml2 = securityData._pending.saml2;- }- if (mailData._pending) {- pendingBlock.mail = mailData._pending;- }- if (telegramData._pending) {- pendingBlock.telegram = telegramData._pending;- }- if (premiumData._pending?.proFeatures?.ssoAutoLogin !== undefined) {- pendingBlock.ssoAutoLogin =- premiumData._pending.proFeatures.ssoAutoLogin;- }- if (systemData._pending?.enableMobileScanner !== undefined) {- pendingBlock.enableMobileScanner =- systemData._pending.enableMobileScanner;- }- if (- systemData._pending?.mobileScannerSettings?.convertToPdf !== undefined- ) {- pendingBlock.mobileScannerConvertToPdf =- systemData._pending.mobileScannerSettings.convertToPdf;- }- if (- systemData._pending?.mobileScannerSettings?.imageResolution !==- undefined- ) {- pendingBlock.mobileScannerImageResolution =- systemData._pending.mobileScannerSettings.imageResolution;- }- if (- systemData._pending?.mobileScannerSettings?.pageFormat !== undefined- ) {- pendingBlock.mobileScannerPageFormat =- systemData._pending.mobileScannerSettings.pageFormat;- }- if (- systemData._pending?.mobileScannerSettings?.stretchToFit !== undefined- ) {- pendingBlock.mobileScannerStretchToFit =- systemData._pending.mobileScannerSettings.stretchToFit;- }- if (- premiumData._pending?.proFeatures?.googleDrive?.enabled !== undefined- ) {- pendingBlock.googleDriveEnabled =- premiumData._pending.proFeatures.googleDrive.enabled;- }- if (- premiumData._pending?.proFeatures?.googleDrive?.clientId !== undefined- ) {- pendingBlock.googleDriveClientId =- premiumData._pending.proFeatures.googleDrive.clientId;- }- if (- premiumData._pending?.proFeatures?.googleDrive?.apiKey !== undefined- ) {- pendingBlock.googleDriveApiKey =- premiumData._pending.proFeatures.googleDrive.apiKey;- }- if (premiumData._pending?.proFeatures?.googleDrive?.appId !== undefined) {- pendingBlock.googleDriveAppId =- premiumData._pending.proFeatures.googleDrive.appId;- }-- if (Object.keys(pendingBlock).length > 0) {- result._pending = pendingBlock;- }-- return result;- },- saveTransformer: (currentSettings: ConnectionsSettingsData) => {- const deltaSettings: Record<string, unknown> = {};-- // Build delta for oauth2 settings- if (currentSettings.oauth2) {- Object.keys(currentSettings.oauth2).forEach((key) => {- if (key !== "client") {- deltaSettings[`security.oauth2.${key}`] = (- currentSettings.oauth2 as Record<string, unknown>- )[key];- }- });-- // Build delta for specific OAuth2 providers- const oauth2Client = currentSettings.oauth2.client;- if (oauth2Client) {- Object.keys(oauth2Client).forEach((providerId) => {- const providerSettings = oauth2Client[providerId] as Record<- string,- unknown- >;- Object.keys(providerSettings).forEach((key) => {- deltaSettings[`security.oauth2.client.${providerId}.${key}`] =- providerSettings[key];- });- });- }- }-- // Build delta for saml2 settings- if (currentSettings.saml2) {- const saml2 = currentSettings.saml2 as Record<string, unknown>;- Object.keys(saml2).forEach((key) => {- deltaSettings[`security.saml2.${key}`] = saml2[key];- });- }-- // Mail settings- if (currentSettings.mail) {- const mail = currentSettings.mail as Record<string, unknown>;- Object.keys(mail).forEach((key) => {- deltaSettings[`mail.${key}`] = mail[key];- });- }-- // Telegram settings- if (currentSettings.telegram) {- const telegram = currentSettings.telegram as Record<string, unknown>;- Object.keys(telegram).forEach((key) => {- deltaSettings[`telegram.${key}`] = telegram[key];- });- }-- // SSO Auto Login- if (currentSettings?.ssoAutoLogin !== undefined) {- deltaSettings["premium.proFeatures.ssoAutoLogin"] =- currentSettings.ssoAutoLogin;- }-- // Mobile Scanner settings- if (currentSettings?.enableMobileScanner !== undefined) {- deltaSettings["system.enableMobileScanner"] =- currentSettings.enableMobileScanner;- }- if (currentSettings?.mobileScannerConvertToPdf !== undefined) {- deltaSettings["system.mobileScannerSettings.convertToPdf"] =- currentSettings.mobileScannerConvertToPdf;- }- if (currentSettings?.mobileScannerImageResolution !== undefined) {- deltaSettings["system.mobileScannerSettings.imageResolution"] =- currentSettings.mobileScannerImageResolution;- }- if (currentSettings?.mobileScannerPageFormat !== undefined) {- deltaSettings["system.mobileScannerSettings.pageFormat"] =- currentSettings.mobileScannerPageFormat;- }- if (currentSettings?.mobileScannerStretchToFit !== undefined) {- deltaSettings["system.mobileScannerSettings.stretchToFit"] =- currentSettings.mobileScannerStretchToFit;- }-- // Google Drive settings- if (currentSettings?.googleDriveEnabled !== undefined) {- deltaSettings["premium.proFeatures.googleDrive.enabled"] =- currentSettings.googleDriveEnabled;- }- if (currentSettings?.googleDriveClientId !== undefined) {- deltaSettings["premium.proFeatures.googleDrive.clientId"] =- currentSettings.googleDriveClientId;- }- if (currentSettings?.googleDriveApiKey !== undefined) {- deltaSettings["premium.proFeatures.googleDrive.apiKey"] =- currentSettings.googleDriveApiKey;- }- if (currentSettings?.googleDriveAppId !== undefined) {- deltaSettings["premium.proFeatures.googleDrive.appId"] =- currentSettings.googleDriveAppId;- }-- return {- sectionData: {},- deltaSettings,- };- },- });-- const { settings, setSettings, loading, isFieldPending } = adminSettings;-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- const handleSave = async () => {- markSaved();- try {- await adminSettings.saveSettings();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- // Override loading state when login is disabled- const actualLoading = loginEnabled ? loading : false;-- const isProviderConfigured = (provider: Provider): boolean => {- if (provider.id === "saml2") {- return settings?.saml2?.enabled === true;- }-- if (provider.id === "smtp") {- return settings?.mail?.enabled === true;- }-- if (provider.id === "telegram") {- return settings?.telegram?.enabled === true;- }-- if (provider.id === "googledrive") {- return settings?.googleDriveEnabled === true;- }-- if (provider.id === "oauth2-generic") {- return settings?.oauth2?.enabled === true;- }-- // Check if specific OAuth2 provider is configured (has clientId)- const providerSettings = settings?.oauth2?.client?.[provider.id];- return !!providerSettings?.clientId;- };-- const getProviderSettings = (provider: Provider): ProviderSettings => {- if (provider.id === "saml2") {- return settings?.saml2 || {};- }-- if (provider.id === "smtp") {- return settings?.mail || {};- }-- if (provider.id === "telegram") {- return settings?.telegram || {};- }-- if (provider.id === "googledrive") {- const gd: GoogleDriveSettings = {- enabled: settings?.googleDriveEnabled,- clientId: settings?.googleDriveClientId,- apiKey: settings?.googleDriveApiKey,- appId: settings?.googleDriveAppId,- };- return gd;- }-- if (provider.id === "oauth2-generic") {- const generic: OAuth2GenericSettings = {- enabled: settings?.oauth2?.enabled,- provider: settings?.oauth2?.provider,- issuer: settings?.oauth2?.issuer,- clientId: settings?.oauth2?.clientId,- clientSecret: settings?.oauth2?.clientSecret,- scopes: settings?.oauth2?.scopes,- useAsUsername: settings?.oauth2?.useAsUsername,- autoCreateUser: settings?.oauth2?.autoCreateUser,- blockRegistration: settings?.oauth2?.blockRegistration,- };- return generic;- }-- // Specific OAuth2 provider settings- return settings?.oauth2?.client?.[provider.id] || {};- };-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- const linkedProviders = allProviders.filter((p) => isProviderConfigured(p));- const availableProviders = allProviders.filter(- (p) => !isProviderConfigured(p),- );-- const updateProviderSettings = (- provider: Provider,- updatedSettings: Record<string, unknown>,- ) => {- if (provider.id === "smtp") {- setSettings({ ...settings, mail: updatedSettings });- } else if (provider.id === "telegram") {- setSettings({- ...settings,- telegram: updatedSettings,- });- } else if (provider.id === "googledrive") {- const gd = updatedSettings as GoogleDriveSettings;- setSettings({- ...settings,- googleDriveEnabled: gd.enabled,- googleDriveClientId: gd.clientId,- googleDriveApiKey: gd.apiKey,- googleDriveAppId: gd.appId,- });- } else if (provider.id === "saml2") {- setSettings({ ...settings, saml2: updatedSettings });- } else if (provider.id === "oauth2-generic") {- const generic = updatedSettings as OAuth2GenericSettings;- setSettings({ ...settings, oauth2: { ...settings.oauth2, ...generic } });- } else {- // Specific OAuth2 provider- const clientSettings = updatedSettings as OAuth2ClientSettings;- setSettings({- ...settings,- oauth2: {- ...settings.oauth2,- client: {- ...settings.oauth2?.client,- [provider.id]: clientSettings,- },- },- });- }- };-- return (- <div className="settings-section-container">- <Stack gap="xl" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />-- {/* Header */}- <div>- <Text fw={600} size="lg">- {t("admin.settings.connections.title", "Connections")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.connections.description",- "Configure external authentication providers like OAuth2 and SAML.",- )}- </Text>- </div>-- {/* SSO Auto Login - Premium Feature */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.connections.ssoAutoLogin.label",- "SSO Auto Login",- )}- </Text>- <Badge- color="grape"- size="sm"- style={{ cursor: "pointer" }}- onClick={() => navigate("/settings/adminPlan")}- title={t(- "admin.settings.badge.clickToUpgrade",- "Click to view plan details",- )}- >- PRO- </Badge>- </Group>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.connections.ssoAutoLogin.enable",- "Enable SSO Auto Login",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.connections.ssoAutoLogin.description",- "Automatically redirect to SSO login when authentication is required",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings?.ssoAutoLogin || false}- onChange={(e) => {- if (!loginEnabled) return; // Block change when login disabled- setSettings({- ...settings,- ssoAutoLogin: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("ssoAutoLogin")} />- </Group>- </div>- </Stack>- </Paper>-- {/* Mobile Scanner (QR Code) Upload */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group gap="xs" align="center">- <LocalIcon- icon="qr-code-rounded"- width="1.25rem"- height="1.25rem"- />- <Text fw={600} size="sm">- {t(- "admin.settings.connections.mobileScanner.label",- "Mobile Phone Upload",- )}- </Text>- </Group>-- {/* Documentation Link */}- <Anchor- href="https://docs.stirlingpdf.com/Functionality/Mobile-Scanner"- target="_blank"- size="xs"- c="var(--c-accent-text)"- >- {t(- "admin.settings.connections.documentation",- "View documentation",- )}{" "}- ↗- </Anchor>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.connections.mobileScanner.enable",- "Enable QR Code Upload",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.connections.mobileScanner.description",- "Allow users to upload files from mobile devices by scanning a QR code",- )}- </Text>- <Text size="xs" c="var(--color-amber-dark)" mt={8} fw={500}>- {t(- "admin.settings.connections.mobileScanner.note",- "Note: Requires Frontend URL to be configured. ",- )}- <Anchor- href="#"- onClick={(e) => {- e.preventDefault();- navigate("/settings/adminGeneral#frontendUrl");- }}- c="var(--color-amber-dark)"- td="underline"- >- {t(- "admin.settings.connections.mobileScanner.link",- "Configure in System Settings",- )}- </Anchor>- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings?.enableMobileScanner || false}- onChange={(e) => {- if (!loginEnabled) return; // Block change when login disabled- setSettings({- ...settings,- enableMobileScanner: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("enableMobileScanner")} />- </Group>- </div>-- {/* Mobile Scanner Settings - Only show when enabled */}- <Collapse in={settings?.enableMobileScanner || false}>- <Stack- gap="md"- mt="md"- ml="lg"- style={{- borderLeft: "2px solid var(--mantine-color-gray-3)",- paddingLeft: "1rem",- }}- >- {/* Convert to PDF */}- <div>- <Text size="sm" fw={500} mb="xs">- {t(- "admin.settings.connections.mobileScannerConvertToPdf",- "Convert Images to PDF",- )}- </Text>- <Text size="xs" c="dimmed" mb="sm">- {t(- "admin.settings.connections.mobileScannerConvertToPdfDesc",- "Automatically convert uploaded images to PDF format. If disabled, images will be kept as-is.",- )}- </Text>- <Group gap="xs">- <Switch- checked={settings?.mobileScannerConvertToPdf !== false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- mobileScannerConvertToPdf: e.target.checked,- });- }}- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("mobileScannerConvertToPdf")}- />- </Group>- </div>-- {/* PDF Conversion Settings - Only show when convertToPdf is enabled */}- {settings?.mobileScannerConvertToPdf !== false && (- <>- {/* Image Resolution */}- <div>- <Text size="sm" fw={500} mb="xs">- {t(- "admin.settings.connections.mobileScannerImageResolution",- "Image Resolution",- )}- </Text>- <Text size="xs" c="dimmed" mb="sm">- {t(- "admin.settings.connections.mobileScannerImageResolutionDesc",- 'Resolution of uploaded images. "Reduced" scales images to max 1200px to reduce file size.',- )}- </Text>- <Group gap="xs">- <Select- value={- settings?.mobileScannerImageResolution || "full"- }- onChange={(value) => {- if (!loginEnabled) return;- setSettings({- ...settings,- mobileScannerImageResolution: value || "full",- });- }}- data={[- {- value: "full",- label: t(- "admin.settings.connections.imageResolutionFull",- "Full (Original Size)",- ),- },- {- value: "reduced",- label: t(- "admin.settings.connections.imageResolutionReduced",- "Reduced (Max 1200px)",- ),- },- ]}- disabled={!loginEnabled}- style={{ width: "250px" }}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />- <PendingBadge- show={isFieldPending("mobileScannerImageResolution")}- />- </Group>- </div>-- {/* Page Format */}- <div>- <Text size="sm" fw={500} mb="xs">- {t(- "admin.settings.connections.mobileScannerPageFormat",- "Page Format",- )}- </Text>- <Text size="xs" c="dimmed" mb="sm">- {t(- "admin.settings.connections.mobileScannerPageFormatDesc",- 'PDF page size for converted images. "Keep" uses original image dimensions.',- )}- </Text>- <Group gap="xs">- <Select- value={settings?.mobileScannerPageFormat || "A4"}- onChange={(value) => {- if (!loginEnabled) return;- setSettings({- ...settings,- mobileScannerPageFormat: value || "A4",- });- }}- data={[- {- value: "keep",- label: t(- "admin.settings.connections.pageFormatKeep",- "Keep (Original Dimensions)",- ),- },- {- value: "A4",- label: t(- "admin.settings.connections.pageFormatA4",- "A4 (210×297mm)",- ),- },- {- value: "letter",- label: t(- "admin.settings.connections.pageFormatLetter",- "Letter (8.5×11in)",- ),- },- ]}- disabled={!loginEnabled}- style={{ width: "250px" }}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- />- <PendingBadge- show={isFieldPending("mobileScannerPageFormat")}- />- </Group>- </div>-- {/* Stretch to Fit */}- <div>- <Text size="sm" fw={500} mb="xs">- {t(- "admin.settings.connections.mobileScannerStretchToFit",- "Stretch to Fit",- )}- </Text>- <Text size="xs" c="dimmed" mb="sm">- {t(- "admin.settings.connections.mobileScannerStretchToFitDesc",- "Stretch images to fill the entire page. If disabled, images are centered with preserved aspect ratio.",- )}- </Text>- <Group gap="xs">- <Switch- checked={settings?.mobileScannerStretchToFit || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- mobileScannerStretchToFit: e.target.checked,- });- }}- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("mobileScannerStretchToFit")}- />- </Group>- </div>- </>- )}- </Stack>- </Collapse>- </Stack>- </Paper>-- {/* Linked Services Section - Only show if there are linked providers */}- {linkedProviders.length > 0 && (- <>- <div>- <Text fw={600} size="md" mb="md">- {t(- "admin.settings.connections.linkedServices",- "Linked Services",- )}- </Text>- <Stack gap="sm">- {linkedProviders.map((provider) => (- <ProviderCard- key={provider.id}- provider={provider}- isConfigured={true}- settings={- getProviderSettings(provider) as Record<string, unknown>- }- onChange={(updatedSettings) =>- updateProviderSettings(provider, updatedSettings)- }- disabled={!loginEnabled}- />- ))}- </Stack>- </div>-- {/* Divider between sections */}- {availableProviders.length > 0 && <Divider />}- </>- )}-- {/* Unlinked Services Section */}- {availableProviders.length > 0 && (- <div>- <Text fw={600} size="md" mb="md">- {t(- "admin.settings.connections.unlinkedServices",- "Unlinked Services",- )}- </Text>- <Stack gap="sm">- {availableProviders.map((provider) => (- <ProviderCard- key={provider.id}- provider={provider}- isConfigured={false}- settings={- getProviderSettings(provider) as Record<string, unknown>- }- onChange={(updatedSettings) =>- updateProviderSettings(provider, updatedSettings)- }- disabled={!loginEnabled}- />- ))}- </Stack>- </div>- )}-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={adminSettings.saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminDatabaseSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminDatabaseSection.tsxdeleted file mode 100644index 3d013c6bd4..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminDatabaseSection.tsx+++ /dev/null@@ -1,1145 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from "react";-import { isAxiosError } from "axios";-import { useNavigate } from "react-router-dom";-import { useTranslation } from "react-i18next";-import {- NumberInput,- Switch,- Stack,- Paper,- Text,- Loader,- Group,- TextInput,- Select,- Badge,- Table,- Tooltip,- FileInput,- Alert,- Divider,- Box,- Modal,-} from "@mantine/core";-import { Button } from "@app/ui/Button";-import { ActionIcon } from "@app/ui/ActionIcon";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import EditableSecretField from "@app/components/shared/EditableSecretField";-import apiClient from "@app/services/apiClient";-import LocalIcon from "@app/components/shared/LocalIcon";-import databaseManagementService, {- DatabaseBackupFile,-} from "@app/services/databaseManagementService";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";--interface DatabaseSettingsData {- enableCustomDatabase?: boolean;- customDatabaseUrl?: string;- username?: string;- password?: string;- type?: string;- hostName?: string;- port?: number;- name?: string;-}--export default function AdminDatabaseSection() {- const { t } = useTranslation();- const navigate = useNavigate();- const { loginEnabled, validateLoginEnabled, getDisabledStyles } =- useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();- const [backupFiles, setBackupFiles] = useState<DatabaseBackupFile[]>([]);- const [databaseVersion, setDatabaseVersion] = useState<string | null>(null);- const [backupsLoading, setBackupsLoading] = useState(false);- const [creatingBackup, setCreatingBackup] = useState(false);- const [importingUpload, setImportingUpload] = useState(false);- const [importingBackupFile, setImportingBackupFile] = useState<string | null>(- null,- );- const [deletingFile, setDeletingFile] = useState<string | null>(null);- const [downloadingFile, setDownloadingFile] = useState<string | null>(null);- const [uploadFile, setUploadFile] = useState<File | null>(null);- const [confirmImportOpen, setConfirmImportOpen] = useState(false);- const [deleteConfirmFile, setDeleteConfirmFile] = useState<string | null>(- null,- );- const [confirmCode, setConfirmCode] = useState("");- const [confirmInput, setConfirmInput] = useState("");-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<DatabaseSettingsData>({- sectionName: "database",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- DatabaseSettingsData & { _pending?: Record<string, unknown> }- > => {- const response = await apiClient.get(- "/api/v1/admin/settings/section/system",- );- const systemData = response.data || {};-- // Extract datasource from system response and handle pending- const datasource = systemData.datasource || {- enableCustomDatabase: false,- customDatabaseUrl: "",- username: "",- password: "",- type: "postgresql",- hostName: "localhost",- port: 5432,- name: "postgres",- };-- // Map pending changes from system._pending.datasource to root level- const result: DatabaseSettingsData & {- _pending?: Record<string, unknown>;- } = { ...datasource };- if (systemData._pending?.datasource) {- result._pending = systemData._pending.datasource;- }-- return result;- },- saveTransformer: (settings: DatabaseSettingsData) => {- // Convert flat settings to dot-notation for delta endpoint- const deltaSettings: Record<string, unknown> = {- "system.datasource.enableCustomDatabase": settings.enableCustomDatabase,- "system.datasource.customDatabaseUrl": settings.customDatabaseUrl,- "system.datasource.username": settings.username,- "system.datasource.password": settings.password,- "system.datasource.type": settings.type,- "system.datasource.hostName": settings.hostName,- "system.datasource.port": settings.port,- "system.datasource.name": settings.name,- };-- return {- sectionData: {},- deltaSettings,- };- },- });-- const datasourceType = (settings?.type || "").toLowerCase();- const isCustomDatabase = settings?.enableCustomDatabase === true;- const isEmbeddedH2 = useMemo(() => {- if (isCustomDatabase === false) {- return true;- }- if (datasourceType === "h2") {- return true;- }- return false;- }, [isCustomDatabase, datasourceType]);-- const loadBackupData = async () => {- if (!loginEnabled || !isEmbeddedH2) {- setBackupFiles([]);- setDatabaseVersion(null);- return;- }- setBackupsLoading(true);- try {- const data = await databaseManagementService.getDatabaseData();- setBackupFiles(data.backupFiles || []);- setDatabaseVersion(data.databaseVersion || null);- } catch (error: unknown) {- const message = isAxiosError(error)- ? error.response?.data?.message || error.message- : undefined;- alert({- alertType: "error",- title: t(- "admin.settings.database.loadError",- "Failed to load database backups",- ),- body: message,- });- } finally {- setBackupsLoading(false);- }- };-- useEffect(() => {- loadBackupData();- }, [loginEnabled, isEmbeddedH2, isCustomDatabase, datasourceType]);-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }-- try {- markSaved();- await saveSettings();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- const handleCreateBackup = async () => {- if (!validateLoginEnabled()) return;- setCreatingBackup(true);- try {- await databaseManagementService.createBackup();- alert({- alertType: "success",- title: t(- "admin.settings.database.backupCreated",- "Backup created successfully",- ),- });- await loadBackupData();- } catch (error: unknown) {- const message = isAxiosError(error)- ? error.response?.data?.message || error.message- : undefined;- alert({- alertType: "error",- title: t(- "admin.settings.database.backupFailed",- "Failed to create backup",- ),- body: message,- });- } finally {- setCreatingBackup(false);- }- };-- const performUploadImport = async () => {- if (!uploadFile) return;- setImportingUpload(true);- try {- await databaseManagementService.uploadAndImport(uploadFile);- alert({- alertType: "success",- title: t(- "admin.settings.database.importSuccess",- "Backup imported successfully",- ),- });- setUploadFile(null);- await loadBackupData();- } catch (error: unknown) {- const message = isAxiosError(error)- ? error.response?.data?.message || error.message- : undefined;- alert({- alertType: "error",- title: t(- "admin.settings.database.importFailed",- "Failed to import backup",- ),- body: message,- });- } finally {- setImportingUpload(false);- }- };-- const generateConfirmationCode = () => {- if (- typeof crypto !== "undefined" &&- typeof crypto.getRandomValues === "function"- ) {- const array = new Uint32Array(1);- crypto.getRandomValues(array);- const randomNumber = array[0] % 10000; // 0-9999- return randomNumber.toString().padStart(4, "0");- }- // Fallback: non-cryptographic but avoids Math.random(); this is only a UX safeguard.- const fallbackNumber = Date.now() % 10000;- return fallbackNumber.toString().padStart(4, "0");- };-- const handleUploadImport = () => {- if (!validateLoginEnabled()) return;- if (!uploadFile) {- alert({- alertType: "warning",- title: t(- "admin.settings.database.selectFile",- "Please select a .sql file to import",- ),- });- return;- }- const code = generateConfirmationCode();- setConfirmCode(code);- setConfirmInput("");- setConfirmImportOpen(true);- };-- const closeConfirmImportModal = () => {- setConfirmImportOpen(false);- setConfirmInput("");- };-- const handleConfirmImport = async () => {- if (confirmInput !== confirmCode) {- alert({- alertType: "warning",- title: t(- "admin.settings.database.codeMismatch",- "Confirmation code does not match",- ),- body: t(- "admin.settings.database.codeMismatchBody",- "Please enter the code exactly as shown to proceed.",- ),- });- return;- }- closeConfirmImportModal();- await performUploadImport();- };-- const handleImportExisting = async (fileName: string) => {- if (!validateLoginEnabled()) return;- setImportingBackupFile(fileName);- try {- await databaseManagementService.importFromFileName(fileName);- alert({- alertType: "success",- title: t(- "admin.settings.database.importSuccess",- "Backup imported successfully",- ),- });- await loadBackupData();- } catch (error: unknown) {- const message = isAxiosError(error)- ? error.response?.data?.message || error.message- : undefined;- alert({- alertType: "error",- title: t(- "admin.settings.database.importFailed",- "Failed to import backup",- ),- body: message,- });- } finally {- setImportingBackupFile(null);- }- };-- const handleDelete = async (fileName: string) => {- if (!validateLoginEnabled()) return;- setDeletingFile(fileName);- try {- await databaseManagementService.deleteBackup(fileName);- alert({- alertType: "success",- title: t("admin.settings.database.deleteSuccess", "Backup deleted"),- });- await loadBackupData();- } catch (error: unknown) {- const message = isAxiosError(error)- ? error.response?.data?.message || error.message- : undefined;- alert({- alertType: "error",- title: t(- "admin.settings.database.deleteFailed",- "Failed to delete backup",- ),- body: message,- });- } finally {- setDeletingFile(null);- setDeleteConfirmFile(null);- }- };-- const handleDeleteClick = (fileName: string) => {- if (!validateLoginEnabled()) return;- setDeleteConfirmFile(fileName);- };-- const handleDownload = async (fileName: string) => {- if (!validateLoginEnabled()) return;- setDownloadingFile(fileName);- let url: string | null = null;-- const link = document.createElement("a");- try {- const blob = await databaseManagementService.downloadBackup(fileName);- url = window.URL.createObjectURL(blob);- link.href = url;- link.download = fileName;- document.body.appendChild(link);- link.click();- } catch (error: unknown) {- const message = isAxiosError(error)- ? error.response?.data?.message || error.message- : undefined;- alert({- alertType: "error",- title: t(- "admin.settings.database.downloadFailed",- "Failed to download backup",- ),- body: message,- });- } finally {- if (link.isConnected) {- link.remove();- }- if (url) {- window.URL.revokeObjectURL(url);- }- setDownloadingFile(null);- }- };-- // Override loading state when login is disabled- const actualLoading = loginEnabled ? loading : false;-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />-- <div>- <Group justify="space-between" align="center">- <div>- <Text fw={600} size="lg">- {t("admin.settings.database.title", "Database")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.database.description",- "Configure custom database connection settings for enterprise deployments.",- )}- </Text>- </div>- <Badge- color="grape"- size="lg"- style={{ cursor: "pointer" }}- onClick={() => navigate("/settings/adminPlan")}- title={t(- "admin.settings.badge.clickToUpgrade",- "Click to view plan details",- )}- >- ENTERPRISE- </Badge>- </Group>- </div>-- {/* Database Configuration */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t(- "admin.settings.database.configuration",- "Database Configuration",- )}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.database.enableCustom.label",- "Enable Custom Database",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.database.enableCustom.description",- "Use your own custom database configuration instead of the default embedded database",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings?.enableCustomDatabase || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- enableCustomDatabase: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("enableCustomDatabase")} />- </Group>- </div>-- {settings?.enableCustomDatabase && (- <>- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.database.customUrl.label",- "Custom Database URL",- )}- </span>- <PendingBadge- show={isFieldPending("customDatabaseUrl")}- />- </Group>- }- description={t(- "admin.settings.database.customUrl.description",- "Full JDBC connection string (e.g., jdbc:postgresql://localhost:5432/postgres). If provided, individual connection settings below are not used.",- )}- value={settings?.customDatabaseUrl || ""}- onChange={(e) =>- setSettings({- ...settings,- customDatabaseUrl: e.target.value,- })- }- placeholder="jdbc:postgresql://localhost:5432/postgres"- disabled={!loginEnabled}- />- </div>-- <div>- <Select- label={- <Group gap="xs">- <span>- {t(- "admin.settings.database.type.label",- "Database Type",- )}- </span>- <PendingBadge show={isFieldPending("type")} />- </Group>- }- description={t(- "admin.settings.database.type.description",- "Type of database (not used if custom URL is provided)",- )}- value={settings?.type || "postgresql"}- onChange={(value) =>- setSettings({ ...settings, type: value || "postgresql" })- }- data={[- { value: "postgresql", label: "PostgreSQL" },- { value: "h2", label: "H2" },- { value: "mysql", label: "MySQL" },- { value: "mariadb", label: "MariaDB" },- ]}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.database.hostName.label",- "Host Name",- )}- </span>- <PendingBadge show={isFieldPending("hostName")} />- </Group>- }- description={t(- "admin.settings.database.hostName.description",- "Database server hostname (not used if custom URL is provided)",- )}- value={settings?.hostName || ""}- onChange={(e) =>- setSettings({ ...settings, hostName: e.target.value })- }- placeholder="localhost"- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- label={- <Group gap="xs">- <span>- {t("admin.settings.database.port.label", "Port")}- </span>- <PendingBadge show={isFieldPending("port")} />- </Group>- }- description={t(- "admin.settings.database.port.description",- "Database server port (not used if custom URL is provided)",- )}- value={settings?.port || 5432}- onChange={(value) =>- setSettings({ ...settings, port: Number(value) })- }- min={1}- max={65535}- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.database.name.label",- "Database Name",- )}- </span>- <PendingBadge show={isFieldPending("name")} />- </Group>- }- description={t(- "admin.settings.database.name.description",- "Name of the database (not used if custom URL is provided)",- )}- value={settings?.name || ""}- onChange={(e) =>- setSettings({ ...settings, name: e.target.value })- }- placeholder="postgres"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.database.username.label",- "Username",- )}- </span>- <PendingBadge show={isFieldPending("username")} />- </Group>- }- description={t(- "admin.settings.database.username.description",- "Database authentication username",- )}- value={settings?.username || ""}- onChange={(e) =>- setSettings({ ...settings, username: e.target.value })- }- placeholder="postgres"- disabled={!loginEnabled}- />- </div>-- <div>- <Group gap="xs" align="center" mb={4}>- <span style={{ fontWeight: 500, fontSize: "0.875rem" }}>- {t("admin.settings.database.password.label", "Password")}- </span>- <PendingBadge show={isFieldPending("password")} />- </Group>- <EditableSecretField- description={t(- "admin.settings.database.password.description",- "Database authentication password",- )}- value={settings?.password || ""}- onChange={(value) =>- setSettings({ ...settings, password: value })- }- placeholder={t(- "admin.settings.database.password.placeholder",- "Enter database password",- )}- disabled={!loginEnabled}- />- </div>- </>- )}- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- <Stack- gap="lg"- className="settings-section-content"- style={{ marginTop: 0 }}- >- <Divider my="md" />-- <Stack gap="md">- <Group justify="space-between" align="center">- <div>- <Text fw={600} size="lg">- {t("admin.settings.database.backupTitle", "Backups & Restore")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.database.backupDescription",- "Manage H2 backups directly from the admin console.",- )}- </Text>- </div>- <Group gap="xs">- {databaseVersion && (- <Badge color="blue" variant="light">- {t("admin.settings.database.version", "H2 Version")}:{" "}- {databaseVersion}- </Badge>- )}- <Badge color={isEmbeddedH2 ? "green" : "red"} variant="light">- {isEmbeddedH2- ? t("admin.settings.database.embedded", "Embedded H2")- : t("admin.settings.database.external", "External DB")}- </Badge>- </Group>- </Group>-- {!isEmbeddedH2 && (- <Alert- icon={<LocalIcon icon="info" width="1.2rem" height="1.2rem" />}- color="yellow"- radius="md"- >- <Text fw={600} size="sm">- {t(- "admin.settings.database.h2Only",- "Backups are available only for the embedded H2 database.",- )}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.database.h2Hint",- "Set the database type to H2 and disable custom database to enable backup and restore.",- )}- </Text>- </Alert>- )}- {isEmbeddedH2 && (- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="center">- <Group gap="xs">- <LocalIcon icon="backup" width="1.4rem" height="1.4rem" />- <Text fw={600}>- {t(- "admin.settings.database.manageBackups",- "Manage backups",- )}- </Text>- </Group>- <Group gap="xs">- <Button- variant="secondary"- leftSection={- <LocalIcon icon="refresh" width="1rem" height="1rem" />- }- onClick={loadBackupData}- disabled={!loginEnabled || !isEmbeddedH2}- >- {t("admin.settings.database.refresh", "Refresh")}- </Button>- <Button- leftSection={- <LocalIcon icon="upload" width="1rem" height="1rem" />- }- onClick={handleCreateBackup}- loading={creatingBackup}- disabled={!loginEnabled || !isEmbeddedH2}- >- {t(- "admin.settings.database.createBackup",- "Create backup",- )}- </Button>- </Group>- </Group>-- <Box>- <Text fw={500} size="sm" mb={6}>- {t(- "admin.settings.database.uploadTitle",- "Upload & import",- )}- </Text>- <Group gap="sm" align="flex-end" wrap="wrap">- <FileInput- value={uploadFile}- onChange={setUploadFile}- placeholder={t(- "admin.settings.database.chooseFile",- "Choose a .sql backup file",- )}- accept=".sql"- disabled={!loginEnabled || !isEmbeddedH2}- styles={{ input: { minWidth: 280 } }}- />- <Button- variant="secondary"- onClick={handleUploadImport}- loading={importingUpload}- disabled={!loginEnabled || !isEmbeddedH2}- leftSection={- <LocalIcon- icon="play-circle"- width="1rem"- height="1rem"- />- }- >- {t(- "admin.settings.database.importFromUpload",- "Import upload",- )}- </Button>- </Group>- </Box>-- {backupsLoading ? (- <Group justify="center" py="md">- <Loader size="sm" />- </Group>- ) : backupFiles.length === 0 ? (- <Text size="sm" c="dimmed">- {isEmbeddedH2- ? t(- "admin.settings.database.noBackups",- "No backups found yet.",- )- : t(- "admin.settings.database.unavailable",- "Backup list unavailable for the current database configuration.",- )}- </Text>- ) : (- <Table- highlightOnHover- withColumnBorders- verticalSpacing="sm"- >- <Table.Thead>- <Table.Tr>- <Table.Th>- {t("admin.settings.database.fileName", "File")}- </Table.Th>- <Table.Th>- {t("admin.settings.database.created", "Created")}- </Table.Th>- <Table.Th>- {t("admin.settings.database.size", "Size")}- </Table.Th>- <Table.Th w={150}>- {t("admin.settings.database.actions", "Actions")}- </Table.Th>- </Table.Tr>- </Table.Thead>- <Table.Tbody>- {backupFiles.map((backup) => (- <Table.Tr key={backup.fileName}>- <Table.Td>{backup.fileName}</Table.Td>- <Table.Td>- {backup.formattedCreationDate ||- backup.creationDate ||- "-"}- </Table.Td>- <Table.Td>{backup.formattedFileSize || "-"}</Table.Td>- <Table.Td>- <Group gap="xs" justify="flex-start">- <Tooltip- label={t(- "admin.settings.database.download",- "Download",- )}- withArrow- >- <ActionIcon- variant="tertiary"- onClick={() =>- handleDownload(backup.fileName)- }- disabled={!loginEnabled || !isEmbeddedH2}- aria-label={t(- "admin.settings.database.download",- "Download",- )}- >- {downloadingFile === backup.fileName ? (- <Loader size="xs" />- ) : (- <LocalIcon- icon="download"- width="1rem"- height="1rem"- />- )}- </ActionIcon>- </Tooltip>- <Tooltip- label={t(- "admin.settings.database.import",- "Import",- )}- withArrow- >- <ActionIcon- variant="tertiary"- onClick={() =>- handleImportExisting(backup.fileName)- }- disabled={!loginEnabled || !isEmbeddedH2}- aria-label={t(- "admin.settings.database.import",- "Import",- )}- >- {importingBackupFile === backup.fileName ? (- <Loader size="xs" />- ) : (- <LocalIcon- icon="backup"- width="1rem"- height="1rem"- />- )}- </ActionIcon>- </Tooltip>- <Tooltip- label={t(- "admin.settings.database.delete",- "Delete",- )}- withArrow- >- <ActionIcon- variant="tertiary"- accent="danger"- onClick={() =>- handleDeleteClick(backup.fileName)- }- disabled={!loginEnabled || !isEmbeddedH2}- aria-label={t(- "admin.settings.database.delete",- "Delete",- )}- >- {deletingFile === backup.fileName ? (- <Loader size="xs" />- ) : (- <LocalIcon- icon="delete"- width="1rem"- height="1rem"- />- )}- </ActionIcon>- </Tooltip>- </Group>- </Table.Td>- </Table.Tr>- ))}- </Table.Tbody>- </Table>- )}- </Stack>- </Paper>- )}- </Stack>-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />-- <Modal- opened={confirmImportOpen}- onClose={closeConfirmImportModal}- title={t(- "admin.settings.database.confirmImportTitle",- "Confirm database import",- )}- centered- withinPortal- zIndex={Z_INDEX_OVER_CONFIG_MODAL}- >- <Stack gap="md">- <Alert- color="red"- variant="light"- icon={<LocalIcon icon="warning" width="1.2rem" height="1.2rem" />}- >- <Text fw={600}>- {t(- "admin.settings.database.overwriteWarning",- "Warning: This will overwrite the current database.",- )}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.database.overwriteWarningBody",- "All existing data will be replaced by the uploaded backup. This action cannot be undone.",- )}- </Text>- </Alert>- <Stack gap={6}>- <Text size="sm" fw={600}>- {t(- "admin.settings.database.confirmCodeLabel",- "Enter the confirmation code to proceed",- )}- </Text>- <Text size="lg" fw={700}>- {confirmCode}- </Text>- <TextInput- value={confirmInput}- onChange={(e) => setConfirmInput(e.currentTarget.value)}- placeholder={t(- "admin.settings.database.enterCode",- "Enter the code shown above",- )}- minLength={4}- maxLength={4}- disabled={importingUpload}- />- </Stack>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={closeConfirmImportModal}- disabled={importingUpload}- >- {t("cancel", "Cancel")}- </Button>- <Button- accent="danger"- onClick={handleConfirmImport}- loading={importingUpload}- disabled={confirmInput.length === 0}- >- {t("admin.settings.database.confirmImport", "Confirm import")}- </Button>- </Group>- </Stack>- </Modal>-- <Modal- opened={deleteConfirmFile !== null}- onClose={() => setDeleteConfirmFile(null)}- title={t("admin.settings.database.deleteTitle", "Delete backup")}- centered- withinPortal- zIndex={Z_INDEX_OVER_CONFIG_MODAL}- >- <Stack gap="md">- <Alert- color="red"- variant="light"- icon={<LocalIcon icon="warning" width="1.2rem" height="1.2rem" />}- >- <Text fw={600}>- {t(- "admin.settings.database.deleteConfirm",- "Delete this backup? This cannot be undone.",- )}- </Text>- <Text size="sm" c="dimmed">- {deleteConfirmFile}- </Text>- </Alert>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={() => setDeleteConfirmFile(null)}- disabled={deletingFile !== null}- >- {t("cancel", "Cancel")}- </Button>- <Button- accent="danger"- onClick={() =>- deleteConfirmFile && handleDelete(deleteConfirmFile)- }- loading={deletingFile === deleteConfirmFile}- >- {t(- "admin.settings.database.deleteConfirmAction",- "Delete backup",- )}- </Button>- </Group>- </Stack>- </Modal>- </Stack>- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminEndpointsSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminEndpointsSection.tsxdeleted file mode 100644index b4df553a93..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminEndpointsSection.tsx+++ /dev/null@@ -1,441 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import {- Stack,- Paper,- Text,- Loader,- Group,- MultiSelect,- Switch,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";--interface UISettingsData {- defaultHideUnavailableTools?: boolean;- defaultHideUnavailableConversions?: boolean;-}--interface EndpointsSettingsData {- toRemove?: string[];- groupsToRemove?: string[];-}--export default function AdminEndpointsSection() {- const { t } = useTranslation();- const { loginEnabled, validateLoginEnabled } = useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<EndpointsSettingsData>({- sectionName: "endpoints",- enabled: loginEnabled,- });-- const {- settings: uiSettings,- setSettings: setUiSettings,- loading: uiLoading,- saving: uiSaving,- saveSettings: saveUiSettings,- isFieldPending: isUiFieldPending,- } = useAdminSettings<UISettingsData>({- sectionName: "ui",- enabled: loginEnabled,- });-- const {- isDirty: isEndpointsDirty,- resetToSnapshot: resetEndpointsSnapshot,- markSaved: markEndpointsSaved,- } = useSettingsDirty(settings, loading);- const {- isDirty: isUiDirty,- resetToSnapshot: resetUiSnapshot,- markSaved: markUiSaved,- } = useSettingsDirty(uiSettings, uiLoading);-- const isDirty = isEndpointsDirty || isUiDirty;-- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }-- try {- if (isEndpointsDirty) {- markEndpointsSaved();- await saveSettings();- }- if (isUiDirty) {- markUiSaved();- await saveUiSettings();- }- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- if (isEndpointsDirty) {- const original = resetEndpointsSnapshot();- setSettings(original);- }- if (isUiDirty) {- const original = resetUiSnapshot();- setUiSettings(original);- }- }, [- isEndpointsDirty,- isUiDirty,- resetEndpointsSnapshot,- resetUiSnapshot,- setSettings,- setUiSettings,- ]);-- // Override loading state when login is disabled- const actualLoading = loginEnabled ? loading || uiLoading : false;-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- // Complete list of all endpoints from frontend tool registry (alphabetical)- const commonEndpoints = [- "add-attachments",- "add-image",- "add-page-numbers",- "add-password",- "add-stamp",- "add-watermark",- "adjust-contrast",- "auto-redact",- "auto-rename",- "auto-split-pdf",- "automate",- "booklet-imposition",- "cert-sign",- "compare",- "compress-pdf",- "crop",- "dev-airgapped-docs",- "dev-api-docs",- "dev-folder-scanning-docs",- "dev-sso-guide-docs",- "edit-table-of-contents",- "eml-to-pdf",- "extract-image-scans",- "extract-images",- "file-to-pdf",- "flatten",- "get-info-on-pdf",- "handleData",- "html-to-pdf",- "img-to-pdf",- "markdown-to-pdf",- "merge-pdfs",- "multi-page-layout",- "multi-tool",- "ocr-pdf",- "overlay-pdf",- "pdf-to-csv",- "pdf-to-xlsx",- "pdf-to-epub",- "pdf-to-html",- "pdf-to-img",- "pdf-to-markdown",- "pdf-to-pdfa",- "pdf-to-presentation",- "pdf-to-single-page",- "pdf-to-text",- "pdf-to-word",- "pdf-to-xml",- "pipeline",- "rearrange-pages",- "remove-annotations",- "remove-blanks",- "remove-cert-sign",- "remove-image-pdf",- "remove-pages",- "remove-password",- "repair",- "replace-invert-pdf",- "rotate-pdf",- "sanitize-pdf",- "scale-pages",- "scanner-effect",- "show-javascript",- "sign",- "split-by-size-or-count",- "split-pages",- "split-pdf-by-chapters",- "split-pdf-by-sections",- "text-editor-pdf",- "unlock-pdf-forms",- "update-metadata",- "validate-signature",- "view-pdf",- ];-- // Complete list of functional and tool groups from EndpointConfiguration.java- const commonGroups = [- // Functional Groups- "PageOps",- "Convert",- "Security",- "Other",- "Advance",- "Automation",- "DeveloperTools",- "DeveloperDocs",- // Tool Groups- "CLI",- "Python",- "OpenCV",- "LibreOffice",- "Unoconvert",- "Java",- "Javascript",- "qpdf",- "Ghostscript",- "ImageMagick",- "tesseract",- "OCRmyPDF",- "Weasyprint",- "Pdftohtml",- "Calibre",- "FFmpeg",- "veraPDF",- "rar",- ];-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />-- <div>- <Text fw={600} size="lg">- {t("admin.settings.endpoints.title", "API Endpoints")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.endpoints.description",- "Control which API endpoints and endpoint groups are available.",- )}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.endpoints.management", "Endpoint Management")}- </Text>-- <div>- <MultiSelect- label={- <Group gap="xs">- <span>- {t(- "admin.settings.endpoints.toRemove.label",- "Disabled Endpoints",- )}- </span>- <PendingBadge show={isFieldPending("toRemove")} />- </Group>- }- description={t(- "admin.settings.endpoints.toRemove.description",- "Select individual endpoints to disable",- )}- value={settings.toRemove || []}- onChange={(value) => {- if (!loginEnabled) return;- setSettings({ ...settings, toRemove: value });- }}- data={commonEndpoints.map((endpoint) => ({- value: endpoint,- label: endpoint,- }))}- searchable- clearable- placeholder={t(- "admin.settings.endpoints.toRemove.placeholder",- "Select endpoints to disable",- )}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>-- <div>- <MultiSelect- label={- <Group gap="xs">- <span>- {t(- "admin.settings.endpoints.groupsToRemove.label",- "Disabled Endpoint Groups",- )}- </span>- <PendingBadge show={isFieldPending("groupsToRemove")} />- </Group>- }- description={t(- "admin.settings.endpoints.groupsToRemove.description",- "Select endpoint groups to disable",- )}- value={settings.groupsToRemove || []}- onChange={(value) => {- if (!loginEnabled) return;- setSettings({ ...settings, groupsToRemove: value });- }}- data={commonGroups.map((group) => ({- value: group,- label: group,- }))}- searchable- clearable- placeholder={t(- "admin.settings.endpoints.groupsToRemove.placeholder",- "Select groups to disable",- )}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>- </Stack>- </Paper>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Text fw={600} size="sm" mb="xs">- {t(- "admin.settings.endpoints.userDefaults",- "User Preference Defaults",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.endpoints.userDefaultsDescription",- "Set default values for user preferences. Users can override these in their personal settings.",- )}- </Text>- </div>-- <Switch- label={- <Group gap="xs">- <span>- {t(- "admin.settings.endpoints.defaultHideUnavailableTools.label",- "Hide unavailable tools by default",- )}- </span>- <PendingBadge- show={isUiFieldPending("defaultHideUnavailableTools")}- />- </Group>- }- description={t(- "admin.settings.endpoints.defaultHideUnavailableTools.description",- "Remove disabled tools instead of showing them greyed out",- )}- checked={uiSettings.defaultHideUnavailableTools || false}- onChange={(e) => {- if (!loginEnabled) return;- setUiSettings({- ...uiSettings,- defaultHideUnavailableTools: e.currentTarget.checked,- });- }}- disabled={!loginEnabled}- />-- <Switch- label={- <Group gap="xs">- <span>- {t(- "admin.settings.endpoints.defaultHideUnavailableConversions.label",- "Hide unavailable conversions by default",- )}- </span>- <PendingBadge- show={isUiFieldPending("defaultHideUnavailableConversions")}- />- </Group>- }- description={t(- "admin.settings.endpoints.defaultHideUnavailableConversions.description",- "Remove disabled conversion options instead of showing them greyed out",- )}- checked={uiSettings.defaultHideUnavailableConversions || false}- onChange={(e) => {- if (!loginEnabled) return;- setUiSettings({- ...uiSettings,- defaultHideUnavailableConversions: e.currentTarget.checked,- });- }}- disabled={!loginEnabled}- />- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving || uiSaving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsxdeleted file mode 100644index 15c38f0605..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsx+++ /dev/null@@ -1,374 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import { useNavigate } from "react-router-dom";-import {- TextInput,- NumberInput,- Switch,- Stack,- Paper,- Text,- Loader,- Group,- Badge,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import AdminFormDetectionSection from "@app/components/shared/config/configSections/AdminFormDetectionSection";--interface FeaturesSettingsData {- serverCertificate?: {- enabled?: boolean;- organizationName?: string;- validity?: number;- regenerateOnStartup?: boolean;- };-}--export default function AdminFeaturesSection() {- const { t } = useTranslation();- const navigate = useNavigate();- const { loginEnabled, validateLoginEnabled, getDisabledStyles } =- useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<FeaturesSettingsData>({- sectionName: "features",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- FeaturesSettingsData & { _pending?: Record<string, unknown> }- > => {- const systemResponse = await apiClient.get(- "/api/v1/admin/settings/section/system",- );- const systemData = systemResponse.data || {};-- const result: FeaturesSettingsData & {- _pending?: Record<string, unknown>;- } = {- serverCertificate: systemData.serverCertificate || {- enabled: true,- organizationName: "Stirling PDF Inc",- validity: 365,- regenerateOnStartup: false,- },- };-- // Map pending changes from system._pending.serverCertificate- if (systemData._pending?.serverCertificate) {- result._pending = {- serverCertificate: systemData._pending.serverCertificate,- };- }-- return result;- },- saveTransformer: (settings: FeaturesSettingsData) => {- const deltaSettings: Record<string, unknown> = {};-- if (settings.serverCertificate) {- deltaSettings["system.serverCertificate.enabled"] =- settings.serverCertificate.enabled;- deltaSettings["system.serverCertificate.organizationName"] =- settings.serverCertificate.organizationName;- deltaSettings["system.serverCertificate.validity"] =- settings.serverCertificate.validity;- deltaSettings["system.serverCertificate.regenerateOnStartup"] =- settings.serverCertificate.regenerateOnStartup;- }-- return {- sectionData: {},- deltaSettings,- };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }- try {- markSaved();- await saveSettings();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- const actualLoading = loginEnabled ? loading : false;-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Text fw={600} size="lg">- {t("admin.settings.features.title", "Features")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.features.description",- "Configure optional features and functionality.",- )}- </Text>- </div>-- {/* Server Certificate - Pro Feature */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.features.serverCertificate.label",- "Server Certificate",- )}- </Text>- <Badge- color="grape"- size="sm"- style={{ cursor: "pointer" }}- onClick={() => navigate("/settings/adminPlan")}- title={t(- "admin.settings.badge.clickToUpgrade",- "Click to view plan details",- )}- >- PRO- </Badge>- </Group>-- <Text size="xs" c="dimmed">- {t(- "admin.settings.features.serverCertificate.description",- 'Configure server-side certificate generation for "Sign with Stirling-PDF" functionality',- )}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.features.serverCertificate.enabled.label",- "Enable Server Certificate",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.features.serverCertificate.enabled.description",- 'Enable server-side certificate for "Sign with Stirling-PDF" option',- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.serverCertificate?.enabled ?? true}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- serverCertificate: {- ...settings.serverCertificate,- enabled: e.target.checked,- },- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge- show={isFieldPending("serverCertificate.enabled")}- />- </Group>- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.features.serverCertificate.organizationName.label",- "Organization Name",- )}- </span>- <PendingBadge- show={isFieldPending(- "serverCertificate.organizationName",- )}- />- </Group>- }- description={t(- "admin.settings.features.serverCertificate.organizationName.description",- "Organization name for generated certificates",- )}- value={- settings.serverCertificate?.organizationName ||- "Stirling PDF Inc"- }- onChange={(e) =>- setSettings({- ...settings,- serverCertificate: {- ...settings.serverCertificate,- organizationName: e.target.value,- },- })- }- placeholder="Stirling-PDF"- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.features.serverCertificate.validity.label",- "Certificate Validity (days)",- )}- </span>- <PendingBadge- show={isFieldPending("serverCertificate.validity")}- />- </Group>- }- description={t(- "admin.settings.features.serverCertificate.validity.description",- "Number of days the certificate will be valid",- )}- value={settings.serverCertificate?.validity ?? 365}- onChange={(value) =>- setSettings({- ...settings,- serverCertificate: {- ...settings.serverCertificate,- validity: Number(value),- },- })- }- min={1}- max={3650}- disabled={!loginEnabled}- />- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.features.serverCertificate.regenerateOnStartup.label",- "Regenerate on Startup",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.features.serverCertificate.regenerateOnStartup.description",- "Generate new certificate on each application startup",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={- settings.serverCertificate?.regenerateOnStartup ?? false- }- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- serverCertificate: {- ...settings.serverCertificate,- regenerateOnStartup: e.target.checked,- },- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge- show={isFieldPending("serverCertificate.regenerateOnStartup")}- />- </Group>- </div>- </Stack>- </Paper>-- <AdminFormDetectionSection />- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFolderAccessSection.stories.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFolderAccessSection.stories.tsxdeleted file mode 100644index 140445fe0e..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFolderAccessSection.stories.tsx+++ /dev/null@@ -1,95 +0,0 @@-import type React from "react";-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse } from "msw";-import AdminFolderAccessSection from "@app/components/shared/config/configSections/AdminFolderAccessSection";-import { AppConfigProvider } from "@app/contexts/AppConfigContext";-import { UnsavedChangesProvider } from "@app/contexts/UnsavedChangesContext";--/**- * AdminFolderAccessSection fetches its settings via apiClient on mount (through- * useAdminSettings, plus its own implied-folder-roots request) rather than- * taking props, so each story mocks both GETs with MSW. It also reads- * useAppConfig()/useSettingsDirty(), which throw without their providers, so- * every story wraps in both.- */-function withProviders(enableLogin: boolean) {- return function Decorator(Story: () => React.JSX.Element) {- return (- <AppConfigProvider- autoFetch={false}- bootstrapMode="non-blocking"- initialConfig={{ enableLogin }}- >- <UnsavedChangesProvider>- <Story />- </UnsavedChangesProvider>- </AppConfigProvider>- );- };-}--function impliedRootsHandler(- roots: { path: string; reason: string }[] = [- { path: "/srv/stirling/storage", reason: "serverStorage" },- { path: "/srv/stirling/watched/invoices", reason: "watchedFolder" },- ],-) {- return http.get("/api/v1/admin/settings/policies/implied-folder-roots", () =>- HttpResponse.json(roots),- );-}--function allowedRootsHandler(allowedFolderRoots: string[]) {- return http.get("/api/v1/admin/settings/section/policies", () =>- HttpResponse.json({ allowedFolderRoots }),- );-}--const meta = {- title: "Config/AdminFolderAccessSection",- component: AdminFolderAccessSection,- parameters: {- layout: "padded",- msw: {- handlers: [- http.put("/api/v1/admin/settings/section/policies", () =>- HttpResponse.json({}),- ),- ],- },- },- decorators: [withProviders(true)],-} satisfies Meta<typeof AdminFolderAccessSection>;-export default meta;-type Story = StoryObj<typeof meta>;--/** Two allowed folder roots configured, plus the always-allowed implied roots. */-export const Default: Story = {- parameters: {- msw: {- handlers: [- allowedRootsHandler(["/data/inbox", "/data/exports"]),- impliedRootsHandler(),- ],- },- },-};--/** No folder roots configured yet: folder sources and outputs are disabled. */-export const NoRootsConfigured: Story = {- parameters: {- msw: {- handlers: [allowedRootsHandler([]), impliedRootsHandler([])],- },- },-};--/** Login mode disabled: the section is read-only and shows the login-required banner. */-export const LoginDisabled: Story = {- decorators: [withProviders(false)],- parameters: {- msw: {- handlers: [allowedRootsHandler([]), impliedRootsHandler([])],- },- },-};diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFolderAccessSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFolderAccessSection.tsxdeleted file mode 100644index 742bebbbb1..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFolderAccessSection.tsx+++ /dev/null@@ -1,324 +0,0 @@-import { useCallback, useEffect, useState } from "react";-import { useTranslation } from "react-i18next";-import {- Alert,- Code,- Group,- Loader,- Paper,- Stack,- Text,- TextInput,-} from "@mantine/core";-import { Button } from "@app/ui/Button";-import LocalIcon from "@app/components/shared/LocalIcon";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import apiClient from "@app/services/apiClient";--interface FolderAccessSettingsData {- allowedFolderRoots?: string[];-}--interface ImpliedFolderRoot {- path: string;- reason: string;-}--export default function AdminFolderAccessSection() {- const { t } = useTranslation();- const { loginEnabled, validateLoginEnabled, getDisabledStyles } =- useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<FolderAccessSettingsData>({- sectionName: "policies",- enabled: loginEnabled,- });-- const [newRoot, setNewRoot] = useState("");- const [impliedRoots, setImpliedRoots] = useState<ImpliedFolderRoot[]>([]);-- useEffect(() => {- if (!loginEnabled) return;- apiClient- .get<ImpliedFolderRoot[]>(- "/api/v1/admin/settings/policies/implied-folder-roots",- )- .then((res) => setImpliedRoots(res.data ?? []))- .catch(() => setImpliedRoots([]));- }, [loginEnabled]);-- const roots = settings.allowedFolderRoots ?? [];-- const reasonLabel = (reason: string) => {- switch (reason) {- case "serverStorage":- return t(- "admin.settings.folderAccess.implied.serverStorage",- "Server file storage",- );- case "watchedFolder":- return t(- "admin.settings.folderAccess.implied.watchedFolder",- "Pipeline watched folder",- );- default:- return reason;- }- };-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const setRoots = useCallback(- (next: string[]) => {- setSettings({ ...settings, allowedFolderRoots: next });- },- [settings, setSettings],- );-- const addRoot = useCallback(() => {- const value = newRoot.trim();- if (!value) return;- if (roots.includes(value)) {- setNewRoot("");- return;- }- setRoots([...roots, value]);- setNewRoot("");- }, [newRoot, roots, setRoots]);-- const removeRoot = useCallback(- (value: string) => {- setRoots(roots.filter((root) => root !== value));- },- [roots, setRoots],- );-- const handleDiscard = useCallback(() => {- setSettings(resetToSnapshot());- setNewRoot("");- }, [resetToSnapshot, setSettings]);-- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }- try {- await saveSettings();- markSaved();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- if (loginEnabled && loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <div className="settings-section-content">- <Stack gap="sm">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Group gap="xs" align="center">- <Text fw={600} size="lg">- {t("admin.settings.folderAccess.title", "Folder Access")}- </Text>- {isFieldPending("allowedFolderRoots") && (- <PendingBadge show={true} />- )}- </Group>- <Text size="sm" c="dimmed">- {t(- "admin.settings.folderAccess.description",- "Directories that folder sources and folder outputs are allowed to read from and write to. This is a security boundary: automations can never be pointed at a server path outside this list.",- )}- </Text>- </div>-- <Alert variant="light" color="blue">- <Text size="xs">- {t(- "admin.settings.folderAccess.securityNote",- "Leave this empty to disable folder sources and outputs entirely. Stirling's own configuration directory is always off-limits, and folder access is always disabled in hosted (SaaS) mode.",- )}- </Text>- </Alert>-- <Paper withBorder p="sm" radius="md">- <Stack gap="sm">- <div>- <Text fw={600} size="sm">- {t(- "admin.settings.folderAccess.roots.label",- "Allowed folder roots",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.folderAccess.roots.hint",- "Enter absolute paths, for example /data/inbox.",- )}- </Text>- </div>-- {roots.length === 0 ? (- <Text size="sm" c="dimmed" fs="italic">- {t(- "admin.settings.folderAccess.roots.empty",- "No folders allowed. Folder sources and outputs are currently disabled.",- )}- </Text>- ) : (- <Stack gap="xs">- {roots.map((root) => (- <Group- key={root}- justify="space-between"- wrap="nowrap"- gap="xs"- >- <Code style={{ wordBreak: "break-all" }}>{root}</Code>- <Button- variant="tertiary"- aria-label={t(- "admin.settings.folderAccess.roots.remove",- "Remove folder root",- )}- leftSection={- <LocalIcon- icon="close-rounded"- width="1.1rem"- height="1.1rem"- />- }- onClick={() => removeRoot(root)}- disabled={!loginEnabled}- style={{ flexShrink: 0 }}- />- </Group>- ))}- </Stack>- )}-- <Group gap="xs" align="flex-end" wrap="nowrap">- <TextInput- style={{ flex: 1 }}- value={newRoot}- onChange={(e) => setNewRoot(e.currentTarget.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- addRoot();- }- }}- placeholder={t(- "admin.settings.folderAccess.roots.placeholder",- "/data/inbox",- )}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <Button- variant="secondary"- onClick={addRoot}- disabled={!loginEnabled || newRoot.trim().length === 0}- >- {t("admin.settings.folderAccess.roots.add", "Add")}- </Button>- </Group>- </Stack>- </Paper>-- {impliedRoots.length > 0 && (- <Paper withBorder p="sm" radius="md">- <Stack gap="sm">- <div>- <Text fw={600} size="sm">- {t(- "admin.settings.folderAccess.implied.title",- "Always allowed",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.folderAccess.implied.description",- "These Stirling-managed directories are always permitted and can't be changed here.",- )}- </Text>- </div>- <Stack gap="xs">- {impliedRoots.map((root) => (- <Group- key={root.path}- justify="space-between"- wrap="nowrap"- gap="xs"- align="center"- >- <Code style={{ wordBreak: "break-all" }}>- {root.path}- </Code>- <Group gap={6} wrap="nowrap" style={{ flexShrink: 0 }}>- <Text size="xs" c="dimmed">- {reasonLabel(root.reason)}- </Text>- <LocalIcon icon="lock" width="1rem" height="1rem" />- </Group>- </Group>- ))}- </Stack>- </Stack>- </Paper>- )}-- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </Stack>- </div>- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsxindex ed14f93b64..e1854bf67d 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsx@@ -15,7 +15,6 @@ import { StatusBadge, type StatusTone } from "@app/ui/StatusBadge";import { ProgressBar } from "@app/ui/ProgressBar";import { Banner } from "@app/ui/Banner";import { Collapsible } from "@app/ui/Collapsible";-import { Tooltip } from "@app/components/shared/Tooltip";import LocalIcon from "@app/components/shared/LocalIcon";import {useFormDetectionModelStatus,@@ -359,197 +358,169 @@ export default function AdminFormDetectionSection() {};return (- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Group justify="space-between" align="center" wrap="nowrap">- <Group gap="xs" wrap="nowrap">- <Text fw={600} size="sm">- {t("admin.formDetection.title", "AI Form Detection")}- </Text>- <Tooltip- content={t(- "admin.formDetection.description",- "Detects text fields, checkboxes and signature areas in a PDF and turns them into fillable form fields. Detection runs on this server with the model you install below.",- )}- position="top"- arrow- >+ <Stack gap="md">+ <Group justify="space-between" align="center" wrap="nowrap">+ <Group gap="xs" wrap="nowrap">+ <Text fw={500} size="sm">+ {t("admin.formDetection.enableFeature", "Enable feature")}+ </Text>+ {status ? (+ <StatusBadge tone={statusTone} size="sm">+ {statusLabel}+ </StatusBadge>+ ) : null}+ </Group>+ <Switch+ checked={enabled}+ onChange={(e) => doSetConfig({ enabled: e.currentTarget.checked })}+ disabled={configBusy || (loading && !status)}+ size="sm"+ aria-label={t("admin.formDetection.enableFeature", "Enable feature")}+ />+ </Group>++ {loading && !status ? (+ <Loader />+ ) : (+ <Stack gap="md">+ {anyError ? (+ <Banner+ tone="danger"+ icon={<LocalIcon- icon="info-outline-rounded"- width="1rem"- height="1rem"- style={{ color: "var(--c-text-subtle)", cursor: "help" }}+ icon="error-outline-rounded"+ width="1.1rem"+ height="1.1rem"/>- </Tooltip>- {status ? (- <StatusBadge tone={statusTone} size="sm">- {statusLabel}- </StatusBadge>- ) : null}- </Group>- <Switch- checked={enabled}- onChange={(e) =>- doSetConfig({ enabled: e.currentTarget.checked })}- disabled={configBusy || (loading && !status)}- size="sm"- aria-label={t(- "admin.formDetection.enableFeature",- "Enable feature",+ title={t(+ "admin.formDetection.errorTitle",+ "Something went wrong",)}+ description={anyError}/>- </Group>- </div>+ ) : null}- {loading && !status ? (- <Loader />- ) : (- <Stack gap="md">- {anyError ? (- <Banner- tone="danger"- icon={- <LocalIcon- icon="error-outline-rounded"- width="1.1rem"- height="1.1rem"- />- }- title={t(- "admin.formDetection.errorTitle",- "Something went wrong",- )}- description={anyError}- />- ) : null}-- {status && !status.writable ? (- <Banner- tone="warning"- icon={- <LocalIcon- icon="warning-rounded"- width="1.1rem"- height="1.1rem"- />- }- description={t(- "admin.formDetection.notWritable",- "The model directory is not writable; check the configs volume mount.",- )}- />- ) : null}+ {status && !status.writable ? (+ <Banner+ tone="warning"+ icon={+ <LocalIcon+ icon="warning-rounded"+ width="1.1rem"+ height="1.1rem"+ />+ }+ description={t(+ "admin.formDetection.notWritable",+ "The model directory is not writable; check the configs volume mount.",+ )}+ />+ ) : null}- {!serverEngineAvailable ? (- <Banner- tone="warning"- icon={- <LocalIcon- icon="warning-rounded"- width="1.1rem"- height="1.1rem"- />- }- description={t(- "admin.formDetection.engineUnavailable",- "This build does not include the detection engine, so the tool stays unavailable even with a model installed.",- )}- />- ) : null}+ {!serverEngineAvailable ? (+ <Banner+ tone="warning"+ icon={+ <LocalIcon+ icon="warning-rounded"+ width="1.1rem"+ height="1.1rem"+ />+ }+ description={t(+ "admin.formDetection.engineUnavailable",+ "This build does not include the detection engine, so the tool stays unavailable even with a model installed.",+ )}+ />+ ) : null}- <div>- <Text fw={500} size="sm" mb={4}>- {t("admin.formDetection.modelsLabel", "Detection model")}- </Text>- <Stack gap="xs">{catalog.map(renderModelCard)}</Stack>- </div>+ <div>+ <Text fw={500} size="sm" mb={4}>+ {t("admin.formDetection.modelsLabel", "Detection model")}+ </Text>+ <Stack gap="xs">{catalog.map(renderModelCard)}</Stack>+ </div>- <Divider />+ <Divider />- <Collapsible- open={airgapOpen}- onToggle={() => setAirgapOpen((o) => !o)}- header={- <Group gap={6} wrap="nowrap">- <LocalIcon- icon="download-rounded"- width="1rem"- height="1rem"- />- <Text size="sm">- {t(- "admin.formDetection.airgap.show",- "Offline / air-gapped install",- )}- </Text>- </Group>- }- >- <Stack gap="sm" p="sm">- <Text size="xs" c="dimmed">+ <Collapsible+ open={airgapOpen}+ onToggle={() => setAirgapOpen((o) => !o)}+ header={+ <Group gap={6} wrap="nowrap">+ <LocalIcon icon="download-rounded" width="1rem" height="1rem" />+ <Text size="sm">{t(- "admin.formDetection.airgap.intro",- "No internet on the server? Download the model elsewhere, verify it, and copy it into the model directory. It is picked up on restart.",+ "admin.formDetection.airgap.show",+ "Offline / air-gapped install",)}</Text>- {catalog- .filter((c) => c.onnxUrl)- .map((c) => (- <Stack gap={6} key={c.id}>- <Text size="xs" fw={600}>- {c.displayName}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.formDetection.airgap.step1",- "1. Download on a machine with internet:",- )}- </Text>- <CommandRow- code={`curl -L -o ${c.id}.onnx "${c.onnxUrl}"`}- copyLabel={copyLabel}- />- <Text size="xs" c="dimmed">- {t(- "admin.formDetection.airgap.step2",- "2. Check the SHA-256 checksum matches:",- )}- </Text>- <CommandRow- code={- c.sha256 ||- t(- "admin.formDetection.airgap.noSha",- "(checksum not set)",- )- }- copyLabel={copyLabel}- />- <Text size="xs" c="dimmed">- {t(- "admin.formDetection.airgap.step3",- "3. Copy it into the model directory on this server:",- )}- </Text>- <CommandRow- code={`<configs>/models/form-detection/${c.id}.onnx`}- copyLabel={copyLabel}- />- </Stack>- ))}- <Text size="xs" c="dimmed">- {t(- "admin.formDetection.airgap.step4",- "4. Set formDetection.activeModelId to the model's id in settings.yml and restart. <configs> is the configs volume (e.g. /configs in Docker). The air-gapped image ships with a model already installed.",- )}- </Text>- </Stack>- </Collapsible>- </Stack>- )}- </Stack>- </Paper>+ </Group>+ }+ >+ <Stack gap="sm" p="sm">+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.intro",+ "No internet on the server? Download the model elsewhere, verify it, and copy it into the model directory. It is picked up on restart.",+ )}+ </Text>+ {catalog+ .filter((c) => c.onnxUrl)+ .map((c) => (+ <Stack gap={6} key={c.id}>+ <Text size="xs" fw={600}>+ {c.displayName}+ </Text>+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step1",+ "1. Download on a machine with internet:",+ )}+ </Text>+ <CommandRow+ code={`curl -L -o ${c.id}.onnx "${c.onnxUrl}"`}+ copyLabel={copyLabel}+ />+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step2",+ "2. Check the SHA-256 checksum matches:",+ )}+ </Text>+ <CommandRow+ code={+ c.sha256 ||+ t(+ "admin.formDetection.airgap.noSha",+ "(checksum not set)",+ )+ }+ copyLabel={copyLabel}+ />+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step3",+ "3. Copy it into the model directory on this server:",+ )}+ </Text>+ <CommandRow+ code={`<configs>/models/form-detection/${c.id}.onnx`}+ copyLabel={copyLabel}+ />+ </Stack>+ ))}+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step4",+ "4. Set formDetection.activeModelId to the model's id in settings.yml and restart. <configs> is the configs volume (e.g. /configs in Docker). The air-gapped image ships with a model already installed.",+ )}+ </Text>+ </Stack>+ </Collapsible>+ </Stack>+ )}+ </Stack>);}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminGeneralSection.test.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminGeneralSection.test.tsxdeleted file mode 100644index eefb921360..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminGeneralSection.test.tsx+++ /dev/null@@ -1,102 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";-import { MantineProvider } from "@mantine/core";--const h = vi.hoisted(() => ({- settings: {} as Record<string, unknown>,-}));--vi.mock("@app/services/apiClient", () => ({- default: { get: vi.fn().mockResolvedValue({ data: {} }), post: vi.fn() },-}));-vi.mock("@app/hooks/useAdminSettings", () => ({- useAdminSettings: () => ({- settings: h.settings,- rawSettings: {},- loading: false,- saving: false,- setSettings: vi.fn(),- fetchSettings: vi.fn(),- saveSettings: vi.fn(),- isFieldPending: () => false,- hasPendingChanges: () => false,- }),-}));-vi.mock("@app/components/shared/config/useRestartServer", () => ({- useRestartServer: () => ({- restartModalOpened: false,- showRestartModal: vi.fn(),- closeRestartModal: vi.fn(),- restartServer: vi.fn(),- }),-}));-vi.mock("@app/hooks/useSettingsDirty", () => ({- useSettingsDirty: () => ({- isDirty: false,- resetToSnapshot: vi.fn(),- markSaved: vi.fn(),- }),-}));-vi.mock("@app/contexts/PreferencesContext", () => ({- usePreferences: () => ({ preferences: {}, updatePreference: vi.fn() }),-}));-vi.mock("@app/contexts/UnsavedChangesContext", () => ({- useUnsavedChanges: () => ({ markClean: vi.fn() }),-}));-vi.mock("@app/hooks/useLoginRequired", () => ({- useLoginRequired: () => ({- loginEnabled: true,- validateLoginEnabled: () => true,- }),-}));-// Partial mocks: @app/i18n initialises i18next at import time and needs the-// real initReactI18next, and the component only touches two router hooks.-vi.mock("react-i18next", async (importOriginal) => ({- ...(await importOriginal<typeof import("react-i18next")>()),- useTranslation: () => ({- t: (_key: string, fallback?: string) => fallback ?? _key,- i18n: { changeLanguage: vi.fn() },- }),-}));-vi.mock("react-router-dom", async (importOriginal) => ({- ...(await importOriginal<typeof import("react-router-dom")>()),- useLocation: () => ({ hash: "", pathname: "/settings/adminGeneral" }),- useNavigate: () => vi.fn(),-}));--import AdminGeneralSection from "@app/components/shared/config/configSections/AdminGeneralSection";--function renderWithLocale(defaultLocale: string) {- h.settings = { ui: {}, system: { defaultLocale } };- render(- <MantineProvider>- <AdminGeneralSection />- </MantineProvider>,- );- return screen.getByPlaceholderText("en_US") as HTMLInputElement;-}--beforeEach(() => {- vi.clearAllMocks();-});--describe("AdminGeneralSection default locale", () => {- // The Select's options are keyed on the underscore form, but- // SYSTEM_DEFAULTLOCALE accepts a hyphenated tag too, and the backend stores- // whichever form was configured.- it("shows the configured language for the underscore form", () => {- expect(renderWithLocale("en_GB").value).toBe("English (UK) (en-GB)");- });-- it("shows the configured language for the hyphenated form", () => {- expect(renderWithLocale("en-GB").value).toBe("English (UK) (en-GB)");- });-- it("matches a lowercased region tag", () => {- expect(renderWithLocale("en-gb").value).toBe("English (UK) (en-GB)");- });-- it("leaves the field empty when no locale is configured", () => {- expect(renderWithLocale("").value).toBe("");- });-});diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminGeneralSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminGeneralSection.tsxdeleted file mode 100644index 9d0a092c80..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminGeneralSection.tsx+++ /dev/null@@ -1,1347 +0,0 @@-import { useEffect, useCallback, useMemo } from "react";-import { useTranslation } from "react-i18next";-import { useLocation, useNavigate } from "react-router-dom";-import {- TextInput,- Textarea,- Switch,- Stack,- Paper,- Text,- Loader,- Group,- MultiSelect,- Badge,- Select,-} from "@mantine/core";-import { SegmentedControl } from "@app/ui/SegmentedControl";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import { usePreferences } from "@app/contexts/PreferencesContext";-import { useUnsavedChanges } from "@app/contexts/UnsavedChangesContext";-import {- normalizeLanguageCode,- supportedLanguages,- toUnderscoreFormat,- toUnderscoreLanguages,-} from "@app/i18n";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";--interface GeneralSettingsData {- ui: {- appNameNavbar?: string;- languages?: string[];- logoStyle?: "modern" | "classic";- hideDisabledTools?: {- googleDrive?: boolean;- mobileQRScanner?: boolean;- };- };- system: {- defaultLocale?: string;- showUpdate?: boolean;- showUpdateOnlyAdmin?: boolean;- customHTMLFiles?: boolean;- fileUploadLimit?: string;- frontendUrl?: string;- };- customPaths?: {- pipeline?: {- pipelineDir?: string;- watchedFoldersDir?: string;- watchedFoldersDirs?: string[];- finishedFoldersDir?: string;- };- operations?: {- weasyprint?: string;- unoconvert?: string;- };- };- customMetadata?: {- autoUpdateMetadata?: boolean;- author?: string;- creator?: string;- producer?: string;- };-}--export default function AdminGeneralSection() {- const { t } = useTranslation();- const location = useLocation();- const navigate = useNavigate();- const { loginEnabled, validateLoginEnabled } = useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();- const { preferences, updatePreference } = usePreferences();- const { markClean } = useUnsavedChanges();- const languageOptions = useMemo(- () =>- Object.entries(supportedLanguages)- .map(([code, label]) => ({- value: toUnderscoreFormat(code),- label: `${label} (${code})`,- }))- .sort((a, b) => a.label.localeCompare(b.label)),- [],- );- const parseWatchedFoldersInput = useCallback((value: string) => {- const paths = value- .split(/[\n,;]+/)- .map((entry) => entry.trim())- .filter(Boolean);-- // Deduplicate paths (case-sensitive, exact match)- const uniquePaths = Array.from(new Set(paths));-- return uniquePaths;- }, []);-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<GeneralSettingsData>({- sectionName: "general",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- GeneralSettingsData & { _pending?: Record<string, unknown> }- > => {- const [uiResponse, systemResponse, premiumResponse] = await Promise.all([- apiClient.get("/api/v1/admin/settings/section/ui"),- apiClient.get("/api/v1/admin/settings/section/system"),- apiClient.get("/api/v1/admin/settings/section/premium"),- ]);-- const ui = { ...(uiResponse.data || {}) };- const system = { ...(systemResponse.data || {}) };- const premium = { ...(premiumResponse.data || {}) };-- ui.languages = Array.isArray(ui.languages)- ? toUnderscoreLanguages(ui.languages)- : [];-- const pipelinePaths = system.customPaths?.pipeline || {};- const watchedFoldersDirs = Array.isArray(pipelinePaths.watchedFoldersDirs)- ? pipelinePaths.watchedFoldersDirs- : [];- const normalizedWatchedFoldersDirs =- watchedFoldersDirs.length > 0- ? watchedFoldersDirs- : pipelinePaths.watchedFoldersDir- ? [pipelinePaths.watchedFoldersDir]- : [];-- const result: GeneralSettingsData & {- _pending?: Record<string, unknown>;- } = {- ui,- system,- customPaths: {- ...(system.customPaths || {}),- pipeline: {- ...pipelinePaths,- pipelineDir: pipelinePaths.pipelineDir || "",- watchedFoldersDir: pipelinePaths.watchedFoldersDir || "",- watchedFoldersDirs: normalizedWatchedFoldersDirs,- finishedFoldersDir: pipelinePaths.finishedFoldersDir || "",- },- operations: {- ...(system.customPaths?.operations || {}),- weasyprint: system.customPaths?.operations?.weasyprint || "",- unoconvert: system.customPaths?.operations?.unoconvert || "",- },- },- customMetadata: premium.proFeatures?.customMetadata || {- autoUpdateMetadata: false,- author: "",- creator: "",- producer: "",- },- };-- // Merge pending blocks from all three endpoints- const pendingBlock: Record<string, unknown> = {};- if (ui._pending) {- pendingBlock.ui = ui._pending;- }- if (system._pending) {- pendingBlock.system = system._pending;- }- if (system._pending?.customPaths) {- pendingBlock.customPaths = system._pending.customPaths;- }- if (premium._pending?.proFeatures?.customMetadata) {- pendingBlock.customMetadata =- premium._pending.proFeatures.customMetadata;- }-- if (Object.keys(pendingBlock).length > 0) {- result._pending = pendingBlock;- }-- return result;- },- saveTransformer: (settings: GeneralSettingsData) => {- const deltaSettings: Record<string, unknown> = {- // UI settings- "ui.appNameNavbar": settings.ui?.appNameNavbar,- "ui.languages": settings.ui?.languages,- "ui.logoStyle": settings.ui?.logoStyle,- "ui.hideDisabledTools.googleDrive":- settings.ui?.hideDisabledTools?.googleDrive,- "ui.hideDisabledTools.mobileQRScanner":- settings.ui?.hideDisabledTools?.mobileQRScanner,- // System settings- "system.defaultLocale": settings.system?.defaultLocale,- "system.showUpdate": settings.system?.showUpdate,- "system.showUpdateOnlyAdmin": settings.system?.showUpdateOnlyAdmin,- "system.customHTMLFiles": settings.system?.customHTMLFiles,- "system.fileUploadLimit": settings.system?.fileUploadLimit,- "system.frontendUrl": settings.system?.frontendUrl,- // Premium custom metadata- "premium.proFeatures.customMetadata.autoUpdateMetadata":- settings.customMetadata?.autoUpdateMetadata,- "premium.proFeatures.customMetadata.author":- settings.customMetadata?.author,- "premium.proFeatures.customMetadata.creator":- settings.customMetadata?.creator,- "premium.proFeatures.customMetadata.producer":- settings.customMetadata?.producer,- };-- if (settings.customPaths) {- deltaSettings["system.customPaths.pipeline.pipelineDir"] =- settings.customPaths?.pipeline?.pipelineDir;- deltaSettings["system.customPaths.pipeline.watchedFoldersDir"] =- settings.customPaths?.pipeline?.watchedFoldersDir;- deltaSettings["system.customPaths.pipeline.watchedFoldersDirs"] =- settings.customPaths?.pipeline?.watchedFoldersDirs;- deltaSettings["system.customPaths.pipeline.finishedFoldersDir"] =- settings.customPaths?.pipeline?.finishedFoldersDir;- deltaSettings["system.customPaths.operations.weasyprint"] =- settings.customPaths?.operations?.weasyprint;- deltaSettings["system.customPaths.operations.unoconvert"] =- settings.customPaths?.operations?.unoconvert;- }-- return {- sectionData: {},- deltaSettings,- };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const selectedLanguages = useMemo(- () => toUnderscoreLanguages(settings.ui?.languages || []),- [settings.ui?.languages],- );- // SYSTEM_DEFAULTLOCALE accepts en-GB as well as en_GB, but every option below- // is keyed on the underscore form, so match the stored value to it before- // handing it to the Select. Normalising only what is displayed keeps the- // configured value untouched when the field is left alone.- const defaultLocaleValue = useMemo(- () =>- toUnderscoreFormat(- normalizeLanguageCode(settings.system?.defaultLocale || ""),- ),- [settings.system?.defaultLocale],- );- const watchedFoldersInput = useMemo(- () => (settings.customPaths?.pipeline?.watchedFoldersDirs || []).join("\n"),- [settings.customPaths?.pipeline?.watchedFoldersDirs],- );-- const watchedFoldersValidation = useMemo(() => {- const paths = settings.customPaths?.pipeline?.watchedFoldersDirs || [];- const finishedPath =- settings.customPaths?.pipeline?.finishedFoldersDir || "";- const warnings: string[] = [];-- // Normalize paths for comparison (handle both Windows and Unix paths)- const normalizePath = (p: string) =>- p.replace(/\\/g, "/").replace(/\/+$/, "");-- // Check for overlapping watched folders- if (paths.length >= 2) {- for (let i = 0; i < paths.length; i++) {- for (let j = i + 1; j < paths.length; j++) {- const path1 = normalizePath(paths[i]);- const path2 = normalizePath(paths[j]);-- if (path1 === path2) {- warnings.push(`Duplicate path detected: '${paths[i]}'`);- } else if (path1.startsWith(path2 + "/")) {- warnings.push(- `'${paths[i]}' is nested inside '${paths[j]}' - may cause duplicate processing`,- );- } else if (path2.startsWith(path1 + "/")) {- warnings.push(- `'${paths[j]}' is nested inside '${paths[i]}' - may cause duplicate processing`,- );- }- }- }- }-- // Check for conflicts with finished folder- if (finishedPath && paths.length > 0) {- const normalizedFinished = normalizePath(finishedPath);- for (const watchedPath of paths) {- const normalizedWatched = normalizePath(watchedPath);-- if (normalizedWatched === normalizedFinished) {- warnings.push(- `CRITICAL: Watched folder '${watchedPath}' is the same as finished folder - will cause processing loops!`,- );- } else if (normalizedFinished.startsWith(normalizedWatched + "/")) {- warnings.push(- `Finished folder is nested inside watched folder '${watchedPath}' - may cause issues`,- );- } else if (normalizedWatched.startsWith(normalizedFinished + "/")) {- warnings.push(- `CRITICAL: Watched folder '${watchedPath}' is nested inside finished folder - will cause processing loops!`,- );- }- }- }-- return warnings.length > 0 ? warnings : null;- }, [- settings.customPaths?.pipeline?.watchedFoldersDirs,- settings.customPaths?.pipeline?.finishedFoldersDir,- ]);-- // Filter default locale options based on available languages setting- const defaultLocaleOptions = useMemo(() => {- // If no languages are selected (empty), show all languages- if (!selectedLanguages || selectedLanguages.length === 0) {- return languageOptions;- }- // Otherwise, only show languages that are in the selected list- return languageOptions.filter((option) =>- selectedLanguages.includes(option.value),- );- }, [selectedLanguages, languageOptions]);-- // Sync local preference with server setting on initial load- useEffect(() => {- if (loading || !loginEnabled || !settings.ui?.logoStyle) return;-- // This ensures localStorage always reflects the server's authoritative value- updatePreference("logoVariant", settings.ui.logoStyle);- }, [loading, loginEnabled, settings.ui?.logoStyle, updatePreference]);-- // Handle hash navigation for deep linking to specific fields- useEffect(() => {- if (location.hash && !loading) {- const elementId = location.hash.substring(1); // Remove the #- const element = document.getElementById(elementId);- if (element) {- setTimeout(() => {- element.scrollIntoView({ behavior: "smooth", block: "start" });- }, 100);- }- }- }, [location.hash, loading]);-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- // Override loading state when login is disabled- const actualLoading = loginEnabled ? loading : false;-- // Show the server setting when loaded (for admin config), otherwise show user's preference- // Note: User's preference in localStorage is separate and takes precedence in the app via useLogoVariant hook- const logoStyleValue = loginEnabled- ? (settings.ui?.logoStyle ?? preferences.logoVariant ?? "modern")- : (preferences.logoVariant ?? "modern");-- const handleLogoStyleChange = (value: string) => {- const nextValue = value === "classic" ? "classic" : "modern";-- // Only update local settings state - don't update the actual preference until save- // When login is disabled, update preference immediately since there's no server to save to- if (!loginEnabled) {- updatePreference("logoVariant", nextValue);- return;- }-- setSettings({- ...settings,- ui: {- ...settings.ui,- logoStyle: nextValue,- },- });- };-- const handleSave = async () => {- // Block save if login is disabled- if (!validateLoginEnabled()) {- return;- }-- try {- // Mark that we just saved - the snapshot will be updated when refetch completes- markSaved();-- await saveSettings();-- // Update local preference after successful save so the app reflects the saved logo style- if (settings.ui?.logoStyle) {- updatePreference("logoVariant", settings.ui.logoStyle);- }-- markClean();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />-- <div>- <Text fw={600} size="lg">- {t("admin.settings.general.title", "System Settings")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.general.description",- "Configure system-wide application settings including branding and default behaviour.",- )}- </Text>- </div>-- {/* System Settings */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.general.system", "System")}- </Text>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.appNameNavbar.label",- "Navbar Brand",- )}- </span>- <PendingBadge show={isFieldPending("ui.appNameNavbar")} />- </Group>- }- description={t(- "admin.settings.general.appNameNavbar.description",- "The name displayed in the navigation bar",- )}- value={settings.ui?.appNameNavbar || ""}- onChange={(e) =>- setSettings({- ...settings,- ui: { ...settings.ui, appNameNavbar: e.target.value },- })- }- placeholder="Stirling PDF"- disabled={!loginEnabled}- />- </div>-- <div>- <Text component="div" size="sm" fw={500} mb={4}>- <Group gap="xs">- <span>- {t("admin.settings.general.logoStyle.label", "Logo Style")}- </span>- <PendingBadge show={isFieldPending("ui.logoStyle")} />- </Group>- </Text>- <Text size="xs" c="dimmed" mb="xs">- {t(- "admin.settings.general.logoStyle.description",- "Choose between the modern minimalist logo or the classic S icon",- )}- </Text>- <SegmentedControl- value={logoStyleValue}- onChange={handleLogoStyleChange}- options={[- {- value: "classic",- label: (- <div- style={{- display: "flex",- alignItems: "center",- gap: "0.5rem",- padding: "0.25rem 0",- }}- >- <img- src="classic-logo/favicon.ico"- alt={t(- "admin.settings.general.logoStyle.classicAlt",- "Classic logo",- )}- style={{ width: "24px", height: "24px" }}- />- <span>- {t(- "admin.settings.general.logoStyle.classic",- "Classic",- )}- </span>- </div>- ),- },- {- value: "modern",- label: (- <div- style={{- display: "flex",- alignItems: "center",- gap: "0.5rem",- padding: "0.25rem 0",- }}- >- <img- src="modern-logo/StirlingPDFLogoNoTextLight.svg"- alt={t(- "admin.settings.general.logoStyle.modernAlt",- "Modern logo",- )}- style={{ width: "24px", height: "24px" }}- />- <span>- {t(- "admin.settings.general.logoStyle.modern",- "Modern",- )}- </span>- </div>- ),- },- ]}- />- </div>-- <div>- <MultiSelect- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.languages.label",- "Available Languages",- )}- </span>- <PendingBadge show={isFieldPending("ui.languages")} />- </Group>- }- description={t(- "admin.settings.general.languages.description",- "Limit which languages are available (empty = all languages)",- )}- value={selectedLanguages}- onChange={(value) =>- setSettings({- ...settings,- ui: { ...settings.ui, languages: value },- })- }- data={languageOptions}- searchable- clearable- placeholder={t(- "admin.settings.general.languages.placeholder",- "Select languages",- )}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>-- <div>- <Select- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.defaultLocale.label",- "Default Locale",- )}- </span>- <PendingBadge- show={isFieldPending("system.defaultLocale")}- />- </Group>- }- description={t(- "admin.settings.general.defaultLocale.description",- "The default language for new users (e.g., en_US, es_ES)",- )}- value={defaultLocaleValue}- onChange={(value) =>- setSettings({- ...settings,- system: { ...settings.system, defaultLocale: value || "" },- })- }- data={defaultLocaleOptions}- searchable- clearable- placeholder="en_US"- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.fileUploadLimit.label",- "File Upload Limit",- )}- </span>- <PendingBadge- show={isFieldPending("system.fileUploadLimit")}- />- </Group>- }- description={t(- "admin.settings.general.fileUploadLimit.description",- "Maximum file upload size (e.g., 100MB, 1GB)",- )}- value={settings.system?.fileUploadLimit || ""}- onChange={(e) =>- setSettings({- ...settings,- system: {- ...settings.system,- fileUploadLimit: e.target.value,- },- })- }- placeholder="100MB"- disabled={!loginEnabled}- />- </div>-- <div id="frontendUrl">- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.frontendUrl.label",- "Frontend URL",- )}- </span>- <PendingBadge show={isFieldPending("system.frontendUrl")} />- </Group>- }- description={t(- "admin.settings.general.frontendUrl.description",- "Base URL for frontend (e.g., https://pdf.example.com). Used for email invite links and mobile QR code uploads. Leave empty to use backend URL.",- )}- value={settings.system?.frontendUrl || ""}- onChange={(e) =>- setSettings({- ...settings,- system: { ...settings.system, frontendUrl: e.target.value },- })- }- placeholder="https://pdf.example.com"- disabled={!loginEnabled}- />- </div>-- {/* Hide Disabled Tools Settings */}- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- marginBottom: "1rem",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.general.hideDisabledTools.googleDrive.label",- "Hide Google Drive",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.general.hideDisabledTools.googleDrive.description",- "Hide Google Drive button when not enabled",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.ui?.hideDisabledTools?.googleDrive || false}- onChange={(e) =>- setSettings({- ...settings,- ui: {- ...settings.ui,- hideDisabledTools: {- ...settings.ui?.hideDisabledTools,- googleDrive: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("ui.hideDisabledTools.googleDrive")}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.general.hideDisabledTools.mobileScanner.label",- "Hide Mobile Scanner",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.general.hideDisabledTools.mobileScanner.description",- "Hide mobile QR scanner button when not enabled",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={- settings.ui?.hideDisabledTools?.mobileQRScanner || false- }- onChange={(e) =>- setSettings({- ...settings,- ui: {- ...settings.ui,- hideDisabledTools: {- ...settings.ui?.hideDisabledTools,- mobileQRScanner: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("ui.hideDisabledTools.mobileQRScanner")}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.general.showUpdate.label",- "Show Update Notifications",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.general.showUpdate.description",- "Display notifications when a new version is available",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.system?.showUpdate || false}- onChange={(e) =>- setSettings({- ...settings,- system: {- ...settings.system,- showUpdate: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("system.showUpdate")} />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.general.showUpdateOnlyAdmin.label",- "Show Updates to Admins Only",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.general.showUpdateOnlyAdmin.description",- "Restrict update notifications to admin users only",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.system?.showUpdateOnlyAdmin || false}- onChange={(e) =>- setSettings({- ...settings,- system: {- ...settings.system,- showUpdateOnlyAdmin: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("system.showUpdateOnlyAdmin")}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.general.customHTMLFiles.label",- "Custom HTML Files",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.general.customHTMLFiles.description",- "Allow serving custom HTML files from the customFiles directory",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.system?.customHTMLFiles || false}- onChange={(e) =>- setSettings({- ...settings,- system: {- ...settings.system,- customHTMLFiles: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("system.customHTMLFiles")} />- </Group>- </div>- </Stack>- </Paper>-- {/* Custom Metadata - Premium Feature */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.general.customMetadata.label",- "Custom Metadata",- )}- </Text>- <Badge- color="grape"- size="sm"- style={{ cursor: "pointer" }}- onClick={() => navigate("/settings/adminPlan")}- title={t(- "admin.settings.badge.clickToUpgrade",- "Click to view plan details",- )}- >- PRO- </Badge>- </Group>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.general.customMetadata.autoUpdate.label",- "Auto Update Metadata",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.general.customMetadata.autoUpdate.description",- "Automatically update PDF metadata on all processed documents",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.customMetadata?.autoUpdateMetadata || false}- onChange={(e) =>- setSettings({- ...settings,- customMetadata: {- ...settings.customMetadata,- autoUpdateMetadata: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("customMetadata.autoUpdateMetadata")}- />- </Group>- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customMetadata.author.label",- "Default Author",- )}- </span>- <PendingBadge- show={isFieldPending("customMetadata.author")}- />- </Group>- }- description={t(- "admin.settings.general.customMetadata.author.description",- "Default author for PDF metadata (e.g., username)",- )}- value={settings.customMetadata?.author || ""}- onChange={(e) =>- setSettings({- ...settings,- customMetadata: {- ...settings.customMetadata,- author: e.target.value,- },- })- }- placeholder="username"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customMetadata.creator.label",- "Default Creator",- )}- </span>- <PendingBadge- show={isFieldPending("customMetadata.creator")}- />- </Group>- }- description={t(- "admin.settings.general.customMetadata.creator.description",- "Default creator for PDF metadata",- )}- value={settings.customMetadata?.creator || ""}- onChange={(e) =>- setSettings({- ...settings,- customMetadata: {- ...settings.customMetadata,- creator: e.target.value,- },- })- }- placeholder="Stirling-PDF"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customMetadata.producer.label",- "Default Producer",- )}- </span>- <PendingBadge- show={isFieldPending("customMetadata.producer")}- />- </Group>- }- description={t(- "admin.settings.general.customMetadata.producer.description",- "Default producer for PDF metadata",- )}- value={settings.customMetadata?.producer || ""}- onChange={(e) =>- setSettings({- ...settings,- customMetadata: {- ...settings.customMetadata,- producer: e.target.value,- },- })- }- placeholder="Stirling-PDF"- disabled={!loginEnabled}- />- </div>- </Stack>- </Paper>-- {/* Custom Paths */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.general.customPaths.label", "Custom Paths")}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.general.customPaths.description",- "Configure custom file system paths for pipeline processing and external tools",- )}- </Text>- </div>-- <Text fw={500} size="sm" mt="xs">- {t(- "admin.settings.general.customPaths.pipeline.label",- "Pipeline Directories",- )}- </Text>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customPaths.pipeline.pipelineDir.label",- "Pipeline Directory",- )}- </span>- <PendingBadge- show={isFieldPending("customPaths.pipeline.pipelineDir")}- />- </Group>- }- description={t(- "admin.settings.general.customPaths.pipeline.pipelineDir.description",- "Base directory for pipeline resources (leave empty for default: /pipeline)",- )}- value={settings.customPaths?.pipeline?.pipelineDir || ""}- onChange={(e) =>- setSettings({- ...settings,- customPaths: {- ...settings.customPaths,- pipeline: {- ...settings.customPaths?.pipeline,- pipelineDir: e.target.value,- },- },- })- }- placeholder="/pipeline"- disabled={!loginEnabled}- />- </div>-- <div>- <Textarea- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customPaths.pipeline.watchedFoldersDirs.label",- "Watched Folders Directories",- )}- </span>- <PendingBadge- show={- isFieldPending(- "customPaths.pipeline.watchedFoldersDirs",- ) ||- isFieldPending("customPaths.pipeline.watchedFoldersDir")- }- />- </Group>- }- description={t(- "admin.settings.general.customPaths.pipeline.watchedFoldersDirs.description",- "Directories where pipeline monitors for incoming PDFs (one per line or comma-separated; leave empty for default: /pipeline/watchedFolders)",- )}- value={watchedFoldersInput}- onChange={(e) => {- const parsedDirs = parseWatchedFoldersInput(e.target.value);- setSettings({- ...settings,- customPaths: {- ...settings.customPaths,- pipeline: {- ...settings.customPaths?.pipeline,- watchedFoldersDir: parsedDirs[0] || "",- watchedFoldersDirs: parsedDirs,- },- },- });- }}- placeholder="/pipeline/watchedFolders"- minRows={3}- autosize- disabled={!loginEnabled}- />- {watchedFoldersValidation && (- <Stack gap="xs" mt="xs">- {watchedFoldersValidation.map((warning, idx) => (- <Text- key={idx}- size="sm"- c={warning.includes("CRITICAL") ? "red" : "yellow"}- >- {warning}- </Text>- ))}- </Stack>- )}- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customPaths.pipeline.finishedFoldersDir.label",- "Finished Folders Directory",- )}- </span>- <PendingBadge- show={isFieldPending(- "customPaths.pipeline.finishedFoldersDir",- )}- />- </Group>- }- description={t(- "admin.settings.general.customPaths.pipeline.finishedFoldersDir.description",- "Directory where processed PDFs are outputted (leave empty for default: /pipeline/finishedFolders)",- )}- value={settings.customPaths?.pipeline?.finishedFoldersDir || ""}- onChange={(e) =>- setSettings({- ...settings,- customPaths: {- ...settings.customPaths,- pipeline: {- ...settings.customPaths?.pipeline,- finishedFoldersDir: e.target.value,- },- },- })- }- placeholder="/pipeline/finishedFolders"- disabled={!loginEnabled}- />- </div>-- <Text fw={500} size="sm" mt="md">- {t(- "admin.settings.general.customPaths.operations.label",- "External Tool Paths",- )}- </Text>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customPaths.operations.weasyprint.label",- "WeasyPrint Executable",- )}- </span>- <PendingBadge- show={isFieldPending("customPaths.operations.weasyprint")}- />- </Group>- }- description={t(- "admin.settings.general.customPaths.operations.weasyprint.description",- "Path to WeasyPrint executable for HTML to PDF conversion (leave empty for default: /opt/venv/bin/weasyprint)",- )}- value={settings.customPaths?.operations?.weasyprint || ""}- onChange={(e) =>- setSettings({- ...settings,- customPaths: {- ...settings.customPaths,- operations: {- ...settings.customPaths?.operations,- weasyprint: e.target.value,- },- },- })- }- placeholder="/opt/venv/bin/weasyprint"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.general.customPaths.operations.unoconvert.label",- "Unoconvert Executable",- )}- </span>- <PendingBadge- show={isFieldPending("customPaths.operations.unoconvert")}- />- </Group>- }- description={t(- "admin.settings.general.customPaths.operations.unoconvert.description",- "Path to LibreOffice unoconvert for document conversions (leave empty for default: /opt/venv/bin/unoconvert)",- )}- value={settings.customPaths?.operations?.unoconvert || ""}- onChange={(e) =>- setSettings({- ...settings,- customPaths: {- ...settings.customPaths,- operations: {- ...settings.customPaths?.operations,- unoconvert: e.target.value,- },- },- })- }- placeholder="/opt/venv/bin/unoconvert"- disabled={!loginEnabled}- />- </div>- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminLegalSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminLegalSection.tsxdeleted file mode 100644index 4598e4a3d0..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminLegalSection.tsx+++ /dev/null@@ -1,370 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import {- TextInput,- Stack,- Paper,- Text,- Loader,- Group,- Alert,- Switch,- Divider,-} from "@mantine/core";-import WarningIcon from "@mui/icons-material/Warning";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import LoginAgreementEditor from "@app/components/shared/config/configSections/LoginAgreementEditor";--interface LegalSettingsData {- termsAndConditions?: string;- privacyPolicy?: string;- accessibilityStatement?: string;- cookiePolicy?: string;- impressum?: string;- loginAgreement?: {- enabled?: boolean;- showInAnonymousMode?: boolean;- fallbackText?: string;- };-}--export default function AdminLegalSection() {- const { t } = useTranslation();- const { loginEnabled, validateLoginEnabled } = useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<LegalSettingsData>({- sectionName: "legal",- enabled: loginEnabled,- // The flat legal URL fields save through the section endpoint as before; the nested- // loginAgreement object is flattened to dotted keys sent via the global settings endpoint- // (updateSettingsTransactional), which merges into the existing node. Saving a partial- // nested object through the section endpoint would replace the whole loginAgreement node- // and drop the sibling keys the UI didn't touch (e.g. fallbackText). fallbackText is not- // edited here, so it is deliberately omitted and left untouched.- saveTransformer: (current: LegalSettingsData) => {- const { loginAgreement, ...flat } = current;- const deltaSettings: Record<string, unknown> = {};- if (loginAgreement) {- deltaSettings["legal.loginAgreement.enabled"] =- loginAgreement.enabled ?? false;- deltaSettings["legal.loginAgreement.showInAnonymousMode"] =- loginAgreement.showInAnonymousMode ?? true;- }- return { sectionData: flat, deltaSettings };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }- try {- markSaved();- await saveSettings();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- const actualLoading = loginEnabled ? loading : false;-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Text fw={600} size="lg">- {t("admin.settings.legal.title", "Legal Documents")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.legal.description",- "Configure links to legal documents and policies.",- )}- </Text>- </div>-- {/* Legal Disclaimer */}- <Alert- icon={<WarningIcon style={{ fontSize: 18 }} />}- title={t(- "admin.settings.legal.disclaimer.title",- "Legal Responsibility Warning",- )}- color="yellow"- variant="light"- >- <Text size="sm">- {t(- "admin.settings.legal.disclaimer.message",- "By customizing these legal documents, you assume full responsibility for ensuring compliance with all applicable laws and regulations, including but not limited to GDPR and other EU data protection requirements. Only modify these settings if: (1) you are operating a personal/private instance, (2) you are outside EU jurisdiction and understand your local legal obligations, or (3) you have obtained proper legal counsel and accept sole responsibility for all user data and legal compliance. Stirling-PDF and its developers assume no liability for your legal obligations.",- )}- </Text>- </Alert>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.legal.termsAndConditions.label",- "Terms and Conditions",- )}- </span>- <PendingBadge show={isFieldPending("termsAndConditions")} />- </Group>- }- description={t(- "admin.settings.legal.termsAndConditions.description",- "URL or filename to terms and conditions",- )}- value={settings.termsAndConditions || ""}- onChange={(e) =>- setSettings({- ...settings,- termsAndConditions: e.target.value,- })- }- placeholder="https://example.com/terms"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.legal.privacyPolicy.label",- "Privacy Policy",- )}- </span>- <PendingBadge show={isFieldPending("privacyPolicy")} />- </Group>- }- description={t(- "admin.settings.legal.privacyPolicy.description",- "URL or filename to privacy policy",- )}- value={settings.privacyPolicy || ""}- onChange={(e) =>- setSettings({ ...settings, privacyPolicy: e.target.value })- }- placeholder="https://example.com/privacy"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.legal.accessibilityStatement.label",- "Accessibility Statement",- )}- </span>- <PendingBadge- show={isFieldPending("accessibilityStatement")}- />- </Group>- }- description={t(- "admin.settings.legal.accessibilityStatement.description",- "URL or filename to accessibility statement",- )}- value={settings.accessibilityStatement || ""}- onChange={(e) =>- setSettings({- ...settings,- accessibilityStatement: e.target.value,- })- }- placeholder="https://example.com/accessibility"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.legal.cookiePolicy.label",- "Cookie Policy",- )}- </span>- <PendingBadge show={isFieldPending("cookiePolicy")} />- </Group>- }- description={t(- "admin.settings.legal.cookiePolicy.description",- "URL or filename to cookie policy",- )}- value={settings.cookiePolicy || ""}- onChange={(e) =>- setSettings({ ...settings, cookiePolicy: e.target.value })- }- placeholder="https://example.com/cookies"- disabled={!loginEnabled}- />- </div>-- <div>- <TextInput- label={- <Group gap="xs">- <span>- {t("admin.settings.legal.impressum.label", "Impressum")}- </span>- <PendingBadge show={isFieldPending("impressum")} />- </Group>- }- description={t(- "admin.settings.legal.impressum.description",- "URL or filename to impressum (required in some jurisdictions)",- )}- value={settings.impressum || ""}- onChange={(e) =>- setSettings({ ...settings, impressum: e.target.value })- }- placeholder="https://example.com/impressum"- disabled={!loginEnabled}- />- </div>- </Stack>- </Paper>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Text fw={600}>- {t(- "admin.settings.legal.loginAgreement.title",- "Login Agreement",- )}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.legal.loginAgreement.description",- "Show a disclaimer users must accept after logging in. The text follows each user's language.",- )}- </Text>- </div>-- <Switch- label={t(- "admin.settings.legal.loginAgreement.enabled.label",- "Enable login agreement",- )}- checked={settings.loginAgreement?.enabled ?? false}- onChange={(e) =>- setSettings({- ...settings,- loginAgreement: {- ...settings.loginAgreement,- enabled: e.currentTarget.checked,- },- })- }- disabled={!loginEnabled}- />-- <Switch- label={t(- "admin.settings.legal.loginAgreement.anonymous.label",- "Show in anonymous (no-login) mode",- )}- checked={settings.loginAgreement?.showInAnonymousMode ?? true}- onChange={(e) =>- setSettings({- ...settings,- loginAgreement: {- ...settings.loginAgreement,- showInAnonymousMode: e.currentTarget.checked,- },- })- }- disabled={!loginEnabled}- />-- <Text size="xs" c="dimmed">- {t(- "admin.settings.legal.loginAgreement.restartNote",- "Enabling or disabling the agreement applies after a restart, like other settings. Text edits below apply immediately.",- )}- </Text>-- <Divider />-- <LoginAgreementEditor disabled={!loginEnabled} />- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMailSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMailSection.tsxindex 663d5c9dbb..c3cdabdbdf 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMailSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMailSection.tsx@@ -1,4 +1,5 @@import { useCallback } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";import { useTranslation } from "react-i18next";import { useNavigate } from "react-router-dom";import {@@ -129,13 +130,13 @@ export default function AdminMailSection() {<Group justify="space-between" align="flex-start" wrap="nowrap"><div><Text fw={500} size="sm">- {t("admin.settings.mail.enabled.label", "Enable Mail")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.mail.enabled.description",- "Enable email notifications and SMTP functionality",- )}+ {t("admin.settings.mail.enabled.label", "Enable Mail")}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.mail.enabled.description",+ "Enable email notifications and SMTP functionality",+ )}+ /></Text></div><Group gap="xs">@@ -155,13 +156,13 @@ export default function AdminMailSection() {{t("admin.settings.mail.enableInvites.label","Enable Email Invites",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.mail.enableInvites.description",- "Allow admins to invite users via email with auto-generated passwords",- )}+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.mail.enableInvites.description",+ "Allow admins to invite users via email with auto-generated passwords",+ )}+ /></Text><Text size="xs" c="var(--color-amber-dark)" mt={8} fw={500}>{t(@@ -207,12 +208,14 @@ export default function AdminMailSection() {{t("admin.settings.mail.host.label", "SMTP Host")}</span><PendingBadge show={isFieldPending("host")} />+ <InfoTooltip+ label={t(+ "admin.settings.mail.host.description",+ "SMTP server hostname",+ )}+ /></Group>}- description={t(- "admin.settings.mail.host.description",- "SMTP server hostname",- )}value={settings.host || ""}onChange={(e) =>setSettings({ ...settings, host: e.target.value })@@ -229,12 +232,14 @@ export default function AdminMailSection() {{t("admin.settings.mail.port.label", "SMTP Port")}</span><PendingBadge show={isFieldPending("port")} />+ <InfoTooltip+ label={t(+ "admin.settings.mail.port.description",+ "SMTP server port (typically 587 for TLS, 465 for SSL)",+ )}+ /></Group>}- description={t(- "admin.settings.mail.port.description",- "SMTP server port (typically 587 for TLS, 465 for SSL)",- )}value={settings.port || 587}onChange={(value) =>setSettings({ ...settings, port: Number(value) })@@ -252,12 +257,14 @@ export default function AdminMailSection() {{t("admin.settings.mail.username.label", "SMTP Username")}</span><PendingBadge show={isFieldPending("username")} />+ <InfoTooltip+ label={t(+ "admin.settings.mail.username.description",+ "SMTP authentication username",+ )}+ /></Group>}- description={t(- "admin.settings.mail.username.description",- "SMTP authentication username",- )}value={settings.username || ""}onChange={(e) =>setSettings({ ...settings, username: e.target.value })@@ -296,12 +303,14 @@ export default function AdminMailSection() {{t("admin.settings.mail.from.label", "From Address")}</span><PendingBadge show={isFieldPending("from")} />+ <InfoTooltip+ label={t(+ "admin.settings.mail.from.description",+ "Email address to use as sender",+ )}+ /></Group>}- description={t(- "admin.settings.mail.from.description",- "Email address to use as sender",- )}value={settings.from || ""}onChange={(e) =>setSettings({ ...settings, from: e.target.value })diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMcpSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMcpSection.tsxdeleted file mode 100644index 5567b136b5..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminMcpSection.tsx+++ /dev/null@@ -1,579 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import {- TextInput,- Textarea,- Switch,- Select,- Stack,- Paper,- Text,- Loader,- Group,- Alert,- Code,- List,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import LocalIcon from "@app/components/shared/LocalIcon";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";--interface McpAuthData {- mode?: string;- issuerUri?: string;- jwksUri?: string;- resourceId?: string;- acceptedAudiences?: string[];- usernameClaim?: string;- requireExistingAccount?: boolean;-}--interface McpSettingsData {- enabled?: boolean;- scopesEnabled?: boolean;- allowedOperations?: string[];- blockedOperations?: string[];- auth?: McpAuthData;-}--/** Parse a comma/space/newline separated list into a string[]. */-function parseOpList(raw: string): string[] {- return raw- .split(/[\s,]+/)- .map((s) => s.trim())- .filter(Boolean);-}--interface ApiResponseWithPending<T> {- _pending?: Partial<T>;-}--type McpApiResponse = McpSettingsData & ApiResponseWithPending<McpSettingsData>;--export default function AdminMcpSection() {- const { t } = useTranslation();- const { loginEnabled } = useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<McpSettingsData>({- sectionName: "mcp",- fetchTransformer: async (): Promise<- McpSettingsData & { _pending?: Partial<McpSettingsData> }- > => {- const response = await apiClient.get<McpApiResponse>(- "/api/v1/admin/settings/section/mcp",- );- return response.data || {};- },- // Save nested auth.* keys as dot-notation through the root endpoint so siblings are preserved.- saveTransformer: (s: McpSettingsData) => ({- sectionData: {},- deltaSettings: {- "mcp.enabled": s.enabled ?? false,- "mcp.scopesEnabled": s.scopesEnabled ?? true,- "mcp.allowedOperations": s.allowedOperations ?? [],- "mcp.blockedOperations": s.blockedOperations ?? [],- "mcp.auth.mode": s.auth?.mode ?? "oauth",- "mcp.auth.issuerUri": s.auth?.issuerUri ?? "",- "mcp.auth.jwksUri": s.auth?.jwksUri ?? "",- "mcp.auth.resourceId": s.auth?.resourceId ?? "",- "mcp.auth.acceptedAudiences": s.auth?.acceptedAudiences ?? [],- "mcp.auth.usernameClaim": s.auth?.usernameClaim ?? "sub",- "mcp.auth.requireExistingAccount":- s.auth?.requireExistingAccount ?? true,- },- }),- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleSave = async () => {- try {- await saveSettings();- markSaved();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- setSettings(resetToSnapshot());- }, [resetToSnapshot, setSettings]);-- const setAuth = (patch: Partial<McpAuthData>) =>- setSettings({ ...settings, auth: { ...(settings.auth || {}), ...patch } });-- if (loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- const baseUrl =- typeof window !== "undefined"- ? window.location.origin- : "https://your-host";- const mcpUrl = `${baseUrl}/mcp`;- const metadataUrl = `${baseUrl}/.well-known/oauth-protected-resource`;- const authMode = settings.auth?.mode || "oauth";-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <div>- <Text fw={600} size="lg">- {t("admin.settings.mcp.title", "MCP Server")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.mcp.description",- "Expose Stirling's PDF tools and AI agents to MCP clients over an OAuth-protected endpoint.",- )}- </Text>- </div>-- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Text fw={500} size="sm">- {t("admin.settings.mcp.enabled.label", "Enable MCP Server")}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.mcp.enabled.description",- "When off (default), no /mcp endpoint, metadata, or MCP beans are loaded.",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.enabled || false}- onChange={(e) =>- setSettings({ ...settings, enabled: e.target.checked })- }- />- <PendingBadge show={isFieldPending("enabled")} />- </Group>- </Group>-- <Select- label={- <Group gap="xs">- <span>- {t("admin.settings.mcp.mode.label", "Authentication mode")}- </span>- <PendingBadge show={isFieldPending("auth.mode")} />- </Group>- }- description={t(- "admin.settings.mcp.mode.description",- "OAuth needs an external IdP. API key uses a Stirling per-user API key (X-API-KEY) - simplest for self-host.",- )}- data={[- { value: "oauth", label: "OAuth 2.1 (external IdP)" },- { value: "apikey", label: "API key (Stirling per-user key)" },- ]}- value={authMode}- onChange={(v) => setAuth({ mode: v || "oauth" })}- allowDeselect={false}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!settings.enabled}- />-- {authMode === "apikey" && (- <Alert variant="light" color="gray">- <Text size="xs">- {t(- "admin.settings.mcp.apikeyNote",- "Clients send a Stirling API key in the X-API-KEY header (or Authorization: Bearer <key>). The key maps to its owning Stirling user - only provisioned accounts get in, and actions are audited as that user. Manage keys under Account → API Keys.",- )}- </Text>- </Alert>- )}-- {authMode === "oauth" && (- <>- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.mcp.issuerUri.label",- "OAuth Issuer URL",- )}- </span>- <PendingBadge show={isFieldPending("auth.issuerUri")} />- </Group>- }- description={t(- "admin.settings.mcp.issuerUri.description",- "Your OAuth2 authorization server (must publish /.well-known/openid-configuration). Required when enabled.",- )}- value={settings.auth?.issuerUri || ""}- onChange={(e) => setAuth({ issuerUri: e.target.value })}- placeholder="https://auth.example.com"- disabled={!settings.enabled}- />-- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.mcp.resourceId.label",- "Resource ID",- )}- </span>- <PendingBadge show={isFieldPending("auth.resourceId")} />- </Group>- }- description={t(- "admin.settings.mcp.resourceId.description",- "This server's public /mcp URL. Tokens must list it in their audience (RFC 8707) or they are rejected.",- )}- value={settings.auth?.resourceId || ""}- onChange={(e) => setAuth({ resourceId: e.target.value })}- placeholder={mcpUrl}- disabled={!settings.enabled}- />-- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.mcp.acceptedAudiences.label",- "Additional accepted audiences (optional)",- )}- </span>- <PendingBadge- show={isFieldPending("auth.acceptedAudiences")}- />- </Group>- }- description={t(- "admin.settings.mcp.acceptedAudiences.description",- "Extra token audience values accepted besides the Resource ID (comma or space separated). Leave blank for strict RFC 8707. Needed for IdPs that cannot mint resource audiences - e.g. Supabase's OAuth server always issues aud=authenticated.",- )}- value={(settings.auth?.acceptedAudiences || []).join(" ")}- onChange={(e) =>- setAuth({ acceptedAudiences: parseOpList(e.target.value) })- }- placeholder="authenticated"- disabled={!settings.enabled}- />-- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.mcp.jwksUri.label",- "JWKS URL (optional)",- )}- </span>- <PendingBadge show={isFieldPending("auth.jwksUri")} />- </Group>- }- description={t(- "admin.settings.mcp.jwksUri.description",- "Leave blank to discover it from the issuer. Set only if your IdP serves keys at a non-standard URL.",- )}- value={settings.auth?.jwksUri || ""}- onChange={(e) => setAuth({ jwksUri: e.target.value })}- placeholder={t(- "admin.settings.mcp.jwksUri.placeholder",- "Auto-discovered from issuer",- )}- disabled={!settings.enabled}- />-- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Text fw={500} size="sm">- {t(- "admin.settings.mcp.scopes.label",- "Enforce OAuth scopes",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.mcp.scopes.description",- "Require mcp.tools.read for read ops and mcp.tools.write for write/AI ops.",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.scopesEnabled ?? true}- onChange={(e) =>- setSettings({- ...settings,- scopesEnabled: e.target.checked,- })- }- disabled={!settings.enabled}- />- <PendingBadge show={isFieldPending("scopesEnabled")} />- </Group>- </Group>-- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Text fw={500} size="sm">- {t(- "admin.settings.mcp.requireAccount.label",- "Require an existing Stirling account",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.mcp.requireAccount.description",- "Only let tokens through if their subject maps to a provisioned, enabled Stirling user.",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.auth?.requireExistingAccount ?? true}- onChange={(e) =>- setAuth({ requireExistingAccount: e.target.checked })- }- disabled={!settings.enabled}- />- <PendingBadge- show={isFieldPending("auth.requireExistingAccount")}- />- </Group>- </Group>-- <TextInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.mcp.usernameClaim.label",- "Username claim",- )}- </span>- <PendingBadge- show={isFieldPending("auth.usernameClaim")}- />- </Group>- }- description={t(- "admin.settings.mcp.usernameClaim.description",- "JWT claim matched against a Stirling username (e.g. sub, email, preferred_username).",- )}- value={settings.auth?.usernameClaim || ""}- onChange={(e) => setAuth({ usernameClaim: e.target.value })}- placeholder="sub"- disabled={!settings.enabled}- />- </>- )}-- <Textarea- label={- <Group gap="xs">- <span>- {t("admin.settings.mcp.allowedOps.label", "Allowed tools")}- </span>- <PendingBadge show={isFieldPending("allowedOperations")} />- </Group>- }- description={t(- "admin.settings.mcp.allowedOps.description",- "If set, ONLY these operation ids are exposed (an allow-list; comma or space separated). Leave blank to expose all enabled tools except any blocked below.",- )}- value={(settings.allowedOperations || []).join(" ")}- onChange={(e) =>- setSettings({- ...settings,- allowedOperations: parseOpList(e.target.value),- })- }- placeholder="merge-pdfs split-pdf rotate-pdf"- autosize- minRows={1}- maxRows={3}- disabled={!settings.enabled}- />-- <Textarea- label={- <Group gap="xs">- <span>- {t("admin.settings.mcp.blockedOps.label", "Blocked tools")}- </span>- <PendingBadge show={isFieldPending("blockedOperations")} />- </Group>- }- description={t(- "admin.settings.mcp.blockedOps.description",- "Operation ids to hide from MCP (comma or space separated), e.g. add-password remove-password. Leave blank to expose all enabled tools.",- )}- value={(settings.blockedOperations || []).join(" ")}- onChange={(e) =>- setSettings({- ...settings,- blockedOperations: parseOpList(e.target.value),- })- }- placeholder="add-password sanitize-pdf"- autosize- minRows={1}- maxRows={3}- disabled={!settings.enabled}- />- </Stack>- </Paper>-- {/* Compact in-page setup guide */}- <Alert- variant="light"- color="blue"- title={t("admin.settings.mcp.guide.title", "Connect an MCP client")}- icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}- >- <Stack gap={6}>- <List size="xs" type="ordered" spacing={4}>- {authMode === "oauth" ? (- <>- <List.Item>- {t(- "admin.settings.mcp.guide.step1",- "Enter your OAuth issuer + resource ID above, Save, and restart.",- )}- </List.Item>- <List.Item>- {t(- "admin.settings.mcp.guide.step2",- "In your MCP client add a",- )}{" "}- <b>streamable-HTTP</b>{" "}- {t(- "admin.settings.mcp.guide.step2b",- "server pointing at:",- )}{" "}- <Code>{mcpUrl}</Code>- </List.Item>- <List.Item>- {t(- "admin.settings.mcp.guide.step3",- "The client auto-discovers OAuth from:",- )}{" "}- <Code>{metadataUrl}</Code>- </List.Item>- <List.Item>- {t(- "admin.settings.mcp.guide.step4",- "Approve the sign-in; the client retries with a token. Tools appear grouped: convert, pages, misc, security, ai.",- )}- </List.Item>- </>- ) : (- <>- <List.Item>- {t(- "admin.settings.mcp.guide.step1ApiKey",- "Create an API key under Account → API Keys (each user uses their own).",- )}- </List.Item>- <List.Item>- {t(- "admin.settings.mcp.guide.step2",- "In your MCP client add a",- )}{" "}- <b>streamable-HTTP</b>{" "}- {t(- "admin.settings.mcp.guide.step2b",- "server pointing at:",- )}{" "}- <Code>{mcpUrl}</Code>- </List.Item>- <List.Item>- {t(- "admin.settings.mcp.guide.step3ApiKey",- "Send the key in an",- )}{" "}- <Code>X-API-KEY</Code>{" "}- {t(- "admin.settings.mcp.guide.step3ApiKeyb",- "header (or Authorization: Bearer <key>). No OAuth or metadata discovery is used.",- )}- </List.Item>- <List.Item>- {t(- "admin.settings.mcp.guide.step4ApiKey",- "Tools appear grouped: convert, pages, misc, security, ai - and every call is audited as the key's owner.",- )}- </List.Item>- </>- )}- </List>- <Text size="xs" c="dimmed">- {authMode === "oauth"- ? t(- "admin.settings.mcp.guide.tip",- "Tip: register the resource ID as an allowed audience in your IdP. Tested with MCP Inspector and Claude Desktop.",- )- : t(- "admin.settings.mcp.guide.tipApiKey",- "Tip: API-key mode needs no external IdP - simplest for self-host. The key maps to its owning Stirling user.",- )}- </Text>- </Stack>- </Alert>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsxindex 728486de94..911f08d024 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPlanSection.tsx@@ -1,5 +1,6 @@import React, { useState, useCallback, useEffect, useMemo } from "react";-import { Divider, Loader, Alert } from "@mantine/core";+import { SettingsEmptyState } from "@app/components/shared/config/SettingsEmptyState";+import { Divider, Loader } from "@mantine/core";import { useTranslation } from "react-i18next";import { usePlans } from "@app/hooks/usePlans";import licenseService, {@@ -19,7 +20,6 @@ import {setCachedCurrency,} from "@app/utils/currencyDetection";import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@core/components/shared/config/LoginRequiredBanner";import { isSupabaseConfigured } from "@app/services/supabaseClient";const AdminPlanSection: React.FC = () => {@@ -183,22 +183,20 @@ const AdminPlanSection: React.FC = () => {if (!plans || plans.length === 0) {return (- <Alert- color="yellow"- title={t("admin.settings.plan.noData.title", "No data available")}+ <SettingsEmptyState+ icon="star-rounded"+ title={t("admin.settings.plan.noData.title", "No plan data")}>{t("admin.settings.plan.noData.message",- "Plans data is not available at the moment.",+ "This server could not reach the licence service. Retry, or check the licence key.",)}- </Alert>+ </SettingsEmptyState>);}return (<div style={{ display: "flex", flexDirection: "column", gap: "2rem" }}>- <LoginRequiredBanner show={!loginEnabled} />-{shouldShowLicenseWarning && (<AppBannericon="warning-rounded"diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPremiumSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPremiumSection.tsxindex 2389b4bc66..cffd3f0eaf 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPremiumSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPremiumSection.tsx@@ -1,8 +1,9 @@import { useCallback } from "react";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";import { Trans, useTranslation } from "react-i18next";import {TextInput,- Switch,Stack,Paper,Text,@@ -20,7 +21,6 @@ import { useSettingsDirty } from "@app/hooks/useSettingsDirty";import PendingBadge from "@app/components/shared/config/PendingBadge";import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";interface PremiumSettingsData {key?: string;@@ -89,7 +89,6 @@ export default function AdminPremiumSection() {return (<div className="settings-section-container"><Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} /><div><Text fw={600} size="lg">{t("admin.settings.premium.title", "Premium & Enterprise")}@@ -169,12 +168,14 @@ export default function AdminPremiumSection() {{t("admin.settings.premium.key.label", "License Key")}</span><PendingBadge show={isFieldPending("key")} />+ <InfoTooltip+ label={t(+ "admin.settings.premium.key.description",+ "Enter your premium or enterprise license key",+ )}+ /></Group>}- description={t(- "admin.settings.premium.key.description",- "Enter your premium or enterprise license key",- )}value={settings.key || ""}onChange={(e) =>setSettings({ ...settings, key: e.target.value })@@ -184,40 +185,24 @@ export default function AdminPremiumSection() {/></div>- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",+ <SettingsToggleRow+ label={t(+ "admin.settings.premium.enabled.label",+ "Enable Premium Features",+ )}+ info={t(+ "admin.settings.premium.enabled.description",+ "Enable license key checks for pro/enterprise features",+ )}+ pending={isFieldPending("enabled")}+ checked={settings.enabled || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({ ...settings, enabled: checked });}}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.premium.enabled.label",- "Enable Premium Features",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.premium.enabled.description",- "Enable license key checks for pro/enterprise features",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings.enabled || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({ ...settings, enabled: e.target.checked });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("enabled")} />- </Group>- </div>+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ /></Stack></Paper></Stack>diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPrivacySection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPrivacySection.tsxdeleted file mode 100644index 14f44074db..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminPrivacySection.tsx+++ /dev/null@@ -1,300 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import { Switch, Stack, Paper, Text, Loader, Group } from "@mantine/core";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import apiClient from "@app/services/apiClient";--interface PrivacySettingsData {- enableAnalytics?: boolean;- googleVisibility?: boolean;- metricsEnabled?: boolean;-}--export default function AdminPrivacySection() {- const { t } = useTranslation();- const { loginEnabled, validateLoginEnabled, getDisabledStyles } =- useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<PrivacySettingsData>({- sectionName: "privacy",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- PrivacySettingsData & { _pending?: Record<string, unknown> }- > => {- const [metricsResponse, systemResponse] = await Promise.all([- apiClient.get("/api/v1/admin/settings/section/metrics"),- apiClient.get("/api/v1/admin/settings/section/system"),- ]);-- const metrics = metricsResponse.data;- const system = systemResponse.data;-- const result: PrivacySettingsData & {- _pending?: Record<string, unknown>;- } = {- enableAnalytics: system.enableAnalytics || false,- googleVisibility: system.googlevisibility || false,- metricsEnabled: metrics.enabled || false,- };-- // Merge pending blocks from both endpoints- const pendingBlock: Record<string, unknown> = {};- if (system._pending?.enableAnalytics !== undefined) {- pendingBlock.enableAnalytics = system._pending.enableAnalytics;- }- if (system._pending?.googlevisibility !== undefined) {- pendingBlock.googleVisibility = system._pending.googlevisibility;- }- if (metrics._pending?.enabled !== undefined) {- pendingBlock.metricsEnabled = metrics._pending.enabled;- }-- if (Object.keys(pendingBlock).length > 0) {- result._pending = pendingBlock;- }-- return result;- },- saveTransformer: (settings: PrivacySettingsData) => {- const deltaSettings = {- "system.enableAnalytics": settings.enableAnalytics,- "system.googlevisibility": settings.googleVisibility,- "metrics.enabled": settings.metricsEnabled,- };-- return {- sectionData: {},- deltaSettings,- };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }-- try {- markSaved();- await saveSettings();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- // Override loading state when login is disabled- const actualLoading = loginEnabled ? loading : false;-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />-- <div>- <Text fw={600} size="lg">- {t("admin.settings.privacy.title", "Privacy")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.privacy.description",- "Configure privacy and data collection settings.",- )}- </Text>- </div>-- {/* Analytics & Tracking */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.privacy.analytics", "Analytics & Tracking")}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.privacy.enableAnalytics.label",- "Enable Analytics",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.privacy.enableAnalytics.description",- "Collect anonymous usage analytics to help improve the application",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings?.enableAnalytics || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- enableAnalytics: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("enableAnalytics")} />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.privacy.metricsEnabled.label",- "Enable Metrics",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.privacy.metricsEnabled.description",- "Enable collection of performance and usage metrics",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings?.metricsEnabled || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- metricsEnabled: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("metricsEnabled")} />- </Group>- </div>- </Stack>- </Paper>-- {/* Search Engine Visibility */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t(- "admin.settings.privacy.searchEngine",- "Search Engine Visibility",- )}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.privacy.googleVisibility.label",- "Google Visibility",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.privacy.googleVisibility.description",- "Allow search engines to index this application",- )}- </Text>- </div>- <Group gap="xs">- <Switch- checked={settings?.googleVisibility || false}- onChange={(e) => {- if (!loginEnabled) return;- setSettings({- ...settings,- googleVisibility: e.target.checked,- });- }}- disabled={!loginEnabled}- styles={getDisabledStyles()}- />- <PendingBadge show={isFieldPending("googleVisibility")} />- </Group>- </div>- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminSecuritySection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminSecuritySection.tsxdeleted file mode 100644index fc46685c6c..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminSecuritySection.tsx+++ /dev/null@@ -1,1513 +0,0 @@-import { useCallback } from "react";-import { useNavigate } from "react-router-dom";-import { useTranslation } from "react-i18next";-import {- NumberInput,- Switch,- Stack,- Paper,- Text,- Loader,- Group,- Select,- Alert,- Badge,- Accordion,- Textarea,-} from "@mantine/core";-import { alert } from "@app/components/toast";-import LocalIcon from "@app/components/shared/LocalIcon";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";--interface SecuritySettingsData {- enableLogin?: boolean;- loginMethod?: string;- loginAttemptCount?: number;- loginResetTimeMinutes?: number;- xFrameOptions?: string;- jwt?: {- enableKeyCleanup?: boolean;- tokenExpiryMinutes?: number;- desktopTokenExpiryMinutes?: number;- allowedClockSkewSeconds?: number;- refreshGraceMinutes?: number;- secureCookie?: boolean;- };- audit?: {- enabled?: boolean;- level?: number;- retentionDays?: number;- captureFileHash?: boolean;- capturePdfAuthor?: boolean;- captureOperationResults?: boolean;- };- html?: {- urlSecurity?: {- enabled?: boolean;- level?: string;- allowedDomains?: string[];- blockedDomains?: string[];- internalTlds?: string[];- blockPrivateNetworks?: boolean;- blockLocalhost?: boolean;- blockLinkLocal?: boolean;- blockCloudMetadata?: boolean;- };- };-}--export default function AdminSecuritySection() {- const { t } = useTranslation();- const navigate = useNavigate();- const { loginEnabled, validateLoginEnabled } = useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<SecuritySettingsData>({- sectionName: "security",- enabled: loginEnabled,- fetchTransformer: async (): Promise<- SecuritySettingsData & { _pending?: Record<string, unknown> }- > => {- const [securityResponse, premiumResponse, systemResponse] =- await Promise.all([- apiClient.get("/api/v1/admin/settings/section/security"),- apiClient.get("/api/v1/admin/settings/section/premium"),- apiClient.get("/api/v1/admin/settings/section/system"),- ]);-- const securityData = securityResponse.data || {};- const premiumData = premiumResponse.data || {};- const systemData = systemResponse.data || {};-- console.log("[AdminSecuritySection] Raw backend data:");- console.log("Security:", JSON.parse(JSON.stringify(securityData)));- console.log("Premium:", JSON.parse(JSON.stringify(premiumData)));- console.log("System:", JSON.parse(JSON.stringify(systemData)));-- const { _pending: securityPending, ...securityActive } = securityData;- const { _pending: premiumPending, ...premiumActive } = premiumData;- const { _pending: systemPending, ...systemActive } = systemData;-- console.log("[AdminSecuritySection] Extracted pending blocks:", {- securityPending: JSON.parse(JSON.stringify(securityPending || {})),- premiumPending: JSON.parse(JSON.stringify(premiumPending || {})),- systemPending: JSON.parse(JSON.stringify(systemPending || {})),- });-- const combined: SecuritySettingsData & {- _pending?: Record<string, unknown>;- } = {- ...securityActive,- };-- // Only add audit if it exists (don't create defaults)- if (premiumActive.enterpriseFeatures?.audit) {- combined.audit = premiumActive.enterpriseFeatures.audit;- }-- // Only add html if it exists (don't create defaults)- if (systemActive.html) {- combined.html = systemActive.html;- }-- // Merge all _pending blocks- const mergedPending: Record<string, unknown> = {};- if (securityPending) {- Object.assign(mergedPending, securityPending);- }- if (premiumPending?.enterpriseFeatures?.audit) {- mergedPending.audit = premiumPending.enterpriseFeatures.audit;- }- if (systemPending?.html) {- mergedPending.html = systemPending.html;- }-- if (Object.keys(mergedPending).length > 0) {- combined._pending = mergedPending;- }-- return combined;- },- saveTransformer: (settings: SecuritySettingsData) => {- const { audit, html, ...securitySettings } = settings;-- const deltaSettings: Record<string, unknown> = {- // Security settings- "security.enableLogin": securitySettings.enableLogin,- "security.loginMethod": securitySettings.loginMethod,- "security.loginAttemptCount": securitySettings.loginAttemptCount,- "security.loginResetTimeMinutes":- securitySettings.loginResetTimeMinutes,- "security.xFrameOptions": securitySettings.xFrameOptions,- // JWT settings- "security.jwt.enableKeyCleanup": securitySettings.jwt?.enableKeyCleanup,- "security.jwt.tokenExpiryMinutes":- securitySettings.jwt?.tokenExpiryMinutes,- "security.jwt.desktopTokenExpiryMinutes":- securitySettings.jwt?.desktopTokenExpiryMinutes,- "security.jwt.allowedClockSkewSeconds":- securitySettings.jwt?.allowedClockSkewSeconds,- "security.jwt.refreshGraceMinutes":- securitySettings.jwt?.refreshGraceMinutes,- "security.jwt.secureCookie": securitySettings.jwt?.secureCookie,- // Premium audit settings- "premium.enterpriseFeatures.audit.enabled": audit?.enabled,- "premium.enterpriseFeatures.audit.level": audit?.level,- "premium.enterpriseFeatures.audit.retentionDays": audit?.retentionDays,- "premium.enterpriseFeatures.audit.captureFileHash":- audit?.captureFileHash,- "premium.enterpriseFeatures.audit.capturePdfAuthor":- audit?.capturePdfAuthor,- "premium.enterpriseFeatures.audit.captureOperationResults":- audit?.captureOperationResults,- };-- // System HTML settings- if (html?.urlSecurity) {- deltaSettings["system.html.urlSecurity.enabled"] =- html.urlSecurity.enabled;- deltaSettings["system.html.urlSecurity.level"] = html.urlSecurity.level;- deltaSettings["system.html.urlSecurity.allowedDomains"] =- html.urlSecurity.allowedDomains;- deltaSettings["system.html.urlSecurity.blockedDomains"] =- html.urlSecurity.blockedDomains;- deltaSettings["system.html.urlSecurity.internalTlds"] =- html.urlSecurity.internalTlds;- deltaSettings["system.html.urlSecurity.blockPrivateNetworks"] =- html.urlSecurity.blockPrivateNetworks;- deltaSettings["system.html.urlSecurity.blockLocalhost"] =- html.urlSecurity.blockLocalhost;- deltaSettings["system.html.urlSecurity.blockLinkLocal"] =- html.urlSecurity.blockLinkLocal;- deltaSettings["system.html.urlSecurity.blockCloudMetadata"] =- html.urlSecurity.blockCloudMetadata;- }-- return {- sectionData: {},- deltaSettings,- };- },- });-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- // Override loading state when login is disabled- const actualLoading = loginEnabled ? loading : false;-- const handleSave = async () => {- // Block save if login is disabled- if (!validateLoginEnabled()) {- return;- }-- try {- markSaved();- await saveSettings();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- const handleDiscard = useCallback(() => {- const original = resetToSnapshot();- setSettings(original);- }, [resetToSnapshot, setSettings]);-- if (actualLoading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <Stack gap="lg" className="settings-section-content">- <LoginRequiredBanner show={!loginEnabled} />-- <div>- <Text fw={600} size="lg">- {t("admin.settings.security.title", "Security")}- </Text>- <Text size="sm" c="dimmed">- {t(- "admin.settings.security.description",- "Configure authentication, login behaviour, and security policies.",- )}- </Text>- </div>-- {/* Authentication Settings */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.security.authentication", "Authentication")}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.enableLogin.label",- "Enable Login",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.enableLogin.description",- "Require users to log in before accessing the application",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="enableLogin"- checked={settings?.enableLogin || false}- onChange={(e) =>- setSettings({ ...settings, enableLogin: e.target.checked })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("enableLogin")} />- </Group>- </div>-- <div>- <Select- name="loginMethod"- label={t(- "admin.settings.security.loginMethod.label",- "Login Method",- )}- description={t(- "admin.settings.security.loginMethod.description",- "The authentication method to use for user login",- )}- value={settings?.loginMethod || "all"}- onChange={(value) =>- setSettings({ ...settings, loginMethod: value || "all" })- }- data={[- {- value: "all",- label: t(- "admin.settings.security.loginMethod.all",- "All Methods",- ),- },- {- value: "normal",- label: t(- "admin.settings.security.loginMethod.normal",- "Username/Password Only",- ),- },- {- value: "oauth2",- label: t(- "admin.settings.security.loginMethod.oauth2",- "OAuth2 Only",- ),- },- {- value: "saml2",- label: t(- "admin.settings.security.loginMethod.saml2",- "SAML2 Only",- ),- },- ]}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- {isFieldPending("loginMethod") && (- <Group mt="xs">- <PendingBadge show={true} />- </Group>- )}- </div>-- <div>- <NumberInput- name="loginAttemptCount"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.loginAttemptCount.label",- "Login Attempt Limit",- )}- </span>- <PendingBadge show={isFieldPending("loginAttemptCount")} />- </Group>- }- description={t(- "admin.settings.security.loginAttemptCount.description",- "Maximum number of failed login attempts before account lockout",- )}- value={settings?.loginAttemptCount || 0}- onChange={(value) =>- setSettings({ ...settings, loginAttemptCount: Number(value) })- }- min={0}- max={100}- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- name="loginResetTimeMinutes"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.loginResetTimeMinutes.label",- "Login Reset Time (minutes)",- )}- </span>- <PendingBadge- show={isFieldPending("loginResetTimeMinutes")}- />- </Group>- }- description={t(- "admin.settings.security.loginResetTimeMinutes.description",- "Time before failed login attempts are reset",- )}- value={settings?.loginResetTimeMinutes || 0}- onChange={(value) =>- setSettings({- ...settings,- loginResetTimeMinutes: Number(value),- })- }- min={0}- max={1440}- disabled={!loginEnabled}- />- </div>-- <div>- <Select- name="xFrameOptions"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.xFrameOptions.label",- "X-Frame-Options",- )}- </span>- <PendingBadge show={isFieldPending("xFrameOptions")} />- </Group>- }- description={t(- "admin.settings.security.xFrameOptions.description",- "Controls whether the application can be embedded in iframes",- )}- value={settings?.xFrameOptions || "DENY"}- onChange={(value) =>- setSettings({ ...settings, xFrameOptions: value || "DENY" })- }- data={[- {- value: "DENY",- label: t(- "admin.settings.security.xFrameOptions.deny",- "Deny (Prevents all framing)",- ),- },- {- value: "SAMEORIGIN",- label: t(- "admin.settings.security.xFrameOptions.sameorigin",- "Same Origin (Allow framing from same domain)",- ),- },- {- value: "DISABLED",- label: t(- "admin.settings.security.xFrameOptions.disabled",- "Disabled (No X-Frame-Options header)",- ),- },- ]}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>- </Stack>- </Paper>-- {/* SSO/SAML Notice */}- <Alert- variant="light"- color="blue"- title={t(- "admin.settings.security.ssoNotice.title",- "Looking for SSO/SAML settings?",- )}- icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}- >- <Text size="sm">- {t(- "admin.settings.security.ssoNotice.message",- "OAuth2 and SAML2 authentication providers have been moved to the Connections menu for easier management.",- )}- </Text>- </Alert>-- {/* JWT Settings */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Text fw={600} size="sm" mb="xs">- {t("admin.settings.security.jwt.label", "JWT Configuration")}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.jwt.enableKeyCleanup.label",- "Enable Key Cleanup",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.jwt.enableKeyCleanup.description",- "Automatically remove old JWT keys after retention period",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="jwt_enableKeyCleanup"- checked={settings?.jwt?.enableKeyCleanup || false}- onChange={(e) =>- setSettings({- ...settings,- jwt: {- ...settings?.jwt,- enableKeyCleanup: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("jwt.enableKeyCleanup")} />- </Group>- </div>-- <div>- <NumberInput- name="jwt_tokenExpiryMinutes"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.jwt.tokenExpiryMinutes.label",- "Web Token Expiry (minutes)",- )}- </span>- <PendingBadge- show={isFieldPending("jwt.tokenExpiryMinutes")}- />- </Group>- }- description={t(- "admin.settings.security.jwt.tokenExpiryMinutes.description",- "Access token lifetime in minutes for web clients (default: 1440 = 24 hours)",- )}- value={settings?.jwt?.tokenExpiryMinutes || 1440}- onChange={(value) =>- setSettings({- ...settings,- jwt: {- ...settings?.jwt,- tokenExpiryMinutes: Number(value),- },- })- }- min={1}- max={43200}- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- name="jwt_desktopTokenExpiryMinutes"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.jwt.desktopTokenExpiryMinutes.label",- "Desktop Token Expiry (minutes)",- )}- </span>- <PendingBadge- show={isFieldPending("jwt.desktopTokenExpiryMinutes")}- />- </Group>- }- description={t(- "admin.settings.security.jwt.desktopTokenExpiryMinutes.description",- "Access token lifetime in minutes for desktop clients. Desktop apps automatically detected via User-Agent and receive longer sessions for better UX (default: 43200 = 30 days)",- )}- value={settings?.jwt?.desktopTokenExpiryMinutes || 43200}- onChange={(value) =>- setSettings({- ...settings,- jwt: {- ...settings?.jwt,- desktopTokenExpiryMinutes: Number(value),- },- })- }- min={1}- max={525600}- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- name="jwt_allowedClockSkewSeconds"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.jwt.allowedClockSkewSeconds.label",- "Clock Skew Tolerance (seconds)",- )}- </span>- <PendingBadge- show={isFieldPending("jwt.allowedClockSkewSeconds")}- />- </Group>- }- description={t(- "admin.settings.security.jwt.allowedClockSkewSeconds.description",- "Tolerance for client/server time drift during token validation (default: 60 seconds)",- )}- value={settings?.jwt?.allowedClockSkewSeconds ?? 60}- onChange={(value) =>- setSettings({- ...settings,- jwt: {- ...settings?.jwt,- allowedClockSkewSeconds: Number(value),- },- })- }- min={0}- max={300}- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- name="jwt_refreshGraceMinutes"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.jwt.refreshGraceMinutes.label",- "Refresh Grace Period (minutes)",- )}- </span>- <PendingBadge- show={isFieldPending("jwt.refreshGraceMinutes")}- />- </Group>- }- description={t(- "admin.settings.security.jwt.refreshGraceMinutes.description",- "Allow token refresh within this many minutes after expiry (default: 15 minutes, max 3 attempts)",- )}- value={settings?.jwt?.refreshGraceMinutes ?? 15}- onChange={(value) =>- setSettings({- ...settings,- jwt: {- ...settings?.jwt,- refreshGraceMinutes: Number(value),- },- })- }- min={0}- max={120}- disabled={!loginEnabled}- />- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.jwt.secureCookie.label",- "Secure Cookie",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.jwt.secureCookie.description",- "Require HTTPS for JWT cookies (recommended for production)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="jwt_secureCookie"- checked={settings?.jwt?.secureCookie || false}- onChange={(e) =>- setSettings({- ...settings,- jwt: { ...settings?.jwt, secureCookie: e.target.checked },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("jwt.secureCookie")} />- </Group>- </div>- </Stack>- </Paper>-- {/* Audit Logging - Enterprise Feature */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="center">- <Text fw={600} size="sm">- {t("admin.settings.security.audit.label", "Audit Logging")}- </Text>- <Badge- color="grape"- size="sm"- style={{ cursor: "pointer" }}- onClick={() => navigate("/settings/adminPlan")}- title={t(- "admin.settings.badge.clickToUpgrade",- "Click to view plan details",- )}- >- ENTERPRISE- </Badge>- </Group>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.audit.enabled.label",- "Enable Audit Logging",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.audit.enabled.description",- "Track user actions and system events for compliance and security monitoring",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="audit_enabled"- checked={settings?.audit?.enabled || false}- onChange={(e) =>- setSettings({- ...settings,- audit: { ...settings?.audit, enabled: e.target.checked },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("audit.enabled")} />- </Group>- </div>-- <div>- <NumberInput- name="audit_level"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.audit.level.label",- "Audit Level",- )}- </span>- <PendingBadge show={isFieldPending("audit.level")} />- </Group>- }- description={t(- "admin.settings.security.audit.level.description",- "0=OFF, 1=BASIC, 2=STANDARD, 3=VERBOSE",- )}- value={settings?.audit?.level || 2}- onChange={(value) =>- setSettings({- ...settings,- audit: { ...settings?.audit, level: Number(value) },- })- }- min={0}- max={3}- disabled={!loginEnabled}- />- </div>-- <div>- <NumberInput- name="audit_retentionDays"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.audit.retentionDays.label",- "Audit Retention (days)",- )}- </span>- <PendingBadge- show={isFieldPending("audit.retentionDays")}- />- </Group>- }- description={t(- "admin.settings.security.audit.retentionDays.description",- "Number of days to retain audit logs",- )}- value={settings?.audit?.retentionDays || 90}- onChange={(value) =>- setSettings({- ...settings,- audit: { ...settings?.audit, retentionDays: Number(value) },- })- }- min={1}- max={3650}- disabled={!loginEnabled}- />- </div>-- <Alert- color="yellow"- icon={<LocalIcon icon="info" />}- title={t(- "admin.settings.security.audit.advancedOptions.title",- "Advanced Options",- )}- >- {t(- "admin.settings.security.audit.advancedOptions.description",- "The following options increase processing time and memory usage. Enable only if truly needed.",- )}- </Alert>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.audit.captureFileHash.label",- "Capture File Hash",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.audit.captureFileHash.description",- "Store MD5 hash of processed files for audit trail verification",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="audit_captureFileHash"- checked={settings?.audit?.captureFileHash || false}- onChange={(e) =>- setSettings({- ...settings,- audit: {- ...settings?.audit,- captureFileHash: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("audit.captureFileHash")} />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.audit.capturePdfAuthor.label",- "Capture PDF Author",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.audit.capturePdfAuthor.description",- "Extract author field from PDF documents during processing",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="audit_capturePdfAuthor"- checked={settings?.audit?.capturePdfAuthor || false}- onChange={(e) =>- setSettings({- ...settings,- audit: {- ...settings?.audit,- capturePdfAuthor: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge show={isFieldPending("audit.capturePdfAuthor")} />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.audit.captureOperationResults.label",- "Capture Operation Results",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.audit.captureOperationResults.description",- "Store output file information and processing results in audit logs",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="audit_captureOperationResults"- checked={settings?.audit?.captureOperationResults || false}- onChange={(e) =>- setSettings({- ...settings,- audit: {- ...settings?.audit,- captureOperationResults: e.target.checked,- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("audit.captureOperationResults")}- />- </Group>- </div>- </Stack>- </Paper>-- {/* HTML URL Security */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <div>- <Text fw={600} size="sm" mb="xs">- {t(- "admin.settings.security.htmlUrlSecurity.label",- "HTML URL Security",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "admin.settings.security.htmlUrlSecurity.description",- "Configure URL access restrictions for HTML processing to prevent SSRF attacks",- )}- </Text>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.htmlUrlSecurity.enabled.label",- "Enable URL Security",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.htmlUrlSecurity.enabled.description",- "Enable URL security restrictions for HTML to PDF conversions",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="html_urlSecurity_enabled"- checked={settings?.html?.urlSecurity?.enabled || false}- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- enabled: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending("html.urlSecurity.enabled")}- />- </Group>- </div>-- <div>- <Select- name="html_urlSecurity_level"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.htmlUrlSecurity.level.label",- "Security Level",- )}- </span>- <PendingBadge- show={isFieldPending("html.urlSecurity.level")}- />- </Group>- }- description={t(- "admin.settings.security.htmlUrlSecurity.level.description",- "MAX: whitelist only, MEDIUM: block internal networks, OFF: no restrictions",- )}- value={settings?.html?.urlSecurity?.level || "MEDIUM"}- onChange={(value) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- level: value || "MEDIUM",- },- },- })- }- data={[- {- value: "MAX",- label: t(- "admin.settings.security.htmlUrlSecurity.level.max",- "Maximum (Whitelist Only)",- ),- },- {- value: "MEDIUM",- label: t(- "admin.settings.security.htmlUrlSecurity.level.medium",- "Medium (Block Internal)",- ),- },- {- value: "OFF",- label: t(- "admin.settings.security.htmlUrlSecurity.level.off",- "Off (No Restrictions)",- ),- },- ]}- comboboxProps={{- withinPortal: true,- zIndex: Z_INDEX_OVER_CONFIG_MODAL,- }}- disabled={!loginEnabled}- />- </div>-- <Accordion variant="separated">- <Accordion.Item value="advanced">- <Accordion.Control>- {t(- "admin.settings.security.htmlUrlSecurity.advanced",- "Advanced Settings",- )}- </Accordion.Control>- <Accordion.Panel>- <Stack gap="md">- {/* Allowed Domains */}- <div>- <Textarea- name="html_urlSecurity_allowedDomains"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.htmlUrlSecurity.allowedDomains.label",- "Allowed Domains (Whitelist)",- )}- </span>- <PendingBadge- show={isFieldPending(- "html.urlSecurity.allowedDomains",- )}- />- </Group>- }- description={t(- "admin.settings.security.htmlUrlSecurity.allowedDomains.description",- "One domain per line (e.g., cdn.example.com). Only these domains allowed when level is MAX",- )}- value={- settings?.html?.urlSecurity?.allowedDomains?.join(- "\n",- ) || ""- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- allowedDomains: e.target.value- ? e.target.value- .split("\n")- .filter((d) => d.trim())- : [],- },- },- })- }- placeholder="cdn.example.com images.google.com"- minRows={3}- autosize- disabled={!loginEnabled}- />- </div>-- {/* Blocked Domains */}- <div>- <Textarea- name="html_urlSecurity_blockedDomains"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.htmlUrlSecurity.blockedDomains.label",- "Blocked Domains (Blacklist)",- )}- </span>- <PendingBadge- show={isFieldPending(- "html.urlSecurity.blockedDomains",- )}- />- </Group>- }- description={t(- "admin.settings.security.htmlUrlSecurity.blockedDomains.description",- "One domain per line (e.g., malicious.com). Additional domains to block",- )}- value={- settings?.html?.urlSecurity?.blockedDomains?.join(- "\n",- ) || ""- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- blockedDomains: e.target.value- ? e.target.value- .split("\n")- .filter((d) => d.trim())- : [],- },- },- })- }- placeholder="malicious.com evil.org"- minRows={3}- autosize- disabled={!loginEnabled}- />- </div>-- {/* Internal TLDs */}- <div>- <Textarea- name="html_urlSecurity_internalTlds"- label={- <Group component="span" gap="xs">- <span>- {t(- "admin.settings.security.htmlUrlSecurity.internalTlds.label",- "Internal TLDs",- )}- </span>- <PendingBadge- show={isFieldPending(- "html.urlSecurity.internalTlds",- )}- />- </Group>- }- description={t(- "admin.settings.security.htmlUrlSecurity.internalTlds.description",- "One TLD per line (e.g., .local, .internal). Block domains with these TLD patterns",- )}- value={- settings?.html?.urlSecurity?.internalTlds?.join(- "\n",- ) || ""- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- internalTlds: e.target.value- ? e.target.value- .split("\n")- .filter((d) => d.trim())- : [],- },- },- })- }- placeholder=".local .internal .corp .home"- minRows={3}- autosize- disabled={!loginEnabled}- />- </div>-- {/* Network Blocking Options */}- <Text fw={600} size="sm" mt="md">- {t(- "admin.settings.security.htmlUrlSecurity.networkBlocking",- "Network Blocking",- )}- </Text>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.label",- "Block Private Networks",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.description",- "Block RFC 1918 private networks (10.x.x.x, 192.168.x.x, 172.16-31.x.x)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="html_urlSecurity_blockPrivateNetworks"- checked={- settings?.html?.urlSecurity?.blockPrivateNetworks ||- false- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- blockPrivateNetworks: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending(- "html.urlSecurity.blockPrivateNetworks",- )}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.htmlUrlSecurity.blockLocalhost.label",- "Block Localhost",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.htmlUrlSecurity.blockLocalhost.description",- "Block localhost and loopback addresses (127.x.x.x, ::1)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="html_urlSecurity_blockLocalhost"- checked={- settings?.html?.urlSecurity?.blockLocalhost || false- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- blockLocalhost: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending(- "html.urlSecurity.blockLocalhost",- )}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.htmlUrlSecurity.blockLinkLocal.label",- "Block Link-Local Addresses",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.htmlUrlSecurity.blockLinkLocal.description",- "Block link-local addresses (169.254.x.x, fe80::/10)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="html_urlSecurity_blockLinkLocal"- checked={- settings?.html?.urlSecurity?.blockLinkLocal || false- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- blockLinkLocal: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending(- "html.urlSecurity.blockLinkLocal",- )}- />- </Group>- </div>-- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <Text fw={500} size="sm">- {t(- "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.label",- "Block Cloud Metadata Endpoints",- )}- </Text>- <Text size="xs" c="dimmed" mt={4}>- {t(- "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.description",- "Block cloud provider metadata endpoints (169.254.169.254)",- )}- </Text>- </div>- <Group gap="xs">- <Switch- name="html_urlSecurity_blockCloudMetadata"- checked={- settings?.html?.urlSecurity?.blockCloudMetadata ||- false- }- onChange={(e) =>- setSettings({- ...settings,- html: {- ...settings?.html,- urlSecurity: {- ...settings?.html?.urlSecurity,- blockCloudMetadata: e.target.checked,- },- },- })- }- disabled={!loginEnabled}- />- <PendingBadge- show={isFieldPending(- "html.urlSecurity.blockCloudMetadata",- )}- />- </Group>- </div>- </Stack>- </Accordion.Panel>- </Accordion.Item>- </Accordion>- </Stack>- </Paper>- </Stack>-- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />-- {/* Restart Confirmation Modal */}- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminStorageSharingSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminStorageSharingSection.tsxdeleted file mode 100644index 70b25e4813..0000000000--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminStorageSharingSection.tsx+++ /dev/null@@ -1,409 +0,0 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import {- Anchor,- Badge,- Group,- Loader,- Paper,- Stack,- Switch,- Text,-} from "@mantine/core";-import { useNavigate } from "react-router-dom";-import { alert } from "@app/components/toast";-import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";-import { useRestartServer } from "@app/components/shared/config/useRestartServer";-import { useAdminSettings } from "@app/hooks/useAdminSettings";-import PendingBadge from "@app/components/shared/config/PendingBadge";-import apiClient from "@app/services/apiClient";-import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";-import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";-import { useSettingsDirty } from "@app/hooks/useSettingsDirty";--interface StorageSharingSettingsData {- enabled?: boolean;- sharing?: {- enabled?: boolean;- linkEnabled?: boolean;- emailEnabled?: boolean;- };- signing?: {- enabled?: boolean;- };- system?: {- frontendUrl?: string;- };- mail?: {- enabled?: boolean;- };-}--export default function AdminStorageSharingSection() {- const { t } = useTranslation();- const navigate = useNavigate();- const { loginEnabled, validateLoginEnabled, getDisabledStyles } =- useLoginRequired();- const {- restartModalOpened,- showRestartModal,- closeRestartModal,- restartServer,- } = useRestartServer();-- const {- settings,- setSettings,- loading,- saving,- saveSettings,- isFieldPending,- } = useAdminSettings<StorageSharingSettingsData>({- sectionName: "storage",- enabled: loginEnabled,- fetchTransformer: async () => {- const [storageResponse, systemResponse, mailResponse] = await Promise.all(- [- apiClient.get("/api/v1/admin/settings/section/storage"),- apiClient.get("/api/v1/admin/settings/section/system"),- apiClient.get("/api/v1/admin/settings/section/mail"),- ],- );-- const storageData = storageResponse.data || {};- const systemData = systemResponse.data || {};- const mailData = mailResponse.data || {};-- return {- ...storageData,- system: { frontendUrl: systemData.frontendUrl || "" },- mail: { enabled: mailData.enabled || false },- };- },- saveTransformer: (currentSettings) => ({- sectionData: {- enabled: currentSettings.enabled,- sharing: {- enabled: currentSettings.sharing?.enabled,- linkEnabled: currentSettings.sharing?.linkEnabled,- emailEnabled: currentSettings.sharing?.emailEnabled,- },- signing: {- enabled: currentSettings.signing?.enabled,- },- },- }),- });-- const storageEnabled = settings.enabled ?? false;- const sharingEnabled = storageEnabled && (settings.sharing?.enabled ?? false);- const frontendUrlConfigured = Boolean(settings.system?.frontendUrl?.trim());- const mailEnabled = Boolean(settings.mail?.enabled);-- const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(- settings,- loading,- );-- const handleDiscard = useCallback(() => {- setSettings(resetToSnapshot());- }, [resetToSnapshot, setSettings]);-- const handleSave = async () => {- if (!validateLoginEnabled()) {- return;- }- try {- await saveSettings();- markSaved();- showRestartModal();- } catch (_error) {- alert({- alertType: "error",- title: t("admin.error", "Error"),- body: t("admin.settings.saveError", "Failed to save settings"),- });- }- };-- if (loginEnabled && loading) {- return (- <Stack align="center" justify="center" h={200}>- <Loader size="lg" />- </Stack>- );- }-- return (- <div className="settings-section-container">- <div className="settings-section-content">- <Stack gap="sm">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Group gap="xs" align="center">- <Text fw={600} size="lg">- {t("admin.settings.storage.title", "File Storage & Sharing")}- </Text>- <Badge size="sm" variant="light" color="orange">- {t("toolPanel.alpha", "Alpha")}- </Badge>- </Group>- <Text size="sm" c="dimmed">- {t(- "admin.settings.storage.description",- "Control server storage and sharing options.",- )}- </Text>- </div>-- <Paper withBorder p="sm" radius="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Group gap="xs" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.storage.enabled.label",- "Enable Server File Storage",- )}- </Text>- {isFieldPending("enabled") && <PendingBadge show={true} />}- </Group>- <Text size="xs" c="dimmed">- {t(- "admin.settings.storage.enabled.description",- "Allow users to store files on the server.",- )}- </Text>- </div>- <Switch- checked={storageEnabled}- onChange={(e) =>- setSettings({ ...settings, enabled: e.currentTarget.checked })- }- disabled={!loginEnabled}- styles={getDisabledStyles()}- style={{ flexShrink: 0 }}- />- </Group>- </Paper>-- <Paper withBorder p="sm" radius="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Group gap="xs" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.storage.sharing.enabled.label",- "Enable Sharing",- )}- </Text>- {isFieldPending("sharing.enabled") && (- <PendingBadge show={true} />- )}- </Group>- <Text size="xs" c="dimmed">- {t(- "admin.settings.storage.sharing.enabled.description",- "Allow users to share stored files.",- )}- </Text>- </div>- <Switch- checked={settings.sharing?.enabled ?? false}- onChange={(e) =>- setSettings({- ...settings,- sharing: {- ...settings.sharing,- enabled: e.currentTarget.checked,- },- })- }- disabled={!loginEnabled || !storageEnabled}- styles={getDisabledStyles()}- style={{ flexShrink: 0 }}- />- </Group>- </Paper>-- <Paper withBorder p="sm" radius="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Group gap="xs" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.storage.sharing.links.label",- "Enable Share Links",- )}- </Text>- {isFieldPending("sharing.linkEnabled") && (- <PendingBadge show={true} />- )}- </Group>- <Text size="xs" c="dimmed">- {t(- "admin.settings.storage.sharing.links.description",- "Allow sharing via signed-in links.",- )}- </Text>- {!frontendUrlConfigured && (- <Text size="xs" c="var(--color-amber-dark)">- {t(- "admin.settings.storage.sharing.links.frontendUrlNote",- "Requires a Frontend URL. ",- )}- <Anchor- href="#"- onClick={(e) => {- e.preventDefault();- navigate("/settings/adminGeneral#frontendUrl");- }}- c="var(--color-amber-dark)"- td="underline"- >- {t(- "admin.settings.storage.sharing.links.frontendUrlLink",- "Configure in System Settings",- )}- </Anchor>- </Text>- )}- </div>- <Switch- checked={settings.sharing?.linkEnabled ?? false}- onChange={(e) =>- setSettings({- ...settings,- sharing: {- ...settings.sharing,- linkEnabled: e.currentTarget.checked,- },- })- }- disabled={- !loginEnabled || !sharingEnabled || !frontendUrlConfigured- }- styles={getDisabledStyles()}- style={{ flexShrink: 0 }}- />- </Group>- </Paper>-- <Paper withBorder p="sm" radius="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Group gap="xs" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.storage.sharing.email.label",- "Enable Email Sharing",- )}- </Text>- {isFieldPending("sharing.emailEnabled") && (- <PendingBadge show={true} />- )}- </Group>- <Text size="xs" c="dimmed">- {t(- "admin.settings.storage.sharing.email.description",- "Allow sharing with email addresses.",- )}- </Text>- {!mailEnabled && (- <Text size="xs" c="var(--color-amber-dark)">- {t(- "admin.settings.storage.sharing.email.mailNote",- "Requires mail configuration. ",- )}- <Anchor- href="#"- onClick={(e) => {- e.preventDefault();- navigate("/settings/adminConnections");- }}- c="var(--color-amber-dark)"- td="underline"- >- {t(- "admin.settings.storage.sharing.email.mailLink",- "Configure Mail Settings",- )}- </Anchor>- </Text>- )}- </div>- <Switch- checked={settings.sharing?.emailEnabled ?? false}- onChange={(e) =>- setSettings({- ...settings,- sharing: {- ...settings.sharing,- emailEnabled: e.currentTarget.checked,- },- })- }- disabled={!loginEnabled || !sharingEnabled || !mailEnabled}- styles={getDisabledStyles()}- style={{ flexShrink: 0 }}- />- </Group>- </Paper>-- <Paper withBorder p="sm" radius="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Group gap="xs" align="center">- <Text fw={600} size="sm">- {t(- "admin.settings.storage.signing.enabled.label",- "Enable Group Signing",- )}- </Text>- {isFieldPending("signing.enabled") && (- <PendingBadge show={true} />- )}- </Group>- <Text size="xs" c="dimmed">- {t(- "admin.settings.storage.signing.enabled.description",- "Allow users to create multi-participant document signing sessions. Requires server file storage to be enabled.",- )}- </Text>- </div>- <Switch- checked={settings.signing?.enabled ?? false}- onChange={(e) =>- setSettings({- ...settings,- signing: {- ...settings.signing,- enabled: e.currentTarget.checked,- },- })- }- disabled={!loginEnabled || !storageEnabled}- styles={getDisabledStyles()}- style={{ flexShrink: 0 }}- />- </Group>- </Paper>-- <RestartConfirmationModal- opened={restartModalOpened}- onClose={closeRestartModal}- onRestart={restartServer}- />- </Stack>- </div>- <SettingsStickyFooter- isDirty={isDirty}- saving={saving}- loginEnabled={loginEnabled}- onSave={handleSave}- onDiscard={handleDiscard}- />- </div>- );-}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminUsageSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminUsageSection.tsxindex d0a0a1b2e9..42379f3470 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminUsageSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminUsageSection.tsx@@ -1,4 +1,5 @@import React, { useState, useEffect, useCallback } from "react";+import { SettingsEmptyState } from "@app/components/shared/config/SettingsEmptyState";import { Stack, Group, Text, Loader, Alert, Card } from "@mantine/core";import { Button } from "@app/ui/Button";import { SegmentedControl } from "@app/ui/SegmentedControl";@@ -11,7 +12,6 @@ import UsageAnalyticsChart from "@app/components/shared/config/configSections/usimport UsageAnalyticsTable from "@app/components/shared/config/configSections/usage/UsageAnalyticsTable";import LocalIcon from "@app/components/shared/LocalIcon";import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";import { useAppConfig } from "@app/contexts/AppConfigContext";import EnterpriseRequiredBanner from "@app/components/shared/config/EnterpriseRequiredBanner";@@ -229,12 +229,15 @@ const AdminUsageSection: React.FC = () => {if (!data) {return (- <Alert color="yellow" title={t("usage.noData", "No data available")}>+ <SettingsEmptyState+ icon="monitoring"+ title={t("usage.noData", "No usage yet")}+ >{t("usage.noDataMessage",- "No usage statistics are currently available.",+ "Endpoint activity appears here once people start running tools.",)}- </Alert>+ </SettingsEmptyState>);}@@ -267,7 +270,6 @@ const AdminUsageSection: React.FC = () => {return (<Stack gap="lg">- <LoginRequiredBanner show={!loginEnabled} /><EnterpriseRequiredBannershow={!hasEnterpriseLicense}featureName={t(diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/LoginAgreementEditor.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/LoginAgreementEditor.tsxindex 23b879f974..6c28b03cb4 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/LoginAgreementEditor.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/LoginAgreementEditor.tsx@@ -1,4 +1,5 @@import { useEffect, useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";import { useNavigate } from "react-router-dom";import { useTranslation } from "react-i18next";import {@@ -11,10 +12,8 @@ import {Stack,Text,Textarea,- Tooltip,} from "@mantine/core";import { Button } from "@app/ui/Button";-import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";import Markdown from "react-markdown";import remarkGfm from "remark-gfm";import apiClient from "@app/services/apiClient";@@ -167,25 +166,12 @@ export default function LoginAgreementEditor({<span>{t("admin.settings.legal.loginAgreement.language", "Language")}</span>- <Tooltip- multiline- w={300}- withArrow- withinPortal- zIndex={Z_INDEX_OVER_CONFIG_MODAL}+ <InfoTooltiplabel={t("admin.settings.legal.loginAgreement.languageHelp","Each language has its own file. If a user's language has no file, the agreement falls back to the default locale's file, then to the fallback text.",)}- >- <InfoOutlinedIcon- style={{- fontSize: 15,- cursor: "help",- color: "var(--mantine-color-dimmed)",- }}- />- </Tooltip>+ /></Group>}data={languageOptions}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/PeopleSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/PeopleSection.tsxindex 6b14d2b421..fac347d65f 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/PeopleSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/PeopleSection.tsx@@ -27,7 +27,6 @@ import { type Team } from "@app/services/teamService";import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";import InviteMembersModal from "@app/components/shared/InviteMembersModal";import { useLoginRequired } from "@app/hooks/useLoginRequired";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";import { useNavigate } from "react-router-dom";import UpdateSeatsButton from "@app/components/shared/UpdateSeatsButton";import { useLicense } from "@app/contexts/LicenseContext";@@ -402,16 +401,6 @@ User: ${user.username}`)return (<Stack gap="lg">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Text fw={600} size="lg">- {t("workspace.people.title")}- </Text>- <Text size="sm" c="dimmed">- {t("workspace.people.description")}- </Text>- </div>-{/* License Information - Compact */}{licenseInfo && (<Group gap="md" style={{ fontSize: "0.875rem" }}>diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/TeamsSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/TeamsSection.tsxindex b185ad18c5..05090221bc 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/TeamsSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/TeamsSection.tsx@@ -27,7 +27,6 @@ import {useFetchAdminUsers,useAdminMutation,} from "@app/hooks/useAdminDirectory";-import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";const EXAMPLE_TEAMS: Team[] = [{ id: 1, name: "Engineering", userCount: 3 },@@ -213,16 +212,6 @@ export default function TeamsSection() {return (<Stack gap="lg">- <LoginRequiredBanner show={!loginEnabled} />- <div>- <Text fw={600} size="lg">- {t("workspace.teams.title")}- </Text>- <Text size="sm" c="dimmed">- {t("workspace.teams.description")}- </Text>- </div>-{/* Header Actions */}<Group justify="flex-end"><Buttondiff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.css b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.cssnew file mode 100644index 0000000000..cdb2c17e02--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.css@@ -0,0 +1,21 @@+.admin-advanced__card {+ display: flex;+ flex-direction: column;+ gap: var(--space-3, 0.75rem);+}++/* Permanent, not just during the focus pulse: an anchored jump would otherwise+ land the heading under the sticky search bar. */+.admin-advanced__heading {+ margin: 0;+ scroll-margin-top: 1rem;+ font-size: 0.9375rem;+ font-weight: var(--font-weight-semibold, 600);+ color: var(--c-text);+}++.admin-advanced__description {+ margin: -0.35rem 0 0;+ font-size: 0.8125rem;+ color: var(--c-text-subtle);+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsxnew file mode 100644index 0000000000..51f8322373--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsx@@ -0,0 +1,267 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { Stack, Loader } from "@mantine/core";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import apiClient from "@app/services/apiClient";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import { AdvancedSettingsData } from "@app/components/shared/config/configSections/advanced/advancedSettings";+import { AdvancedFeatureFlagsCard } from "@app/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard";+import { AdvancedProcessingCard } from "@app/components/shared/config/configSections/advanced/AdvancedProcessingCard";+import { AdvancedTempFilesCard } from "@app/components/shared/config/configSections/advanced/AdvancedTempFilesCard";+import { AdvancedProcessExecutorCard } from "@app/components/shared/config/configSections/advanced/AdvancedProcessExecutorCard";+import "@app/components/shared/config/configSections/advanced/AdminAdvancedPage.css";++/**+ * Advanced and Database, previously two nav rows over one object: both read+ * `system` and wrote `system.*` dot-notation deltas, so the split bought two+ * fetches and two drafts of the same data. One page, one draft, one save.+ *+ * Backups & restore stays below the footer because it is not part of the+ * draft: those buttons act on the server the moment they are pressed.+ */+export default function AdminAdvancedPage() {+ const { t } = useTranslation();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();+ const { loginEnabled, validateLoginEnabled } = useLoginRequired();++ const {+ settings,+ setSettings,+ loading,+ saving,+ saveSettings,+ isFieldPending,+ } = useAdminSettings<AdvancedSettingsData>({+ sectionName: "advanced",+ enabled: loginEnabled,+ fetchTransformer: async (): Promise<+ AdvancedSettingsData & { _pending?: Record<string, unknown> }+ > => {+ const [systemResponse, processExecutorResponse] = await Promise.all([+ apiClient.get("/api/v1/admin/settings/section/system"),+ apiClient.get("/api/v1/admin/settings/section/processExecutor"),+ ]);++ const systemData = systemResponse.data || {};+ const processExecutorData = processExecutorResponse.data || {};++ const result: AdvancedSettingsData & {+ _pending?: Record<string, unknown>;+ } = {+ enableAlphaFunctionality: systemData.enableAlphaFunctionality || false,+ maxDPI: systemData.maxDPI || 0,+ enableUrlToPDF: systemData.enableUrlToPDF || false,+ tessdataDir: systemData.tessdataDir || "",+ disableSanitize: systemData.disableSanitize || false,+ tempFileManagement: systemData.tempFileManagement || {+ baseTmpDir: "",+ libreofficeDir: "",+ systemTempDir: "",+ prefix: "stirling-pdf-",+ maxAgeHours: 24,+ cleanupIntervalMinutes: 30,+ startupCleanup: true,+ cleanupSystemTemp: false,+ },+ processExecutor: processExecutorData || {},+ };++ // Merge pending blocks from both endpoints+ const pendingBlock: Record<string, unknown> = {};+ if (systemData._pending?.enableAlphaFunctionality !== undefined) {+ pendingBlock.enableAlphaFunctionality =+ systemData._pending.enableAlphaFunctionality;+ }+ if (systemData._pending?.maxDPI !== undefined) {+ pendingBlock.maxDPI = systemData._pending.maxDPI;+ }+ if (systemData._pending?.enableUrlToPDF !== undefined) {+ pendingBlock.enableUrlToPDF = systemData._pending.enableUrlToPDF;+ }+ if (systemData._pending?.tessdataDir !== undefined) {+ pendingBlock.tessdataDir = systemData._pending.tessdataDir;+ }+ if (systemData._pending?.disableSanitize !== undefined) {+ pendingBlock.disableSanitize = systemData._pending.disableSanitize;+ }+ if (systemData._pending?.tempFileManagement) {+ pendingBlock.tempFileManagement =+ systemData._pending.tempFileManagement;+ }+ if (processExecutorData._pending) {+ pendingBlock.processExecutor = processExecutorData._pending;+ }++ if (Object.keys(pendingBlock).length > 0) {+ result._pending = pendingBlock;+ }++ return result;+ },+ saveTransformer: (settings) => {+ const deltaSettings: Record<string, unknown> = {+ "system.enableAlphaFunctionality": settings.enableAlphaFunctionality,+ "system.maxDPI": settings.maxDPI,+ "system.enableUrlToPDF": settings.enableUrlToPDF,+ "system.tessdataDir": settings.tessdataDir,+ "system.disableSanitize": settings.disableSanitize,+ };++ // Add temp file management settings+ if (settings.tempFileManagement) {+ deltaSettings["system.tempFileManagement.baseTmpDir"] =+ settings.tempFileManagement.baseTmpDir;+ deltaSettings["system.tempFileManagement.libreofficeDir"] =+ settings.tempFileManagement.libreofficeDir;+ deltaSettings["system.tempFileManagement.systemTempDir"] =+ settings.tempFileManagement.systemTempDir;+ deltaSettings["system.tempFileManagement.prefix"] =+ settings.tempFileManagement.prefix;+ deltaSettings["system.tempFileManagement.maxAgeHours"] =+ settings.tempFileManagement.maxAgeHours;+ deltaSettings["system.tempFileManagement.cleanupIntervalMinutes"] =+ settings.tempFileManagement.cleanupIntervalMinutes;+ deltaSettings["system.tempFileManagement.startupCleanup"] =+ settings.tempFileManagement.startupCleanup;+ deltaSettings["system.tempFileManagement.cleanupSystemTemp"] =+ settings.tempFileManagement.cleanupSystemTemp;+ }++ // Add process executor settings+ if (settings.processExecutor?.sessionLimit) {+ Object.entries(settings.processExecutor.sessionLimit).forEach(+ ([key, value]) => {+ deltaSettings[`processExecutor.sessionLimit.${key}`] = value;+ },+ );+ }+ if (settings.processExecutor?.timeoutMinutes) {+ Object.entries(settings.processExecutor.timeoutMinutes).forEach(+ ([key, value]) => {+ deltaSettings[`processExecutor.timeoutMinutes.${key}`] = value;+ },+ );+ }++ // The Database row's eight keys, unchanged. The hook drops any whose+ // value matches the server, so the masked password is never resent.++ return {+ sectionData: {},+ deltaSettings,+ };+ },+ });++ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ settings,+ loading,+ );++ const handleSave = async () => {+ if (!validateLoginEnabled()) {+ return;+ }+ try {+ markSaved();+ await saveSettings();+ showRestartModal();+ } catch (_error) {+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ }+ };++ const handleDiscard = useCallback(() => {+ const original = resetToSnapshot();+ setSettings(original);+ }, [resetToSnapshot, setSettings]);++ const actualLoading = loginEnabled ? loading : false;++ if (actualLoading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ const card = { settings, setSettings, isFieldPending, loginEnabled };++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminAdvancedFeatures"+ title={t("admin.settings.advanced.features", "Feature Flags")}+ >+ <AdvancedFeatureFlagsCard {...card} />+ </SettingsCard>++ <SettingsCard+ id="adminAdvancedProcessing"+ title={t("admin.settings.advanced.processing", "Processing")}+ >+ <AdvancedProcessingCard {...card} />+ </SettingsCard>++ <SettingsCard+ id="adminAdvancedTempFiles"+ title={t(+ "admin.settings.advanced.tempFileManagement.label",+ "Temp File Management",+ )}+ description={t(+ "admin.settings.advanced.tempFileManagement.description",+ "Configure temporary file storage and cleanup behavior",+ )}+ >+ <AdvancedTempFilesCard {...card} />+ </SettingsCard>++ <SettingsCard+ id="adminAdvancedProcessExecutor"+ title={t(+ "admin.settings.advanced.processExecutor.label",+ "Process Executor Limits",+ )}+ description={t(+ "admin.settings.advanced.processExecutor.description",+ "Configure session limits and timeouts for each process executor",+ )}+ >+ <AdvancedProcessExecutorCard {...card} />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={saving}+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsxnew file mode 100644index 0000000000..3c7584833c--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminDatabasePage.tsx@@ -0,0 +1,169 @@+import { useCallback, useMemo } from "react";+import { TierBadge } from "@app/components/shared/config/TierBadge";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { Stack, Loader } from "@mantine/core";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import apiClient from "@app/services/apiClient";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import {+ DEFAULT_DATASOURCE,+ isEmbeddedH2Database,+ type DatasourceSettingsData,+} from "@app/components/shared/config/configSections/advanced/advancedSettings";+import { DatabaseConfigCard } from "@app/components/shared/config/configSections/advanced/DatabaseConfigCard";+import { DatabaseBackupsCard } from "@app/components/shared/config/configSections/advanced/DatabaseBackupsCard";+import "@app/components/shared/config/configSections/advanced/AdminAdvancedPage.css";++/**+ * Connecting a database and backing it up. Its own row rather than a card under+ * Advanced: pointing a large deployment at Postgres is a first-day task, not a+ * knob you go looking for behind a folded group.+ */+export default function AdminDatabasePage() {+ const { t } = useTranslation();+ const { loginEnabled, validateLoginEnabled } = useLoginRequired();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();++ const {+ settings,+ setSettings,+ loading,+ saving,+ saveSettings,+ isFieldPending,+ } = useAdminSettings<{ datasource?: DatasourceSettingsData }>({+ sectionName: "database",+ enabled: loginEnabled,+ fetchTransformer: async () => {+ const response = await apiClient.get(+ "/api/v1/admin/settings/section/system",+ );+ const systemData = response.data || {};+ const result: {+ datasource?: DatasourceSettingsData;+ _pending?: Record<string, unknown>;+ } = { datasource: systemData.datasource || { ...DEFAULT_DATASOURCE } };+ if (systemData._pending?.datasource) {+ result._pending = { datasource: systemData._pending.datasource };+ }+ return result;+ },+ saveTransformer: (s) => {+ const d = s.datasource;+ return {+ sectionData: {},+ deltaSettings: {+ "system.datasource.enableCustomDatabase": d?.enableCustomDatabase,+ "system.datasource.customDatabaseUrl": d?.customDatabaseUrl,+ "system.datasource.username": d?.username,+ "system.datasource.password": d?.password,+ "system.datasource.type": d?.type,+ "system.datasource.hostName": d?.hostName,+ "system.datasource.port": d?.port,+ "system.datasource.name": d?.name,+ },+ };+ },+ });++ const actualLoading = loginEnabled ? loading : false;+ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ settings,+ actualLoading,+ );++ // Backups only exist for the embedded database; a custom one is the+ // operator's to back up.+ const isEmbeddedH2 = useMemo(+ () => isEmbeddedH2Database(settings.datasource),+ [settings.datasource],+ );++ const handleSave = async () => {+ if (!validateLoginEnabled()) return;+ try {+ markSaved();+ await saveSettings();+ showRestartModal();+ } catch (_error) {+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ }+ };++ const handleDiscard = useCallback(() => {+ setSettings(resetToSnapshot());+ }, [resetToSnapshot, setSettings]);++ if (actualLoading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminDatabase"+ title={t("admin.settings.database.connection", "Connection")}+ description={t(+ "admin.settings.database.connectionDescription",+ "Point Stirling at an external database instead of the embedded one.",+ )}+ badge={<TierBadge tier="ENTERPRISE" />}+ >+ <DatabaseConfigCard+ settings={settings}+ setSettings={setSettings}+ isFieldPending={isFieldPending}+ loginEnabled={loginEnabled}+ />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={saving}+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <div className="settings-section-content">+ <SettingsCard+ id="adminDatabaseBackups"+ title={t("admin.settings.database.backupTitle", "Backups & Restore")}+ description={t(+ "admin.settings.database.backupDescription",+ "Manage H2 backups directly from the admin console.",+ )}+ >+ <DatabaseBackupsCard isEmbeddedH2={isEmbeddedH2} />+ </SettingsCard>+ </div>++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsxnew file mode 100644index 0000000000..f5315a0f39--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsx@@ -0,0 +1,88 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { Stack, Paper } from "@mantine/core";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type { AdvancedCardProps } from "@app/components/shared/config/configSections/advanced/advancedCardProps";++/** Server-wide switches. All three need a restart to take effect. */+export function AdvancedFeatureFlagsCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: AdvancedCardProps) {+ const { t } = useTranslation();+ const { getDisabledStyles } = useLoginRequired();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.advanced.enableAlphaFunctionality.label",+ "Enable Alpha Features",+ )}+ info={t(+ "admin.settings.advanced.enableAlphaFunctionality.description",+ "Enable experimental and alpha-stage features (may be unstable)",+ )}+ pending={isFieldPending("enableAlphaFunctionality")}+ checked={settings.enableAlphaFunctionality || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ enableAlphaFunctionality: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.advanced.enableUrlToPDF.label",+ "Enable URL to PDF",+ )}+ info={t(+ "admin.settings.advanced.enableUrlToPDF.description",+ "Allow conversion of web pages to PDF documents (internal use only)",+ )}+ pending={isFieldPending("enableUrlToPDF")}+ checked={settings.enableUrlToPDF || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ enableUrlToPDF: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.advanced.disableSanitize.label",+ "Disable HTML Sanitization",+ )}+ info={t(+ "admin.settings.advanced.disableSanitize.description",+ "Disable HTML sanitization (WARNING: Security risk - can lead to XSS injections)",+ )}+ pending={isFieldPending("disableSanitize")}+ checked={settings.disableSanitize || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ disableSanitize: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedProcessExecutorCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedProcessExecutorCard.tsxnew file mode 100644index 0000000000..91f73f038e--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedProcessExecutorCard.tsx@@ -0,0 +1,826 @@+import { useTranslation } from "react-i18next";+import { SettingsFieldLabel } from "@app/components/shared/config/SettingsFieldLabel";+import { NumberInput, Stack, Paper, Accordion } from "@mantine/core";+import type { AdvancedCardProps } from "@app/components/shared/config/configSections/advanced/advancedCardProps";++/** Per-executor concurrency and timeouts. */+export function AdvancedProcessExecutorCard({+ settings,+ setSettings,+ loginEnabled,+}: AdvancedCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Accordion variant="separated">+ <Accordion.Item value="libreOffice">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.libreOffice",+ "LibreOffice",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.libreOfficeSessionLimit ?? 1+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ libreOfficeSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.libreOfficetimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ libreOfficetimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="pdfToHtml">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.pdfToHtml",+ "PDF to HTML",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.pdfToHtmlSessionLimit ?? 1+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ pdfToHtmlSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.pdfToHtmltimeoutMinutes ?? 20+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ pdfToHtmltimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="qpdf">+ <Accordion.Control>+ {t("admin.settings.advanced.processExecutor.qpdf", "QPDF")}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit?.qpdfSessionLimit ??+ 4+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ qpdfSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.qpdfTimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ qpdfTimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ {/* Tesseract OCR */}+ <Accordion.Item value="tesseract">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.tesseract",+ "Tesseract OCR",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.tesseractSessionLimit ?? 1+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ tesseractSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.tesseractTimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ tesseractTimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="pythonOpenCv">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.pythonOpenCv",+ "Python OpenCV",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.pythonOpenCvSessionLimit ?? 8+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ pythonOpenCvSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.pythonOpenCvtimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ pythonOpenCvtimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="weasyPrint">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.weasyPrint",+ "WeasyPrint",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.weasyPrintSessionLimit ?? 16+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ weasyPrintSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.weasyPrinttimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ weasyPrinttimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="installApp">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.installApp",+ "Install App",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.installAppSessionLimit ?? 1+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ installAppSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.installApptimeoutMinutes ?? 60+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ installApptimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="calibre">+ <Accordion.Control>+ {t("admin.settings.advanced.processExecutor.calibre", "Calibre")}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.calibreSessionLimit ?? 1+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ calibreSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.calibretimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ calibretimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="ghostscript">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.ghostscript",+ "Ghostscript",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.ghostscriptSessionLimit ?? 8+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ ghostscriptSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.ghostscriptTimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ ghostscriptTimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>++ <Accordion.Item value="ocrMyPdf">+ <Accordion.Control>+ {t(+ "admin.settings.advanced.processExecutor.ocrMyPdf",+ "OCRmyPDF",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="sm">+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.sessionLimit.description",+ "Maximum concurrent instances",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.sessionLimit.label",+ "Session Limit",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.sessionLimit+ ?.ocrMyPdfSessionLimit ?? 2+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ sessionLimit: {+ ...settings.processExecutor?.sessionLimit,+ ocrMyPdfSessionLimit: Number(value),+ },+ },+ })+ }+ min={1}+ max={100}+ disabled={!loginEnabled}+ />+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.processExecutor.timeout.description",+ "Maximum execution time",+ )}+ >+ {t(+ "admin.settings.advanced.processExecutor.timeout.label",+ "Timeout (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={+ settings.processExecutor?.timeoutMinutes+ ?.ocrMyPdfTimeoutMinutes ?? 30+ }+ onChange={(value) =>+ setSettings({+ ...settings,+ processExecutor: {+ ...settings.processExecutor,+ timeoutMinutes: {+ ...settings.processExecutor?.timeoutMinutes,+ ocrMyPdfTimeoutMinutes: Number(value),+ },+ },+ })+ }+ min={1}+ max={240}+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>+ </Accordion>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedProcessingCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedProcessingCard.tsxnew file mode 100644index 0000000000..9b9714d6cd--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedProcessingCard.tsx@@ -0,0 +1,411 @@+import { useEffect, useMemo, useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { isAxiosError } from "axios";+import { useTranslation } from "react-i18next";+import {+ NumberInput,+ Stack,+ Paper,+ Text,+ Loader,+ Group,+ TextInput,+ MultiSelect,+} from "@mantine/core";+import { Button } from "@app/ui/Button";+import { alert } from "@app/components/toast";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import apiClient from "@app/services/apiClient";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { AdvancedCardProps } from "@app/components/shared/config/configSections/advanced/advancedCardProps";++/**+ * Image DPI and the OCR tessdata directory. The language list and its+ * downloads are their own live state - they are not part of the settings draft.+ */+export function AdvancedProcessingCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: AdvancedCardProps) {+ const { t } = useTranslation();++ const [tessdataLanguages, setTessdataLanguages] = useState<string[]>([]);+ const [remoteTessdataLanguages, setRemoteTessdataLanguages] = useState<+ string[]+ >([]);+ const [tessdataDirWritable, setTessdataDirWritable] = useState<boolean>(true);+ const [manualDownloadLinks, setManualDownloadLinks] = useState<string[]>([]);+ const [tessdataLanguagesLoading, setTessdataLanguagesLoading] =+ useState(false);+ const [downloadLanguagesLoading, setDownloadLanguagesLoading] =+ useState(false);+ const [selectedDownloadLanguages, setSelectedDownloadLanguages] = useState<+ string[]+ >([]);++ useEffect(() => {+ if (!loginEnabled) return;++ const fetchTessdataLanguages = async () => {+ setTessdataLanguagesLoading(true);+ try {+ const { data } = await apiClient.get<{+ installed: string[];+ available: string[];+ writable?: boolean;+ }>("/api/v1/ui-data/tessdata-languages", {+ suppressErrorToast: true,+ });+ const installed = data.installed || [];+ const available = data.available || [];+ setTessdataLanguages(installed);+ setRemoteTessdataLanguages(+ available.filter((lang) => !installed.includes(lang)),+ );+ setTessdataDirWritable(data.writable !== false);+ setManualDownloadLinks([]);+ } catch (error) {+ console.error(+ "[AdvancedProcessingCard] Failed to load tessdata languages",+ error,+ );+ setTessdataLanguages([]);+ setRemoteTessdataLanguages([]);+ setTessdataDirWritable(true);+ setManualDownloadLinks([]);+ } finally {+ setTessdataLanguagesLoading(false);+ }+ };++ fetchTessdataLanguages();+ }, [loginEnabled]);++ const refreshTessdataWithRetry = async (retries = 3, delayMs = 400) => {+ for (let attempt = 0; attempt < retries; attempt++) {+ try {+ const { data } = await apiClient.get<{+ installed: string[];+ available: string[];+ writable?: boolean;+ }>("/api/v1/ui-data/tessdata-languages", { suppressErrorToast: true });+ const installed = data.installed || [];+ const available = data.available || [];+ setTessdataLanguages(installed);+ setRemoteTessdataLanguages(+ available.filter((lang) => !installed.includes(lang)),+ );+ setTessdataDirWritable(data.writable !== false);+ setManualDownloadLinks([]);+ return;+ } catch (err) {+ if (attempt === retries - 1) {+ console.error(+ "[AdvancedProcessingCard] Retry refresh tessdata failed",+ err,+ );+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, delayMs));+ }+ }+ };++ const safeLangRegex = useMemo(() => new RegExp("[^A-Za-z0-9_+\\-]", "g"), []);++ const handleDownloadTessdataLanguages = async () => {+ if (!loginEnabled) return;+ if (selectedDownloadLanguages.length === 0) {+ alert({+ alertType: "warning",+ title: t(+ "admin.settings.advanced.tessdataDir.downloadMissingTitle",+ "No language selected",+ ),+ body: t(+ "admin.settings.advanced.tessdataDir.downloadMissingBody",+ "Please select at least one language to download.",+ ),+ expandable: false,+ });+ return;+ }+ // Ensure selection is a subset of remote languages to prevent invalid requests+ const remoteSet = new Set(remoteTessdataLanguages);+ const invalidSelection = selectedDownloadLanguages.filter(+ (lang) => !remoteSet.has(lang),+ );+ if (invalidSelection.length > 0) {+ alert({+ alertType: "warning",+ title: t(+ "admin.settings.advanced.tessdataDir.downloadInvalidTitle",+ "Invalid selection",+ ),+ body: t(+ "admin.settings.advanced.tessdataDir.downloadInvalidBody",+ "Some selected languages are not available to download. Please refresh and choose from the list.",+ ),+ expandable: false,+ });+ return;+ }+ setDownloadLanguagesLoading(true);+ try {+ await apiClient.post(+ "/api/v1/ui-data/tessdata/download",+ { languages: selectedDownloadLanguages },+ {+ suppressErrorToast: true,+ },+ );+ alert({+ alertType: "success",+ title: t(+ "admin.settings.advanced.tessdataDir.downloadSuccessTitle",+ "Languages downloaded",+ ),+ body: t(+ "admin.settings.advanced.tessdataDir.downloadSuccessBody",+ "The selected tessdata languages have been saved.",+ ),+ });+ // Refresh installed list with retry in case filesystem sync is delayed+ await refreshTessdataWithRetry();+ setSelectedDownloadLanguages([]);+ setManualDownloadLinks([]);+ } catch (error) {+ console.error(+ "[AdvancedProcessingCard] Download tessdata languages failed",+ error,+ );+ const status = isAxiosError(error) ? error.response?.status : undefined;+ const serverMessage = isAxiosError(error)+ ? error.response?.data?.message+ : undefined;++ if (status === 403) {+ console.warn(+ "[AdvancedProcessingCard] Tessdata directory not writable, falling back to manual download:",+ serverMessage,+ );+ setTessdataDirWritable(false);+ setManualDownloadLinks(+ selectedDownloadLanguages.map((lang) => {+ const safeLang = lang.replace(safeLangRegex, "");+ return `https://raw.githubusercontent.com/tesseract-ocr/tessdata/main/${safeLang}.traineddata`;+ }),+ );+ const message = t(+ "admin.settings.advanced.tessdataDir.downloadErrorPermission",+ {+ defaultValue:+ "Tessdata directory is not writable: {{message}}. Please choose a writable directory (e.g. under the application data folder) or adjust permissions.",+ message:+ serverMessage ?? settings.tessdataDir ?? "unknown location",+ },+ );+ alert({+ alertType: "error",+ title: t(+ "admin.settings.advanced.tessdataDir.downloadErrorTitle",+ "Download Failed",+ ),+ body: message,+ expandable: false,+ });+ return;+ }++ let message: string;+ if (!isAxiosError(error) || !error.response) {+ message = t(+ "admin.settings.advanced.tessdataDir.downloadErrorNetwork",+ "Download failed due to a network error. Please check your connection and try again.",+ );+ } else if (status !== undefined && status >= 500) {+ message = t(+ "admin.settings.advanced.tessdataDir.downloadErrorServer",+ "The server encountered an error while downloading tessdata languages. Please try again later.",+ );+ } else {+ message = t(+ "admin.settings.advanced.tessdataDir.downloadErrorGeneric",+ {+ defaultValue:+ "Download failed: {{message}}. Please try again later.",+ message:+ serverMessage ?? settings.tessdataDir ?? "unknown location",+ },+ );+ }+ alert({+ alertType: "error",+ title: t(+ "admin.settings.advanced.tessdataDir.downloadErrorTitle",+ "Download Failed",+ ),+ body: message,+ expandable: false,+ });+ } finally {+ setDownloadLanguagesLoading(false);+ }+ };++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div>+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.advanced.maxDPI.label", "Maximum DPI")}+ </span>+ <PendingBadge show={isFieldPending("maxDPI")} />+ <InfoTooltip+ label={t(+ "admin.settings.advanced.maxDPI.description",+ "Maximum DPI for image processing (0 = unlimited)",+ )}+ />+ </Group>+ }+ value={settings.maxDPI || 0}+ onChange={(value) =>+ setSettings({ ...settings, maxDPI: Number(value) })+ }+ min={0}+ max={3000}+ disabled={!loginEnabled}+ />+ </div>++ {/* Tessdata Directory */}+ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.advanced.tessdataDir.label",+ "Tessdata Directory",+ )}+ </span>+ <PendingBadge show={isFieldPending("tessdataDir")} />+ <InfoTooltip+ label={t(+ "admin.settings.advanced.tessdataDir.description",+ "Path to the directory containing Tessdata files for OCR",+ )}+ />+ </Group>+ }+ value={settings.tessdataDir || ""}+ onChange={(e) =>+ setSettings({ ...settings, tessdataDir: e.target.value })+ }+ placeholder="/usr/share/tessdata"+ disabled={!loginEnabled}+ />+ {tessdataLanguagesLoading ? (+ <Group gap="xs" mt={6}>+ <Loader size="xs" />+ <Text size="xs">+ {t(+ "admin.settings.advanced.tessdataDir.loadingLanguages",+ "Loading installed tessdata languages...",+ )}+ </Text>+ </Group>+ ) : (+ <Text size="xs" c="dimmed" mt={6}>+ {tessdataLanguages.length > 0+ ? `${t("admin.settings.advanced.tessdataDir.installedLanguages", "Installed tessdata languages")}: ${tessdataLanguages.join(", ")}`+ : t(+ "admin.settings.advanced.tessdataDir.noLanguages",+ "No tessdata languages found in the configured directory",+ )}+ </Text>+ )}+ <Stack gap="xs" mt="sm">+ <MultiSelect+ label={t(+ "admin.settings.advanced.tessdataDir.downloadLabel",+ "Download additional tessdata languages",+ )}+ placeholder={t(+ "admin.settings.advanced.tessdataDir.downloadPlaceholder",+ "Select languages",+ )}+ data={remoteTessdataLanguages.map((lang) => ({+ value: lang,+ label: lang,+ }))}+ searchable+ disabled={!loginEnabled || remoteTessdataLanguages.length === 0}+ value={selectedDownloadLanguages}+ onChange={setSelectedDownloadLanguages}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ nothingFoundMessage={t(+ "admin.settings.advanced.tessdataDir.downloadNothingFound",+ "No additional languages found",+ )}+ />+ {!tessdataDirWritable && (+ <Text size="xs" c="yellow.4">+ {t(+ "admin.settings.advanced.tessdataDir.permissionNotice",+ "The tessdata path is not writable. Downloads will be opened in the browser; please save the .traineddata files manually into the tessdata folder.",+ )}+ </Text>+ )}+ {!tessdataDirWritable && manualDownloadLinks.length > 0 && (+ <Stack gap="xs">+ <Text size="xs" c="dimmed">+ {t(+ "admin.settings.advanced.tessdataDir.manualLinks",+ "Manual downloads: click the links and place the files into the tessdata folder.",+ )}+ </Text>+ <Stack gap={4}>+ {manualDownloadLinks.map((link) => (+ <a+ key={link}+ href={link}+ target="_blank"+ rel="noreferrer"+ style={{ fontSize: "12px" }}+ >+ {link}+ </a>+ ))}+ </Stack>+ </Stack>+ )}+ <Group justify="flex-end">+ <Button+ size="sm"+ variant="secondary"+ onClick={handleDownloadTessdataLanguages}+ loading={downloadLanguagesLoading}+ disabled={!loginEnabled || remoteTessdataLanguages.length === 0}+ >+ {t(+ "admin.settings.advanced.tessdataDir.downloadButton",+ "Download selected languages",+ )}+ </Button>+ </Group>+ </Stack>+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedTempFilesCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedTempFilesCard.tsxnew file mode 100644index 0000000000..28e51a9298--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedTempFilesCard.tsx@@ -0,0 +1,264 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { SettingsFieldLabel } from "@app/components/shared/config/SettingsFieldLabel";+import { NumberInput, Stack, Paper, TextInput } from "@mantine/core";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type { AdvancedCardProps } from "@app/components/shared/config/configSections/advanced/advancedCardProps";++/** Where temp files live and when they are swept. */+export function AdvancedTempFilesCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: AdvancedCardProps) {+ const { t } = useTranslation();+ const { getDisabledStyles } = useLoginRequired();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div>+ <TextInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.tempFileManagement.baseTmpDir.description",+ "Base directory for temporary files (leave empty for default: java.io.tmpdir/stirling-pdf)",+ )}+ >+ {t(+ "admin.settings.advanced.tempFileManagement.baseTmpDir.label",+ "Base Temp Directory",+ )}+ </SettingsFieldLabel>+ }+ value={settings.tempFileManagement?.baseTmpDir || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ baseTmpDir: e.target.value,+ },+ })+ }+ placeholder={t(+ "admin.settings.advanced.tempFileManagement.baseTmpDir.placeholder",+ "Default: java.io.tmpdir/stirling-pdf",+ )}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.tempFileManagement.libreofficeDir.description",+ "Directory for LibreOffice temp files (leave empty for default: baseTmpDir/libreoffice)",+ )}+ >+ {t(+ "admin.settings.advanced.tempFileManagement.libreofficeDir.label",+ "LibreOffice Temp Directory",+ )}+ </SettingsFieldLabel>+ }+ value={settings.tempFileManagement?.libreofficeDir || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ libreofficeDir: e.target.value,+ },+ })+ }+ placeholder={t(+ "admin.settings.advanced.tempFileManagement.libreofficeDir.placeholder",+ "Default: baseTmpDir/libreoffice",+ )}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.tempFileManagement.systemTempDir.description",+ "System temp directory to clean (only used if cleanupSystemTemp is enabled)",+ )}+ >+ {t(+ "admin.settings.advanced.tempFileManagement.systemTempDir.label",+ "System Temp Directory",+ )}+ </SettingsFieldLabel>+ }+ value={settings.tempFileManagement?.systemTempDir || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ systemTempDir: e.target.value,+ },+ })+ }+ placeholder={t(+ "admin.settings.advanced.tempFileManagement.systemTempDir.placeholder",+ "System temp directory path",+ )}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.tempFileManagement.prefix.description",+ "Prefix for temp file names",+ )}+ >+ {t(+ "admin.settings.advanced.tempFileManagement.prefix.label",+ "Temp File Prefix",+ )}+ </SettingsFieldLabel>+ }+ value={settings.tempFileManagement?.prefix || "stirling-pdf-"}+ onChange={(e) =>+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ prefix: e.target.value,+ },+ })+ }+ placeholder="stirling-pdf-"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.tempFileManagement.maxAgeHours.description",+ "Maximum age in hours before temp files are cleaned up",+ )}+ >+ {t(+ "admin.settings.advanced.tempFileManagement.maxAgeHours.label",+ "Max Age (hours)",+ )}+ </SettingsFieldLabel>+ }+ value={settings.tempFileManagement?.maxAgeHours ?? 24}+ onChange={(value) =>+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ maxAgeHours: Number(value),+ },+ })+ }+ min={1}+ max={720}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.advanced.tempFileManagement.cleanupIntervalMinutes.description",+ "How often to run cleanup (in minutes)",+ )}+ >+ {t(+ "admin.settings.advanced.tempFileManagement.cleanupIntervalMinutes.label",+ "Cleanup Interval (minutes)",+ )}+ </SettingsFieldLabel>+ }+ value={settings.tempFileManagement?.cleanupIntervalMinutes ?? 30}+ onChange={(value) =>+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ cleanupIntervalMinutes: Number(value),+ },+ })+ }+ min={1}+ max={1440}+ disabled={!loginEnabled}+ />+ </div>++ <SettingsToggleRow+ label={t(+ "admin.settings.advanced.tempFileManagement.startupCleanup.label",+ "Startup Cleanup",+ )}+ info={t(+ "admin.settings.advanced.tempFileManagement.startupCleanup.description",+ "Clean up old temp files on application startup",+ )}+ pending={isFieldPending("tempFileManagement.startupCleanup")}+ checked={settings.tempFileManagement?.startupCleanup ?? true}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ startupCleanup: checked,+ },+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.advanced.tempFileManagement.cleanupSystemTemp.label",+ "Cleanup System Temp",+ )}+ info={t(+ "admin.settings.advanced.tempFileManagement.cleanupSystemTemp.description",+ "Whether to clean broader system temp directory (use with caution)",+ )}+ pending={isFieldPending("tempFileManagement.cleanupSystemTemp")}+ checked={settings.tempFileManagement?.cleanupSystemTemp ?? false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ tempFileManagement: {+ ...settings.tempFileManagement,+ cleanupSystemTemp: checked,+ },+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsxnew file mode 100644index 0000000000..b5d8249483--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseBackupsCard.tsx@@ -0,0 +1,684 @@+import { useEffect, useState } from "react";+import { isAxiosError } from "axios";+import { useTranslation } from "react-i18next";+import {+ Stack,+ Paper,+ Text,+ Loader,+ Group,+ TextInput,+ Badge,+ Table,+ Tooltip,+ FileInput,+ Alert,+ Box,+ Modal,+} from "@mantine/core";+import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";+import { alert } from "@app/components/toast";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import LocalIcon from "@app/components/shared/LocalIcon";+import databaseManagementService, {+ DatabaseBackupFile,+} from "@app/services/databaseManagementService";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";++interface DatabaseBackupsCardProps {+ /** Backups exist only for the embedded H2 database. */+ isEmbeddedH2: boolean;+}++/**+ * Instant CRUD over the H2 backup files: nothing here belongs to the settings+ * draft, so this card owns its own state and never touches Save or Discard.+ */+export function DatabaseBackupsCard({+ isEmbeddedH2,+}: DatabaseBackupsCardProps) {+ const { t } = useTranslation();+ const { loginEnabled, validateLoginEnabled } = useLoginRequired();++ const [backupFiles, setBackupFiles] = useState<DatabaseBackupFile[]>([]);+ const [databaseVersion, setDatabaseVersion] = useState<string | null>(null);+ const [backupsLoading, setBackupsLoading] = useState(false);+ const [creatingBackup, setCreatingBackup] = useState(false);+ const [importingUpload, setImportingUpload] = useState(false);+ const [importingBackupFile, setImportingBackupFile] = useState<string | null>(+ null,+ );+ const [deletingFile, setDeletingFile] = useState<string | null>(null);+ const [downloadingFile, setDownloadingFile] = useState<string | null>(null);+ const [uploadFile, setUploadFile] = useState<File | null>(null);+ const [confirmImportOpen, setConfirmImportOpen] = useState(false);+ const [deleteConfirmFile, setDeleteConfirmFile] = useState<string | null>(+ null,+ );+ const [confirmCode, setConfirmCode] = useState("");+ const [confirmInput, setConfirmInput] = useState("");++ const loadBackupData = async () => {+ if (!loginEnabled || !isEmbeddedH2) {+ setBackupFiles([]);+ setDatabaseVersion(null);+ return;+ }+ setBackupsLoading(true);+ try {+ const data = await databaseManagementService.getDatabaseData();+ setBackupFiles(data.backupFiles || []);+ setDatabaseVersion(data.databaseVersion || null);+ } catch (error: unknown) {+ const message = isAxiosError(error)+ ? error.response?.data?.message || error.message+ : undefined;+ alert({+ alertType: "error",+ title: t(+ "admin.settings.database.loadError",+ "Failed to load database backups",+ ),+ body: message,+ });+ } finally {+ setBackupsLoading(false);+ }+ };++ // The datasource type and the custom-database switch only reach this card+ // through isEmbeddedH2, so it is the whole of the draft this reload watches.+ useEffect(() => {+ loadBackupData();+ }, [loginEnabled, isEmbeddedH2]);++ const handleCreateBackup = async () => {+ if (!validateLoginEnabled()) return;+ setCreatingBackup(true);+ try {+ await databaseManagementService.createBackup();+ alert({+ alertType: "success",+ title: t(+ "admin.settings.database.backupCreated",+ "Backup created successfully",+ ),+ });+ await loadBackupData();+ } catch (error: unknown) {+ const message = isAxiosError(error)+ ? error.response?.data?.message || error.message+ : undefined;+ alert({+ alertType: "error",+ title: t(+ "admin.settings.database.backupFailed",+ "Failed to create backup",+ ),+ body: message,+ });+ } finally {+ setCreatingBackup(false);+ }+ };++ const performUploadImport = async () => {+ if (!uploadFile) return;+ setImportingUpload(true);+ try {+ await databaseManagementService.uploadAndImport(uploadFile);+ alert({+ alertType: "success",+ title: t(+ "admin.settings.database.importSuccess",+ "Backup imported successfully",+ ),+ });+ setUploadFile(null);+ await loadBackupData();+ } catch (error: unknown) {+ const message = isAxiosError(error)+ ? error.response?.data?.message || error.message+ : undefined;+ alert({+ alertType: "error",+ title: t(+ "admin.settings.database.importFailed",+ "Failed to import backup",+ ),+ body: message,+ });+ } finally {+ setImportingUpload(false);+ }+ };++ const generateConfirmationCode = () => {+ if (+ typeof crypto !== "undefined" &&+ typeof crypto.getRandomValues === "function"+ ) {+ const array = new Uint32Array(1);+ crypto.getRandomValues(array);+ const randomNumber = array[0] % 10000; // 0-9999+ return randomNumber.toString().padStart(4, "0");+ }+ // Fallback: non-cryptographic but avoids Math.random(); this is only a UX safeguard.+ const fallbackNumber = Date.now() % 10000;+ return fallbackNumber.toString().padStart(4, "0");+ };++ const handleUploadImport = () => {+ if (!validateLoginEnabled()) return;+ if (!uploadFile) {+ alert({+ alertType: "warning",+ title: t(+ "admin.settings.database.selectFile",+ "Please select a .sql file to import",+ ),+ });+ return;+ }+ const code = generateConfirmationCode();+ setConfirmCode(code);+ setConfirmInput("");+ setConfirmImportOpen(true);+ };++ const closeConfirmImportModal = () => {+ setConfirmImportOpen(false);+ setConfirmInput("");+ };++ const handleConfirmImport = async () => {+ if (confirmInput !== confirmCode) {+ alert({+ alertType: "warning",+ title: t(+ "admin.settings.database.codeMismatch",+ "Confirmation code does not match",+ ),+ body: t(+ "admin.settings.database.codeMismatchBody",+ "Please enter the code exactly as shown to proceed.",+ ),+ });+ return;+ }+ closeConfirmImportModal();+ await performUploadImport();+ };++ const handleImportExisting = async (fileName: string) => {+ if (!validateLoginEnabled()) return;+ setImportingBackupFile(fileName);+ try {+ await databaseManagementService.importFromFileName(fileName);+ alert({+ alertType: "success",+ title: t(+ "admin.settings.database.importSuccess",+ "Backup imported successfully",+ ),+ });+ await loadBackupData();+ } catch (error: unknown) {+ const message = isAxiosError(error)+ ? error.response?.data?.message || error.message+ : undefined;+ alert({+ alertType: "error",+ title: t(+ "admin.settings.database.importFailed",+ "Failed to import backup",+ ),+ body: message,+ });+ } finally {+ setImportingBackupFile(null);+ }+ };++ const handleDelete = async (fileName: string) => {+ if (!validateLoginEnabled()) return;+ setDeletingFile(fileName);+ try {+ await databaseManagementService.deleteBackup(fileName);+ alert({+ alertType: "success",+ title: t("admin.settings.database.deleteSuccess", "Backup deleted"),+ });+ await loadBackupData();+ } catch (error: unknown) {+ const message = isAxiosError(error)+ ? error.response?.data?.message || error.message+ : undefined;+ alert({+ alertType: "error",+ title: t(+ "admin.settings.database.deleteFailed",+ "Failed to delete backup",+ ),+ body: message,+ });+ } finally {+ setDeletingFile(null);+ setDeleteConfirmFile(null);+ }+ };++ const handleDeleteClick = (fileName: string) => {+ if (!validateLoginEnabled()) return;+ setDeleteConfirmFile(fileName);+ };++ const handleDownload = async (fileName: string) => {+ if (!validateLoginEnabled()) return;+ setDownloadingFile(fileName);+ let url: string | null = null;++ const link = document.createElement("a");+ try {+ const blob = await databaseManagementService.downloadBackup(fileName);+ url = window.URL.createObjectURL(blob);+ link.href = url;+ link.download = fileName;+ document.body.appendChild(link);+ link.click();+ } catch (error: unknown) {+ const message = isAxiosError(error)+ ? error.response?.data?.message || error.message+ : undefined;+ alert({+ alertType: "error",+ title: t(+ "admin.settings.database.downloadFailed",+ "Failed to download backup",+ ),+ body: message,+ });+ } finally {+ if (link.isConnected) {+ link.remove();+ }+ if (url) {+ window.URL.revokeObjectURL(url);+ }+ setDownloadingFile(null);+ }+ };++ return (+ <>+ <Stack gap="md">+ {!isEmbeddedH2 && (+ <Alert+ icon={<LocalIcon icon="info" width="1.2rem" height="1.2rem" />}+ color="yellow"+ radius="md"+ >+ <Text fw={600} size="sm">+ {t(+ "admin.settings.database.h2Only",+ "Backups are available only for the embedded H2 database.",+ )}+ </Text>+ <Text size="sm" c="dimmed">+ {t(+ "admin.settings.database.h2Hint",+ "Set the database type to H2 and disable custom database to enable backup and restore.",+ )}+ </Text>+ </Alert>+ )}+ {isEmbeddedH2 && (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Group justify="space-between" align="center">+ <Group gap="xs">+ <LocalIcon icon="backup" width="1.4rem" height="1.4rem" />+ <Text fw={600}>+ {t(+ "admin.settings.database.manageBackups",+ "Manage backups",+ )}+ </Text>+ <Badge color="green" variant="light" size="sm">+ {t("admin.settings.database.embedded", "Embedded H2")}+ </Badge>+ {databaseVersion && (+ <Badge color="blue" variant="light" size="sm">+ {t("admin.settings.database.version", "H2 Version")}:{" "}+ {databaseVersion}+ </Badge>+ )}+ </Group>+ <Group gap="xs">+ <Button+ variant="secondary"+ leftSection={+ <LocalIcon icon="refresh" width="1rem" height="1rem" />+ }+ onClick={loadBackupData}+ disabled={!loginEnabled || !isEmbeddedH2}+ >+ {t("admin.settings.database.refresh", "Refresh")}+ </Button>+ <Button+ leftSection={+ <LocalIcon icon="upload" width="1rem" height="1rem" />+ }+ onClick={handleCreateBackup}+ loading={creatingBackup}+ disabled={!loginEnabled || !isEmbeddedH2}+ >+ {t("admin.settings.database.createBackup", "Create backup")}+ </Button>+ </Group>+ </Group>++ <Box>+ <Text fw={500} size="sm" mb={6}>+ {t("admin.settings.database.uploadTitle", "Upload & import")}+ </Text>+ <Group gap="sm" align="flex-end" wrap="wrap">+ <FileInput+ value={uploadFile}+ onChange={setUploadFile}+ placeholder={t(+ "admin.settings.database.chooseFile",+ "Choose a .sql backup file",+ )}+ accept=".sql"+ disabled={!loginEnabled || !isEmbeddedH2}+ styles={{ input: { minWidth: 280 } }}+ />+ <Button+ variant="secondary"+ onClick={handleUploadImport}+ loading={importingUpload}+ disabled={!loginEnabled || !isEmbeddedH2}+ leftSection={+ <LocalIcon+ icon="play-circle"+ width="1rem"+ height="1rem"+ />+ }+ >+ {t(+ "admin.settings.database.importFromUpload",+ "Import upload",+ )}+ </Button>+ </Group>+ </Box>++ {backupsLoading ? (+ <Group justify="center" py="md">+ <Loader size="sm" />+ </Group>+ ) : backupFiles.length === 0 ? (+ <Text size="sm" c="dimmed">+ {isEmbeddedH2+ ? t(+ "admin.settings.database.noBackups",+ "No backups found yet.",+ )+ : t(+ "admin.settings.database.unavailable",+ "Backup list unavailable for the current database configuration.",+ )}+ </Text>+ ) : (+ <Table highlightOnHover withColumnBorders verticalSpacing="sm">+ <Table.Thead>+ <Table.Tr>+ <Table.Th>+ {t("admin.settings.database.fileName", "File")}+ </Table.Th>+ <Table.Th>+ {t("admin.settings.database.created", "Created")}+ </Table.Th>+ <Table.Th>+ {t("admin.settings.database.size", "Size")}+ </Table.Th>+ <Table.Th w={150}>+ {t("admin.settings.database.actions", "Actions")}+ </Table.Th>+ </Table.Tr>+ </Table.Thead>+ <Table.Tbody>+ {backupFiles.map((backup) => (+ <Table.Tr key={backup.fileName}>+ <Table.Td>{backup.fileName}</Table.Td>+ <Table.Td>+ {backup.formattedCreationDate ||+ backup.creationDate ||+ "-"}+ </Table.Td>+ <Table.Td>{backup.formattedFileSize || "-"}</Table.Td>+ <Table.Td>+ <Group gap="xs" justify="flex-start">+ <Tooltip+ label={t(+ "admin.settings.database.download",+ "Download",+ )}+ withArrow+ >+ <ActionIcon+ variant="tertiary"+ onClick={() => handleDownload(backup.fileName)}+ disabled={!loginEnabled || !isEmbeddedH2}+ aria-label={t(+ "admin.settings.database.download",+ "Download",+ )}+ >+ {downloadingFile === backup.fileName ? (+ <Loader size="xs" />+ ) : (+ <LocalIcon+ icon="download"+ width="1rem"+ height="1rem"+ />+ )}+ </ActionIcon>+ </Tooltip>+ <Tooltip+ label={t(+ "admin.settings.database.import",+ "Import",+ )}+ withArrow+ >+ <ActionIcon+ variant="tertiary"+ onClick={() =>+ handleImportExisting(backup.fileName)+ }+ disabled={!loginEnabled || !isEmbeddedH2}+ aria-label={t(+ "admin.settings.database.import",+ "Import",+ )}+ >+ {importingBackupFile === backup.fileName ? (+ <Loader size="xs" />+ ) : (+ <LocalIcon+ icon="backup"+ width="1rem"+ height="1rem"+ />+ )}+ </ActionIcon>+ </Tooltip>+ <Tooltip+ label={t(+ "admin.settings.database.delete",+ "Delete",+ )}+ withArrow+ >+ <ActionIcon+ variant="tertiary"+ accent="danger"+ onClick={() =>+ handleDeleteClick(backup.fileName)+ }+ disabled={!loginEnabled || !isEmbeddedH2}+ aria-label={t(+ "admin.settings.database.delete",+ "Delete",+ )}+ >+ {deletingFile === backup.fileName ? (+ <Loader size="xs" />+ ) : (+ <LocalIcon+ icon="delete"+ width="1rem"+ height="1rem"+ />+ )}+ </ActionIcon>+ </Tooltip>+ </Group>+ </Table.Td>+ </Table.Tr>+ ))}+ </Table.Tbody>+ </Table>+ )}+ </Stack>+ </Paper>+ )}+ </Stack>++ <Modal+ opened={confirmImportOpen}+ onClose={closeConfirmImportModal}+ title={t(+ "admin.settings.database.confirmImportTitle",+ "Confirm database import",+ )}+ centered+ withinPortal+ zIndex={Z_INDEX_OVER_CONFIG_MODAL}+ >+ <Stack gap="md">+ <Alert+ color="red"+ variant="light"+ icon={<LocalIcon icon="warning" width="1.2rem" height="1.2rem" />}+ >+ <Text fw={600}>+ {t(+ "admin.settings.database.overwriteWarning",+ "Warning: This will overwrite the current database.",+ )}+ </Text>+ <Text size="sm" c="dimmed">+ {t(+ "admin.settings.database.overwriteWarningBody",+ "All existing data will be replaced by the uploaded backup. This action cannot be undone.",+ )}+ </Text>+ </Alert>+ <Stack gap={6}>+ <Text size="sm" fw={600}>+ {t(+ "admin.settings.database.confirmCodeLabel",+ "Enter the confirmation code to proceed",+ )}+ </Text>+ <Text size="lg" fw={700}>+ {confirmCode}+ </Text>+ <TextInput+ value={confirmInput}+ onChange={(e) => setConfirmInput(e.currentTarget.value)}+ placeholder={t(+ "admin.settings.database.enterCode",+ "Enter the code shown above",+ )}+ minLength={4}+ maxLength={4}+ disabled={importingUpload}+ />+ </Stack>+ <Group justify="flex-end" gap="sm">+ <Button+ variant="secondary"+ onClick={closeConfirmImportModal}+ disabled={importingUpload}+ >+ {t("cancel", "Cancel")}+ </Button>+ <Button+ accent="danger"+ onClick={handleConfirmImport}+ loading={importingUpload}+ disabled={confirmInput.length === 0}+ >+ {t("admin.settings.database.confirmImport", "Confirm import")}+ </Button>+ </Group>+ </Stack>+ </Modal>++ <Modal+ opened={deleteConfirmFile !== null}+ onClose={() => setDeleteConfirmFile(null)}+ title={t("admin.settings.database.deleteTitle", "Delete backup")}+ centered+ withinPortal+ zIndex={Z_INDEX_OVER_CONFIG_MODAL}+ >+ <Stack gap="md">+ <Alert+ color="red"+ variant="light"+ icon={<LocalIcon icon="warning" width="1.2rem" height="1.2rem" />}+ >+ <Text fw={600}>+ {t(+ "admin.settings.database.deleteConfirm",+ "Delete this backup? This cannot be undone.",+ )}+ </Text>+ <Text size="sm" c="dimmed">+ {deleteConfirmFile}+ </Text>+ </Alert>+ <Group justify="flex-end" gap="sm">+ <Button+ variant="secondary"+ onClick={() => setDeleteConfirmFile(null)}+ disabled={deletingFile !== null}+ >+ {t("cancel", "Cancel")}+ </Button>+ <Button+ accent="danger"+ onClick={() =>+ deleteConfirmFile && handleDelete(deleteConfirmFile)+ }+ loading={deletingFile === deleteConfirmFile}+ >+ {t(+ "admin.settings.database.deleteConfirmAction",+ "Delete backup",+ )}+ </Button>+ </Group>+ </Stack>+ </Modal>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseConfigCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseConfigCard.tsxnew file mode 100644index 0000000000..4f9d58165b--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/DatabaseConfigCard.tsx@@ -0,0 +1,267 @@+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useTranslation } from "react-i18next";+import {+ NumberInput,+ Stack,+ Paper,+ Group,+ TextInput,+ Select,+} from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import EditableSecretField from "@app/components/shared/EditableSecretField";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { DatasourceSettingsData } from "@app/components/shared/config/configSections/advanced/advancedSettings";+import type { AdvancedCardProps } from "@app/components/shared/config/configSections/advanced/advancedCardProps";++/**+ * The `system.datasource` block, previously its own nav row. The password stays+ * masked ("********") until the user edits it, so an untouched field never+ * reaches the delta.+ */+export function DatabaseConfigCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: AdvancedCardProps) {+ const { t } = useTranslation();+ const { getDisabledStyles } = useLoginRequired();++ const datasource = settings.datasource;+ const setDatasource = (patch: Partial<DatasourceSettingsData>) =>+ setSettings({+ ...settings,+ datasource: { ...(settings.datasource || {}), ...patch },+ });++ return (+ <>+ <div></div>++ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.database.enableCustom.label",+ "Enable Custom Database",+ )}+ info={t(+ "admin.settings.database.enableCustom.description",+ "Use your own custom database configuration instead of the default embedded database",+ )}+ pending={isFieldPending("datasource.enableCustomDatabase")}+ checked={datasource?.enableCustomDatabase || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setDatasource({ enableCustomDatabase: checked });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ {datasource?.enableCustomDatabase && (+ <>+ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.database.customUrl.label",+ "Custom Database URL",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("datasource.customDatabaseUrl")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.database.customUrl.description",+ "Full JDBC connection string (e.g., jdbc:postgresql://localhost:5432/postgres). If provided, individual connection settings below are not used.",+ )}+ />+ </Group>+ }+ value={datasource?.customDatabaseUrl || ""}+ onChange={(e) =>+ setDatasource({ customDatabaseUrl: e.target.value })+ }+ placeholder="jdbc:postgresql://localhost:5432/postgres"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <Select+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.database.type.label",+ "Database Type",+ )}+ </span>+ <PendingBadge show={isFieldPending("datasource.type")} />+ <InfoTooltip+ label={t(+ "admin.settings.database.type.description",+ "Type of database (not used if custom URL is provided)",+ )}+ />+ </Group>+ }+ value={datasource?.type || "postgresql"}+ onChange={(value) =>+ setDatasource({ type: value || "postgresql" })+ }+ data={[+ { value: "postgresql", label: "PostgreSQL" },+ { value: "h2", label: "H2" },+ { value: "mysql", label: "MySQL" },+ { value: "mariadb", label: "MariaDB" },+ ]}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.database.hostName.label",+ "Host Name",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("datasource.hostName")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.database.hostName.description",+ "Database server hostname (not used if custom URL is provided)",+ )}+ />+ </Group>+ }+ value={datasource?.hostName || ""}+ onChange={(e) => setDatasource({ hostName: e.target.value })}+ placeholder="localhost"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.database.port.label", "Port")}+ </span>+ <PendingBadge show={isFieldPending("datasource.port")} />+ <InfoTooltip+ label={t(+ "admin.settings.database.port.description",+ "Database server port (not used if custom URL is provided)",+ )}+ />+ </Group>+ }+ value={datasource?.port || 5432}+ onChange={(value) => setDatasource({ port: Number(value) })}+ min={1}+ max={65535}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.database.name.label",+ "Database Name",+ )}+ </span>+ <PendingBadge show={isFieldPending("datasource.name")} />+ <InfoTooltip+ label={t(+ "admin.settings.database.name.description",+ "Name of the database (not used if custom URL is provided)",+ )}+ />+ </Group>+ }+ value={datasource?.name || ""}+ onChange={(e) => setDatasource({ name: e.target.value })}+ placeholder="postgres"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.database.username.label",+ "Username",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("datasource.username")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.database.username.description",+ "Database authentication username",+ )}+ />+ </Group>+ }+ value={datasource?.username || ""}+ onChange={(e) => setDatasource({ username: e.target.value })}+ placeholder="postgres"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <Group gap="xs" align="center" mb={4}>+ <span style={{ fontWeight: 500, fontSize: "0.875rem" }}>+ {t("admin.settings.database.password.label", "Password")}+ </span>+ <PendingBadge show={isFieldPending("datasource.password")} />+ </Group>+ <EditableSecretField+ description={t(+ "admin.settings.database.password.description",+ "Database authentication password",+ )}+ value={datasource?.password || ""}+ onChange={(value) => setDatasource({ password: value })}+ placeholder={t(+ "admin.settings.database.password.placeholder",+ "Enter database password",+ )}+ disabled={!loginEnabled}+ />+ </div>+ </>+ )}+ </Stack>+ </Paper>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedCardProps.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedCardProps.tsnew file mode 100644index 0000000000..e5fe84953a--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedCardProps.ts@@ -0,0 +1,14 @@+import type { AdvancedSettingsData } from "@app/components/shared/config/configSections/advanced/advancedSettings";++/**+ * What every card on the Advanced page needs from the page that owns them.+ * Advanced and Database were two rows over one `system` object, so the merged+ * page keeps a single draft and hands each card a slice of it.+ */+export interface AdvancedCardProps {+ settings: AdvancedSettingsData;+ setSettings: (next: AdvancedSettingsData) => void;+ /** True while the backend still lists this key as awaiting a restart. */+ isFieldPending: (field: string) => boolean;+ loginEnabled: boolean;+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.test.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.test.tsnew file mode 100644index 0000000000..f225c6be4f--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from "vitest";+import {+ DEFAULT_DATASOURCE,+ isEmbeddedH2Database,+} from "@app/components/shared/config/configSections/advanced/advancedSettings";++describe("isEmbeddedH2Database", () => {+ test("a stock install with no datasource block is embedded", () => {+ expect(isEmbeddedH2Database(undefined)).toBe(true);+ });++ test("the pre-filled form defaults do not make it a custom database", () => {+ // The regression: DEFAULT_DATASOURCE.type is "postgresql" so the picker has+ // something to show, and reading it first hid backups on every stock install.+ expect(DEFAULT_DATASOURCE.type).toBe("postgresql");+ expect(DEFAULT_DATASOURCE.enableCustomDatabase).toBe(false);+ expect(isEmbeddedH2Database(DEFAULT_DATASOURCE)).toBe(true);+ });++ test("custom database on with postgres is not embedded", () => {+ expect(+ isEmbeddedH2Database({+ ...DEFAULT_DATASOURCE,+ enableCustomDatabase: true,+ }),+ ).toBe(false);+ });++ test("custom database on but pointed at H2 still backs up", () => {+ expect(+ isEmbeddedH2Database({+ ...DEFAULT_DATASOURCE,+ enableCustomDatabase: true,+ type: "H2",+ }),+ ).toBe(true);+ });+});diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.tsnew file mode 100644index 0000000000..5ed9e8f3a7--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.ts@@ -0,0 +1,83 @@+/** The `system.datasource` block, previously the Database row's whole draft. */+export interface DatasourceSettingsData {+ enableCustomDatabase?: boolean;+ customDatabaseUrl?: string;+ username?: string;+ password?: string;+ type?: string;+ hostName?: string;+ port?: number;+ name?: string;+}++/**+ * Placeholder values for the custom-database form when `system.datasource` is+ * missing. `type` pre-fills the picker; it does not say what is running.+ */+export const DEFAULT_DATASOURCE: DatasourceSettingsData = {+ enableCustomDatabase: false,+ customDatabaseUrl: "",+ username: "",+ password: "",+ type: "postgresql",+ hostName: "localhost",+ port: 5432,+ name: "postgres",+};++/**+ * Is the server on its embedded H2, the only database it can back up? Custom+ * database off settles it: `type` above is a form default, not what is running.+ */+export function isEmbeddedH2Database(+ datasource: DatasourceSettingsData | undefined,+): boolean {+ if (datasource?.enableCustomDatabase !== true) return true;+ return (datasource.type || "").toLowerCase() === "h2";+}++export interface AdvancedSettingsData {+ enableAlphaFunctionality?: boolean;+ maxDPI?: number;+ enableUrlToPDF?: boolean;+ tessdataDir?: string;+ disableSanitize?: boolean;+ tempFileManagement?: {+ baseTmpDir?: string;+ libreofficeDir?: string;+ systemTempDir?: string;+ prefix?: string;+ maxAgeHours?: number;+ cleanupIntervalMinutes?: number;+ startupCleanup?: boolean;+ cleanupSystemTemp?: boolean;+ };+ processExecutor?: {+ sessionLimit?: {+ libreOfficeSessionLimit?: number;+ pdfToHtmlSessionLimit?: number;+ qpdfSessionLimit?: number;+ tesseractSessionLimit?: number;+ pythonOpenCvSessionLimit?: number;+ weasyPrintSessionLimit?: number;+ installAppSessionLimit?: number;+ calibreSessionLimit?: number;+ ghostscriptSessionLimit?: number;+ ocrMyPdfSessionLimit?: number;+ };+ timeoutMinutes?: {+ libreOfficetimeoutMinutes?: number;+ pdfToHtmltimeoutMinutes?: number;+ pythonOpenCvtimeoutMinutes?: number;+ weasyPrinttimeoutMinutes?: number;+ installApptimeoutMinutes?: number;+ calibretimeoutMinutes?: number;+ tesseractTimeoutMinutes?: number;+ qpdfTimeoutMinutes?: number;+ ghostscriptTimeoutMinutes?: number;+ ocrMyPdfTimeoutMinutes?: number;+ };+ };+ /** Read from the same `system` response as everything above it. */+ datasource?: DatasourceSettingsData;+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AdminAiSection.css b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AdminAiSection.cssnew file mode 100644index 0000000000..431711ce0d--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AdminAiSection.css@@ -0,0 +1,15 @@+.admin-ai__card {+ display: flex;+ flex-direction: column;+ gap: var(--space-3, 0.75rem);+}++/* Permanent, not just during the focus pulse: an anchored jump would otherwise+ land the heading under the sticky search bar. */+.admin-ai__heading {+ margin: 0;+ scroll-margin-top: 1rem;+ font-size: 0.9375rem;+ font-weight: var(--font-weight-semibold, 600);+ color: var(--c-text);+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiCapabilitiesCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiCapabilitiesCard.tsxnew file mode 100644index 0000000000..bc24c51541--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiCapabilitiesCard.tsx@@ -0,0 +1,152 @@+import { useTranslation } from "react-i18next";+import { Stack, Paper, Text, Group, Switch } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import type { AiEngineFeatures } from "@app/components/shared/config/configSections/aiEngineSettings";+import type { AiCardProps } from "@app/components/shared/config/configSections/ai/aiCardProps";++interface FeatureSwitchProps {+ label: string;+ description: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+ pending: boolean;+ disabled: boolean;+}++function FeatureSwitch({+ label,+ description,+ checked,+ onChange,+ pending,+ disabled,+}: FeatureSwitchProps) {+ return (+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <Group gap={4} wrap="nowrap">+ <Text fw={500} size="sm">+ {label}+ </Text>+ <InfoTooltip label={description} />+ </Group>+ <Group gap="xs">+ <Switch+ checked={checked}+ onChange={(e) => onChange(e.target.checked)}+ disabled={disabled}+ // The visible label is a sibling Text, so the control needs its own name.+ aria-label={label}+ />+ <PendingBadge show={pending} />+ </Group>+ </Group>+ );+}++/** Which AI features are on. Every key here needs a restart to take effect. */+export function AiCapabilitiesCard({+ settings,+ setSettings,+ isFieldPending,+}: AiCardProps) {+ const { t } = useTranslation();++ const enabled = settings.enabled || false;+ const setFeatures = (patch: Partial<AiEngineFeatures>) =>+ setSettings({+ ...settings,+ features: { ...(settings.features || {}), ...patch },+ });++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <FeatureSwitch+ label={t(+ "admin.settings.ai.general.features.chat.label",+ "Chat assistant",+ )}+ description={t(+ "admin.settings.ai.general.features.chat.description",+ "Conversational assistant for working with PDFs.",+ )}+ checked={settings.features?.chat ?? false}+ onChange={(checked) => setFeatures({ chat: checked })}+ pending={isFieldPending("features.chat")}+ disabled={!enabled}+ />+ <FeatureSwitch+ label={t(+ "admin.settings.ai.general.features.documentQuestions.label",+ "Document questions",+ )}+ description={t(+ "admin.settings.ai.general.features.documentQuestions.description",+ "Ask questions and get answers grounded in an uploaded document.",+ )}+ checked={settings.features?.documentQuestions ?? false}+ onChange={(checked) => setFeatures({ documentQuestions: checked })}+ pending={isFieldPending("features.documentQuestions")}+ disabled={!enabled}+ />+ <FeatureSwitch+ label={t(+ "admin.settings.ai.general.features.createPdf.label",+ "Create PDF from prompt",+ )}+ description={t(+ "admin.settings.ai.general.features.createPdf.description",+ "Generate a new PDF (e.g. from HTML) via an AI agent.",+ )}+ checked={settings.features?.createPdf ?? false}+ onChange={(checked) => setFeatures({ createPdf: checked })}+ pending={isFieldPending("features.createPdf")}+ disabled={!enabled}+ />+ <FeatureSwitch+ label={t(+ "admin.settings.ai.general.features.mathAuditor.label",+ "Math auditor",+ )}+ description={t(+ "admin.settings.ai.general.features.mathAuditor.description",+ "Review documents for mathematical and numerical errors.",+ )}+ checked={settings.features?.mathAuditor ?? false}+ onChange={(checked) => setFeatures({ mathAuditor: checked })}+ pending={isFieldPending("features.mathAuditor")}+ disabled={!enabled}+ />+ <FeatureSwitch+ label={t(+ "admin.settings.ai.general.features.pdfComment.label",+ "PDF comment agent",+ )}+ description={t(+ "admin.settings.ai.general.features.pdfComment.description",+ "Add AI-authored review comments and annotations to a PDF.",+ )}+ checked={settings.features?.pdfComment ?? false}+ onChange={(checked) => setFeatures({ pdfComment: checked })}+ pending={isFieldPending("features.pdfComment")}+ disabled={!enabled}+ />+ <FeatureSwitch+ label={t(+ "admin.settings.ai.general.features.classify.label",+ "Document classification",+ )}+ description={t(+ "admin.settings.ai.general.features.classify.description",+ "Automatically categorise documents by type or content.",+ )}+ checked={settings.features?.classify ?? false}+ onChange={(checked) => setFeatures({ classify: checked })}+ pending={isFieldPending("features.classify")}+ disabled={!enabled}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsxnew file mode 100644index 0000000000..c976633edd--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsx@@ -0,0 +1,239 @@+import { useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useTranslation } from "react-i18next";+import {+ TextInput,+ NumberInput,+ Switch,+ Stack,+ Paper,+ Text,+ Group,+ Alert,+ Code,+} from "@mantine/core";+import { alert } from "@app/components/toast";+import LocalIcon from "@app/components/shared/LocalIcon";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import apiClient from "@app/services/apiClient";+import { Button } from "@app/ui/Button";+import type { AiCardProps } from "@app/components/shared/config/configSections/ai/aiCardProps";++/** Whether the engine is on and how to reach it. Restart-required, all of it. */+export function AiConnectionCard({+ settings,+ setSettings,+ isFieldPending,+}: AiCardProps) {+ const { t } = useTranslation();+ const [testingConnection, setTestingConnection] = useState(false);+ const enabled = settings.enabled || false;++ const handleTestConnection = async () => {+ setTestingConnection(true);+ try {+ await apiClient.get("/api/v1/ai/health");+ alert({+ alertType: "success",+ title: t(+ "admin.settings.ai.general.test.okTitle",+ "AI engine reachable",+ ),+ body: t(+ "admin.settings.ai.general.test.okBody",+ "The AI engine responded to a health check.",+ ),+ });+ } catch (error) {+ const detail =+ (error as { response?: { data?: { message?: string } } })?.response+ ?.data?.message ||+ t(+ "admin.settings.ai.general.test.failBody",+ "The AI engine did not respond. Check the URL, that the engine container is running, and that AI is enabled (a restart is needed after enabling).",+ );+ alert({+ alertType: "error",+ title: t(+ "admin.settings.ai.general.test.failTitle",+ "AI engine unreachable",+ ),+ body: detail,+ });+ } finally {+ setTestingConnection(false);+ }+ };++ return (+ <>+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <div>+ <Text fw={500} size="sm">+ {t("admin.settings.ai.general.enabled.label", "Enable AI")}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.enabled.description",+ "Master switch. When off, no AI tools, agents, or engine calls are available.",+ )}+ />+ </Text>+ </div>+ <Group gap="xs">+ <Switch+ checked={enabled}+ onChange={(e) =>+ setSettings({ ...settings, enabled: e.target.checked })+ }+ aria-label={t(+ "admin.settings.ai.general.enabled.label",+ "Enable AI",+ )}+ />+ <PendingBadge show={isFieldPending("enabled")} />+ </Group>+ </Group>++ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.ai.general.url.label", "AI engine URL")}+ </span>+ <PendingBadge show={isFieldPending("url")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.url.description",+ "Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001.",+ )}+ />+ </Group>+ }+ value={settings.url || ""}+ onChange={(e) => setSettings({ ...settings, url: e.target.value })}+ placeholder="http://stirling-pdf-engine:5001"+ disabled={!enabled}+ />++ <Group justify="flex-end">+ <Button+ variant="secondary"+ size="sm"+ loading={testingConnection}+ onClick={handleTestConnection}+ >+ {t("admin.settings.ai.general.test.button", "Test connection")}+ </Button>+ </Group>++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.general.timeoutSeconds.label",+ "Request timeout (seconds)",+ )}+ </span>+ <PendingBadge show={isFieldPending("timeoutSeconds")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.timeoutSeconds.description",+ "Timeout for standard AI requests to the engine.",+ )}+ />+ </Group>+ }+ value={settings.timeoutSeconds ?? 0}+ onChange={(value) =>+ setSettings({ ...settings, timeoutSeconds: Number(value) })+ }+ min={1}+ disabled={!enabled}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.general.longRunningTimeoutSeconds.label",+ "Long-running timeout (seconds)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("longRunningTimeoutSeconds")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.longRunningTimeoutSeconds.description",+ "Timeout for heavier agent operations such as document generation.",+ )}+ />+ </Group>+ }+ value={settings.longRunningTimeoutSeconds ?? 0}+ onChange={(value) =>+ setSettings({+ ...settings,+ longRunningTimeoutSeconds: Number(value),+ })+ }+ min={1}+ disabled={!enabled}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.general.streamTimeoutSeconds.label",+ "Stream timeout (seconds)",+ )}+ </span>+ <PendingBadge show={isFieldPending("streamTimeoutSeconds")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.streamTimeoutSeconds.description",+ "Timeout for streamed (token-by-token) chat responses.",+ )}+ />+ </Group>+ }+ value={settings.streamTimeoutSeconds ?? 0}+ onChange={(value) =>+ setSettings({+ ...settings,+ streamTimeoutSeconds: Number(value),+ })+ }+ min={1}+ disabled={!enabled}+ />+ </Stack>+ </Paper>++ <Alert+ variant="light"+ color="blue"+ title={t("admin.settings.ai.general.note.title", "About the AI engine")}+ icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}+ >+ <Text size="xs">+ {t(+ "admin.settings.ai.general.note.body",+ "The AI engine runs as a separate service. Its shared secret",+ )}{" "}+ <Code>STIRLING_ENGINE_SHARED_SECRET</Code>{" "}+ {t(+ "admin.settings.ai.general.note.body2",+ "is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved.",+ )}+ </Text>+ </Alert>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiDocumentsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiDocumentsCard.tsxnew file mode 100644index 0000000000..e992e8338e--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiDocumentsCard.tsx@@ -0,0 +1,278 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import {+ TextInput,+ NumberInput,+ PasswordInput,+ Autocomplete,+ Select,+ Stack,+ Paper,+ Text,+ Group,+ Alert,+} from "@mantine/core";+import LocalIcon from "@app/components/shared/LocalIcon";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import {+ AiEngineRag,+ EMBEDDING_MODEL_SUGGESTIONS,+ MASKED_SECRET,+} from "@app/components/shared/config/configSections/aiEngineSettings";+import type { AiCardProps } from "@app/components/shared/config/configSections/ai/aiCardProps";++interface AiDocumentsCardProps extends AiCardProps {+ /** The picked embedding model differs from the one the server indexed with. */+ embeddingModelChanged: boolean;+ embeddingApiKeyDirty: boolean;+ setEmbeddingApiKeyDirty: (dirty: boolean) => void;+}++/** Embeddings and retrieval. Changing the embedding model needs a re-index. */+export function AiDocumentsCard({+ settings,+ setSettings,+ isFieldPending,+ embeddingApiKeyDirty,+ embeddingModelChanged,+ setEmbeddingApiKeyDirty,+}: AiDocumentsCardProps) {+ const { t } = useTranslation();++ const setRag = (patch: Partial<AiEngineRag>) =>+ setSettings({ ...settings, rag: { ...(settings.rag || {}), ...patch } });+ const embeddingProvider = settings.rag?.embeddingProvider || "voyageai";+ const showEmbeddingApiKey = embeddingProvider !== "ollama";+ const showEmbeddingBaseUrl =+ embeddingProvider === "ollama" || embeddingProvider === "custom";+ const embeddingApiKeyLabel =+ embeddingProvider === "voyageai"+ ? t(+ "admin.settings.ai.documents.embeddingApiKey.voyageai",+ "VoyageAI API key",+ )+ : embeddingProvider === "openai"+ ? t(+ "admin.settings.ai.documents.embeddingApiKey.openai",+ "OpenAI API key",+ )+ : t(+ "admin.settings.ai.documents.embeddingApiKey.generic",+ "Embedding API key",+ );+ const embeddingSuggestions =+ EMBEDDING_MODEL_SUGGESTIONS[embeddingProvider] || [];+ const embeddingApiKeyPlaceholder =+ embeddingProvider === "voyageai"+ ? "pa-..."+ : embeddingProvider === "openai"+ ? "sk-..."+ : "";++ return (+ <>+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Select+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.documents.embeddingProvider.label",+ "Embedding provider",+ )}+ </span>+ <PendingBadge show={isFieldPending("rag.embeddingProvider")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.documents.embeddingProvider.description",+ "Provider used to turn document text into vector embeddings.",+ )}+ />+ </Group>+ }+ data={[+ { value: "voyageai", label: "VoyageAI" },+ { value: "openai", label: "OpenAI" },+ { value: "ollama", label: "Ollama" },+ { value: "custom", label: "Custom (OpenAI-compatible)" },+ ]}+ value={embeddingProvider}+ onChange={(v) => {+ const next = v || "voyageai";+ const patch: Partial<AiEngineRag> = { embeddingProvider: next };+ // Clear fields the new provider doesn't use so a stale hidden value can't+ // leak into the payload.+ if (next !== "ollama" && next !== "custom")+ patch.embeddingBaseUrl = "";+ if (next !== embeddingProvider) {+ // One stored key, issued for one provider: carrying it across a switch+ // would 401 while the field still read "Saved". Require a re-entry.+ patch.embeddingApiKey = "";+ setEmbeddingApiKeyDirty(true);+ }+ setRag(patch);+ }}+ allowDeselect={false}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />++ <Autocomplete+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.documents.embeddingModel.label",+ "Embedding model",+ )}+ </span>+ <PendingBadge show={isFieldPending("rag.embeddingModel")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.documents.embeddingModel.description",+ "Embedding model name. Free text; suggestions are hints only.",+ )}+ />+ </Group>+ }+ data={embeddingSuggestions}+ value={settings.rag?.embeddingModel || ""}+ onChange={(value) => setRag({ embeddingModel: value })}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />++ {showEmbeddingApiKey && (+ <PasswordInput+ label={+ <Group gap="xs">+ <span>{embeddingApiKeyLabel}</span>+ <PendingBadge show={isFieldPending("rag.embeddingApiKey")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.documents.embeddingApiKey.description",+ "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments.",+ )}+ />+ </Group>+ }+ // Blank when a key is already stored (returned masked as "********") so+ // appending to the sentinel can't corrupt the saved key.+ value={+ embeddingApiKeyDirty+ ? (settings.rag?.embeddingApiKey ?? "")+ : ""+ }+ onChange={(e) => {+ setEmbeddingApiKeyDirty(true);+ setRag({ embeddingApiKey: e.target.value });+ }}+ placeholder={+ !embeddingApiKeyDirty &&+ settings.rag?.embeddingApiKey === MASKED_SECRET+ ? t(+ "admin.settings.ai.documents.embeddingApiKey.setPlaceholder",+ "Saved - leave blank to keep the current key",+ )+ : embeddingApiKeyPlaceholder+ }+ />+ )}++ {showEmbeddingBaseUrl && (+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.documents.embeddingBaseUrl.label",+ "Embedding base URL",+ )}+ </span>+ <PendingBadge show={isFieldPending("rag.embeddingBaseUrl")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.documents.embeddingBaseUrl.description",+ "Base URL of the OpenAI-compatible / Ollama embeddings endpoint, e.g. http://ollama:11434/v1. Must point at a trusted internal endpoint (SSRF-sensitive).",+ )}+ />+ </Group>+ }+ value={settings.rag?.embeddingBaseUrl || ""}+ onChange={(e) => setRag({ embeddingBaseUrl: e.target.value })}+ placeholder="http://ollama:11434/v1"+ />+ )}++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.ai.documents.topK.label", "Top K")}+ </span>+ <PendingBadge show={isFieldPending("rag.topK")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.documents.topK.description",+ "Number of most-relevant chunks retrieved per search.",+ )}+ />+ </Group>+ }+ value={settings.rag?.topK ?? 0}+ onChange={(value) => setRag({ topK: Number(value) })}+ min={1}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.documents.maxSearches.label",+ "Max searches",+ )}+ </span>+ <PendingBadge show={isFieldPending("rag.maxSearches")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.documents.maxSearches.description",+ "Maximum number of retrieval searches the agent may run per request.",+ )}+ />+ </Group>+ }+ value={settings.rag?.maxSearches ?? 0}+ onChange={(value) => setRag({ maxSearches: Number(value) })}+ min={0}+ />+ </Stack>+ </Paper>++ {embeddingModelChanged && (+ <Alert+ variant="light"+ color="orange"+ title={t(+ "admin.settings.ai.documents.reindexNote.title",+ "Re-index required",+ )}+ icon={<LocalIcon icon="warning-rounded" width="1rem" height="1rem" />}+ >+ <Text size="xs">+ {t(+ "admin.settings.ai.documents.reindexNote.body",+ "You changed the embedding model. Documents indexed with the previous model must be re-indexed for search to return correct results.",+ )}+ </Text>+ </Alert>+ )}+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiLimitsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiLimitsCard.tsxnew file mode 100644index 0000000000..a7f41b392a--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiLimitsCard.tsx@@ -0,0 +1,100 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { NumberInput, Stack, Paper, Group } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import type { AiEngineLimits } from "@app/components/shared/config/configSections/aiEngineSettings";+import type { AiCardProps } from "@app/components/shared/config/configSections/ai/aiCardProps";++/** Guardrails on request size and concurrency. Pushed to the engine live. */+export function AiLimitsCard({+ settings,+ setSettings,+ isFieldPending,+}: AiCardProps) {+ const { t } = useTranslation();++ const setLimits = (patch: Partial<AiEngineLimits>) =>+ setSettings({+ ...settings,+ limits: { ...(settings.limits || {}), ...patch },+ });++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.limits.maxPages.label",+ "Max pages per request",+ )}+ </span>+ <PendingBadge show={isFieldPending("limits.maxPages")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.limits.maxPages.description",+ "Guardrail: reject AI requests over this many PDF pages.",+ )}+ />+ </Group>+ }+ value={settings.limits?.maxPages ?? 0}+ onChange={(value) => setLimits({ maxPages: Number(value) })}+ min={1}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.limits.maxCharacters.label",+ "Max characters per request",+ )}+ </span>+ <PendingBadge show={isFieldPending("limits.maxCharacters")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.limits.maxCharacters.description",+ "Guardrail: reject AI requests whose extracted text exceeds this length.",+ )}+ />+ </Group>+ }+ value={settings.limits?.maxCharacters ?? 0}+ onChange={(value) => setLimits({ maxCharacters: Number(value) })}+ min={1}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.limits.modelMaxConcurrency.label",+ "Model max concurrency",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("limits.modelMaxConcurrency")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.ai.limits.modelMaxConcurrency.description",+ "Maximum simultaneous in-flight model calls across the whole engine.",+ )}+ />+ </Group>+ }+ value={settings.limits?.modelMaxConcurrency ?? 0}+ onChange={(value) =>+ setLimits({ modelMaxConcurrency: Number(value) })+ }+ min={1}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiModelsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiModelsCard.tsxnew file mode 100644index 0000000000..2ccdc9dcab--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiModelsCard.tsx@@ -0,0 +1,300 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import {+ TextInput,+ NumberInput,+ PasswordInput,+ Autocomplete,+ Select,+ Stack,+ Paper,+ Text,+ Group,+ Alert,+} from "@mantine/core";+import LocalIcon from "@app/components/shared/LocalIcon";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import {+ AiEngineModels,+ MODEL_SUGGESTIONS,+ MASKED_SECRET,+} from "@app/components/shared/config/configSections/aiEngineSettings";+import type { AiCardProps } from "@app/components/shared/config/configSections/ai/aiCardProps";++interface AiModelsCardProps extends AiCardProps {+ apiKeyDirty: boolean;+ setApiKeyDirty: (dirty: boolean) => void;+}++/** Chat models and the provider credential behind them. Pushed to the engine live. */+export function AiModelsCard({+ settings,+ setSettings,+ isFieldPending,+ apiKeyDirty,+ setApiKeyDirty,+}: AiModelsCardProps) {+ const { t } = useTranslation();++ const setModels = (patch: Partial<AiEngineModels>) =>+ setSettings({+ ...settings,+ models: { ...(settings.models || {}), ...patch },+ });+ const provider = settings.models?.provider || "anthropic";+ const showApiKey = provider !== "ollama";+ const showBaseUrl = provider === "ollama" || provider === "custom";+ const apiKeyLabel =+ provider === "anthropic"+ ? t("admin.settings.ai.models.apiKey.anthropic", "Anthropic API key")+ : provider === "openai"+ ? t("admin.settings.ai.models.apiKey.openai", "OpenAI API key")+ : t("admin.settings.ai.models.apiKey.generic", "API key");+ const modelSuggestions = MODEL_SUGGESTIONS[provider] || [];+ const apiKeyPlaceholder =+ provider === "anthropic"+ ? "sk-ant-..."+ : provider === "openai"+ ? "sk-..."+ : "";++ return (+ <>+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Select+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.ai.models.provider.label", "Provider")}+ </span>+ <PendingBadge show={isFieldPending("models.provider")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.provider.description",+ "Which LLM provider the engine talks to.",+ )}+ />+ </Group>+ }+ data={[+ { value: "anthropic", label: "Anthropic" },+ { value: "openai", label: "OpenAI" },+ { value: "ollama", label: "Ollama" },+ { value: "custom", label: "Custom (OpenAI-compatible)" },+ ]}+ value={provider}+ onChange={(v) => {+ const next = v || "anthropic";+ const patch: Partial<AiEngineModels> = { provider: next };+ // Clear fields the new provider doesn't use so a stale hidden value can't+ // leak into the payload (e.g. an Ollama base URL after switching to Anthropic).+ if (next !== "ollama" && next !== "custom") patch.baseUrl = "";+ if (next !== provider) {+ // Only one key is stored and it belongs to its provider; carrying it across a+ // switch would 401 every call while the field still read "Saved", so clear it.+ patch.apiKey = "";+ setApiKeyDirty(true);+ }+ setModels(patch);+ }}+ allowDeselect={false}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />++ <Autocomplete+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.models.smartModel.label",+ "Smart model",+ )}+ </span>+ <PendingBadge show={isFieldPending("models.smartModel")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.smartModel.description",+ "High-capability model for complex reasoning. Free text; suggestions are hints only.",+ )}+ />+ </Group>+ }+ data={modelSuggestions}+ value={settings.models?.smartModel || ""}+ onChange={(value) => setModels({ smartModel: value })}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />++ <Autocomplete+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.ai.models.fastModel.label", "Fast model")}+ </span>+ <PendingBadge show={isFieldPending("models.fastModel")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.fastModel.description",+ "Cheaper, faster model for lightweight tasks. Free text; suggestions are hints only.",+ )}+ />+ </Group>+ }+ data={modelSuggestions}+ value={settings.models?.fastModel || ""}+ onChange={(value) => setModels({ fastModel: value })}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.models.smartMaxTokens.label",+ "Smart model max tokens",+ )}+ </span>+ <PendingBadge show={isFieldPending("models.smartMaxTokens")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.smartMaxTokens.description",+ "Maximum output tokens for the smart model.",+ )}+ />+ </Group>+ }+ value={settings.models?.smartMaxTokens ?? 0}+ onChange={(value) => setModels({ smartMaxTokens: Number(value) })}+ min={1}+ />++ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.models.fastMaxTokens.label",+ "Fast model max tokens",+ )}+ </span>+ <PendingBadge show={isFieldPending("models.fastMaxTokens")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.fastMaxTokens.description",+ "Maximum output tokens for the fast model.",+ )}+ />+ </Group>+ }+ value={settings.models?.fastMaxTokens ?? 0}+ onChange={(value) => setModels({ fastMaxTokens: Number(value) })}+ min={1}+ />++ {showApiKey && (+ <PasswordInput+ label={+ <Group gap="xs">+ <span>{apiKeyLabel}</span>+ <PendingBadge show={isFieldPending("models.apiKey")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.apiKey.description",+ "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments.",+ )}+ />+ </Group>+ }+ // Keep the field blank when a key is already stored (returned masked as "********");+ // a pre-filled sentinel would corrupt the key on append, so bind the real value only once typed.+ value={apiKeyDirty ? (settings.models?.apiKey ?? "") : ""}+ onChange={(e) => {+ setApiKeyDirty(true);+ setModels({ apiKey: e.target.value });+ }}+ placeholder={+ !apiKeyDirty && settings.models?.apiKey === MASKED_SECRET+ ? t(+ "admin.settings.ai.models.apiKey.setPlaceholder",+ "Saved - leave blank to keep the current key",+ )+ : apiKeyPlaceholder+ }+ />+ )}++ {showBaseUrl && (+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.models.baseUrl.label",+ "Provider base URL",+ )}+ </span>+ <PendingBadge show={isFieldPending("models.baseUrl")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.models.baseUrl.description",+ "Base URL of the OpenAI-compatible / Ollama endpoint, e.g. http://ollama:11434/v1.",+ )}+ />+ </Group>+ }+ value={settings.models?.baseUrl || ""}+ onChange={(e) => setModels({ baseUrl: e.target.value })}+ placeholder="http://ollama:11434/v1"+ />+ )}++ {showBaseUrl && (+ <Alert+ variant="light"+ color="orange"+ icon={+ <LocalIcon icon="warning-rounded" width="1rem" height="1rem" />+ }+ >+ <Text size="xs">+ {t(+ "admin.settings.ai.models.baseUrl.warning",+ "The base URL must point at a trusted internal endpoint. The engine will make server-side requests to it, so an untrusted value is SSRF-sensitive.",+ )}+ </Text>+ </Alert>+ )}++ {showBaseUrl && (+ <Alert+ variant="light"+ color="blue"+ icon={+ <LocalIcon icon="info-rounded" width="1rem" height="1rem" />+ }+ >+ <Text size="xs">+ {t(+ "admin.settings.ai.models.baseUrl.contextWindow",+ "Use a context window of at least 16,384 tokens. Smaller windows silently drop part of the prompt. Ollama defaults to 4,096 - raise OLLAMA_CONTEXT_LENGTH.",+ )}+ </Text>+ </Alert>+ )}+ </Stack>+ </Paper>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/aiCardProps.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/aiCardProps.tsnew file mode 100644index 0000000000..aa07e2d258--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/aiCardProps.ts@@ -0,0 +1,15 @@+import type { AiEngineSettingsData } from "@app/components/shared/config/configSections/aiEngineSettings";++/**+ * What every AI card needs from the page that owns them. The four AI sections+ * were one `aiEngine` object split across four rows, so the merged page keeps a+ * single draft and hands each card a slice of it rather than letting each card+ * fetch and save on its own.+ */+export interface AiCardProps {+ settings: AiEngineSettingsData;+ setSettings: (next: AiEngineSettingsData) => void;+ /** True while the backend still lists this key as awaiting a restart. */+ isFieldPending: (field: string) => boolean;+ loginEnabled: boolean;+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsxindex 1b19656b16..0b88820d9d 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsx@@ -1,4 +1,6 @@import React, { useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { SettingsFieldLabel } from "@app/components/shared/config/SettingsFieldLabel";import {Collapse,Alert,@@ -264,11 +266,16 @@ const LicenseKeySection: React.FC<LicenseKeySectionProps> = ({{inputMethod === "text" ? (/* Text input */<TextInput- label={t("admin.settings.premium.key.label", "License Key")}- description={t(- "admin.settings.premium.key.description",- "Enter your premium or enterprise license key. Premium features will be automatically enabled when a key is provided.",- )}+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.premium.key.description",+ "Enter your premium or enterprise license key. Premium features will be automatically enabled when a key is provided.",+ )}+ >+ {t("admin.settings.premium.key.label", "License Key")}+ </SettingsFieldLabel>+ }value={licenseKeyInput}onChange={(e) => setLicenseKeyInput(e.target.value)}placeholder={@@ -285,13 +292,13 @@ const LicenseKeySection: React.FC<LicenseKeySectionProps> = ({{t("admin.settings.premium.file.label","License Certificate File",- )}- </Text>- <Text size="xs" c="dimmed" mb="md">- {t(- "admin.settings.premium.file.description",- "Upload your .lic or .cert license file",- )}+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.premium.file.description",+ "Upload your .lic or .cert license file",+ )}+ /></Text><FilePickeronChange={setLicenseFile}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/plan/StaticCheckoutModal.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/plan/StaticCheckoutModal.tsxindex 05c0e0ec7f..8667d4800a 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/plan/StaticCheckoutModal.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/plan/StaticCheckoutModal.tsx@@ -1,4 +1,5 @@import React, { useState } from "react";+import { SettingsFieldLabel } from "@app/components/shared/config/SettingsFieldLabel";import {Modal,Text,@@ -300,11 +301,16 @@ const StaticCheckoutModal: React.FC<StaticCheckoutModalProps> = ({</Text><TextInput- label={t("admin.settings.premium.key.label", "License Key")}- description={t(- "plan.static.licenseActivation.keyDescription",- "Paste the license key from your email",- )}+ label={+ <SettingsFieldLabel+ info={t(+ "plan.static.licenseActivation.keyDescription",+ "Paste the license key from your email",+ )}+ >+ {t("admin.settings.premium.key.label", "License Key")}+ </SettingsFieldLabel>+ }value={licenseKey}onChange={(e) => setLicenseKey(e.target.value)}placeholder="00000000-0000-0000-0000-000000000000"diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminIntegrationsPage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminIntegrationsPage.tsxnew file mode 100644index 0000000000..2a9e46864a--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminIntegrationsPage.tsx@@ -0,0 +1,217 @@+import { useCallback, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { Stack, Loader } from "@mantine/core";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import apiClient from "@app/services/apiClient";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type { ConnectionsSettingsData } from "@app/components/shared/config/configSections/security/securitySettingsTypes";+import {+ fetchConnectionsSettings,+ saveConnectionsSettings,+} from "@app/components/shared/config/configSections/security/securitySettingsTransformers";+import { useConnectionProviders } from "@app/components/shared/config/configSections/security/connectionProviders";+import { LinkedServicesCard } from "@app/components/shared/config/configSections/security/LinkedServicesCard";+import { UnlinkedServicesCard } from "@app/components/shared/config/configSections/security/UnlinkedServicesCard";+import { MobileUploadQrCard } from "@app/components/shared/config/configSections/security/MobileUploadQrCard";+import { McpCard } from "@app/components/shared/config/configSections/server/McpCard";+import type { McpSettingsData } from "@app/components/shared/config/configSections/server/serverSettings";+import "@app/components/shared/config/configSections/security/AdminSecurityPage.css";++/**+ * The services this server talks to: mail, Telegram, Drive, and the phone that+ * uploads by QR. Sign-in providers live on the security page instead - these+ * are wiring, not authentication, and lumping them together made "Single+ * sign-on" the page you had to visit to configure SMTP.+ *+ * Shares the `connections` section with the security page, which is safe+ * because only one settings section is mounted at a time.+ */+export default function AdminIntegrationsPage() {+ const { t } = useTranslation();+ const { loginEnabled, validateLoginEnabled, getDisabledStyles } =+ useLoginRequired();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();++ const connections = useAdminSettings<ConnectionsSettingsData>({+ sectionName: "connections",+ enabled: loginEnabled,+ fetchTransformer: fetchConnectionsSettings,+ saveTransformer: saveConnectionsSettings,+ });++ const {+ settings: mcp,+ setSettings: setMcp,+ loading: mcpLoading,+ saving: mcpSaving,+ saveSettings: saveMcp,+ isFieldPending: isMcpFieldPending,+ } = useAdminSettings<McpSettingsData>({+ sectionName: "mcp",+ // The standalone MCP row passed no `enabled` and fetched with login off. It+ // has to gate like its neighbours now, or its late arrival reads as an edit.+ enabled: loginEnabled,+ fetchTransformer: async (): Promise<+ McpSettingsData & { _pending?: Partial<McpSettingsData> }+ > => {+ const response = await apiClient.get<+ McpSettingsData & { _pending?: Partial<McpSettingsData> }+ >("/api/v1/admin/settings/section/mcp");+ return response.data || {};+ },+ // Save nested auth.* keys as dot-notation through the root endpoint so siblings are preserved.+ saveTransformer: (s: McpSettingsData) => ({+ sectionData: {},+ deltaSettings: {+ "mcp.enabled": s.enabled ?? false,+ "mcp.scopesEnabled": s.scopesEnabled ?? true,+ "mcp.allowedOperations": s.allowedOperations ?? [],+ "mcp.blockedOperations": s.blockedOperations ?? [],+ "mcp.auth.mode": s.auth?.mode ?? "oauth",+ "mcp.auth.issuerUri": s.auth?.issuerUri ?? "",+ "mcp.auth.jwksUri": s.auth?.jwksUri ?? "",+ "mcp.auth.resourceId": s.auth?.resourceId ?? "",+ "mcp.auth.acceptedAudiences": s.auth?.acceptedAudiences ?? [],+ "mcp.auth.usernameClaim": s.auth?.usernameClaim ?? "sub",+ "mcp.auth.requireExistingAccount":+ s.auth?.requireExistingAccount ?? true,+ },+ }),+ });++ // A disabled fetch reports loading forever, so the ternary decides it.+ const loading = loginEnabled ? connections.loading || mcpLoading : false;+ const draft = useMemo(+ () => ({ connections: connections.settings, mcp }),+ [connections.settings, mcp],+ );+ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ draft,+ loading,+ );++ const { linkedProviders, availableProviders } = useConnectionProviders(+ connections.settings,+ "integration",+ );++ const handleSave = async () => {+ if (!validateLoginEnabled()) return;+ try {+ // Sequential, not Promise.all: both PUT the same flat settings endpoint.+ await connections.saveSettings();+ await saveMcp();+ markSaved();+ showRestartModal();+ } catch (_error) {+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ }+ };++ const handleDiscard = useCallback(() => {+ const original = resetToSnapshot();+ connections.setSettings(original.connections);+ setMcp(original.mcp);+ }, [resetToSnapshot, connections.setSettings, setMcp]);++ if (loading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ const card = {+ settings: connections.settings,+ setSettings: connections.setSettings,+ isFieldPending: connections.isFieldPending,+ loginEnabled,+ getDisabledStyles,+ };++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminConnections"+ title={t(+ "admin.settings.connections.linkedServices",+ "Connected services",+ )}+ description={t(+ "admin.settings.connections.connectedServicesDescription",+ "Services this server is wired up to. Sign-in providers live under Sign-in & security.",+ )}+ >+ <LinkedServicesCard {...card} providers={linkedProviders} />+ </SettingsCard>++ <SettingsCard+ id="integrationsAvailable"+ title={t(+ "admin.settings.connections.unlinkedServices",+ "Available services",+ )}+ >+ <UnlinkedServicesCard {...card} providers={availableProviders} />+ </SettingsCard>++ <SettingsCard+ id="connectionsMobileScanner"+ title={t(+ "admin.settings.connections.mobileScanner.label",+ "Mobile upload",+ )}+ >+ <MobileUploadQrCard {...card} />+ </SettingsCard>++ <SettingsCard+ id="adminMcp"+ title={t("settings.configuration.mcp", "MCP Server")}+ description={t(+ "admin.settings.mcp.description",+ "Expose this server's tools to MCP clients, and choose which ones.",+ )}+ >+ <McpCard+ settings={mcp}+ setSettings={setMcp}+ isFieldPending={isMcpFieldPending}+ loginEnabled={loginEnabled}+ />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={connections.saving || mcpSaving}+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminLegalPrivacyPage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminLegalPrivacyPage.tsxnew file mode 100644index 0000000000..998a9469f9--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminLegalPrivacyPage.tsx@@ -0,0 +1,183 @@+import { useCallback, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { Stack, Loader } from "@mantine/core";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type {+ LegalSettingsData,+ PrivacySettingsData,+} from "@app/components/shared/config/configSections/security/securitySettingsTypes";+import {+ fetchPrivacySettings,+ saveLegalSettings,+ savePrivacySettings,+} from "@app/components/shared/config/configSections/security/securitySettingsTransformers";+import { LegalDocumentsCard } from "@app/components/shared/config/configSections/security/LegalDocumentsCard";+import { LoginAgreementCard } from "@app/components/shared/config/configSections/security/LoginAgreementCard";+import { AnalyticsTrackingCard } from "@app/components/shared/config/configSections/security/AnalyticsTrackingCard";+import { SearchEngineVisibilityCard } from "@app/components/shared/config/configSections/security/SearchEngineVisibilityCard";+import "@app/components/shared/config/configSections/security/AdminSecurityPage.css";++/**+ * What this deployment tells the world about itself: the documents people are+ * shown, whether it reports usage, and whether search engines may index it.+ * None of it governs who may sign in, which is why it is not on that page.+ */+export default function AdminLegalPrivacyPage() {+ const { t } = useTranslation();+ const { loginEnabled, validateLoginEnabled, getDisabledStyles } =+ useLoginRequired();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();++ const privacy = useAdminSettings<PrivacySettingsData>({+ sectionName: "privacy",+ enabled: loginEnabled,+ fetchTransformer: fetchPrivacySettings,+ saveTransformer: savePrivacySettings,+ });+ const legal = useAdminSettings<LegalSettingsData>({+ sectionName: "legal",+ enabled: loginEnabled,+ saveTransformer: saveLegalSettings,+ });++ // A disabled sub-fetch reports loading forever, so the ternary decides it.+ const loading = loginEnabled ? privacy.loading || legal.loading : false;++ const draft = useMemo(+ () => ({ privacy: privacy.settings, legal: legal.settings }),+ [privacy.settings, legal.settings],+ );+ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ draft,+ loading,+ );++ const handleSave = async () => {+ if (!validateLoginEnabled()) return;+ const results: PromiseSettledResult<void>[] = [];+ for (const save of [privacy.saveSettings, legal.saveSettings]) {+ // Sequential, not Promise.all: both PUT the same flat settings endpoint.+ const [result] = await Promise.allSettled([save()]);+ results.push(result);+ }+ if (results.some((r) => r.status === "rejected")) {+ // No markSaved on a partial failure, or the footer clears while a draft+ // that never reached the server is still on screen.+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ return;+ }+ markSaved();+ showRestartModal();+ };++ const handleDiscard = useCallback(() => {+ const original = resetToSnapshot();+ privacy.setSettings(original.privacy);+ legal.setSettings(original.legal);+ }, [resetToSnapshot, privacy.setSettings, legal.setSettings]);++ if (loading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ const privacyCard = {+ settings: privacy.settings,+ setSettings: privacy.setSettings,+ isFieldPending: privacy.isFieldPending,+ loginEnabled,+ getDisabledStyles,+ };+ const legalCard = {+ settings: legal.settings,+ setSettings: legal.setSettings,+ isFieldPending: legal.isFieldPending,+ loginEnabled,+ getDisabledStyles,+ };++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminLegal"+ title={t("settings.policiesPrivacy.legal", "Legal documents")}+ description={t(+ "admin.settings.legal.documentsDescription",+ "Links users are shown for terms, privacy, cookies and the impressum.",+ )}+ >+ <LegalDocumentsCard {...legalCard} />+ </SettingsCard>++ <SettingsCard+ id="legalLoginAgreement"+ title={t(+ "admin.settings.legal.loginAgreement.title",+ "Login agreement",+ )}+ description={t(+ "admin.settings.legal.loginAgreement.description",+ "Show a disclaimer users must accept after logging in. The text follows each user's language.",+ )}+ >+ <LoginAgreementCard {...legalCard} />+ </SettingsCard>++ <SettingsCard+ id="adminPrivacy"+ title={t("admin.settings.privacy.analytics", "Analytics & Tracking")}+ description={t(+ "admin.settings.privacy.description",+ "What this server discloses about itself, and what it reports.",+ )}+ >+ <AnalyticsTrackingCard {...privacyCard} />+ </SettingsCard>++ <SettingsCard+ id="privacySearchEngine"+ title={t(+ "admin.settings.privacy.searchEngine",+ "Search engine visibility",+ )}+ >+ <SearchEngineVisibilityCard {...privacyCard} />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={privacy.saving || legal.saving}+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.css b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.cssnew file mode 100644index 0000000000..afa2f15d2e--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.css@@ -0,0 +1,21 @@+.admin-security__card {+ display: flex;+ flex-direction: column;+ gap: var(--space-3, 0.75rem);+}++/* Permanent, not just during the focus pulse: an anchored jump would otherwise+ land the heading under the sticky search bar. */+.admin-security__heading {+ margin: 0;+ scroll-margin-top: 1rem;+ font-size: 0.9375rem;+ font-weight: var(--font-weight-semibold, 600);+ color: var(--c-text);+}++.admin-security__description {+ margin: -0.35rem 0 0;+ font-size: 0.8125rem;+ color: var(--c-text-subtle);+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsxnew file mode 100644index 0000000000..e65532aa13--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx@@ -0,0 +1,264 @@+import { useCallback, useEffect, useMemo } from "react";+import { TierBadge } from "@app/components/shared/config/TierBadge";+import { useLocation } from "react-router-dom";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { Stack, Loader } from "@mantine/core";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type {+ ConnectionsSettingsData,+ SecuritySettingsData,+} from "@app/components/shared/config/configSections/security/securitySettingsTypes";+import {+ fetchConnectionsSettings,+ fetchSecuritySettings,+ saveConnectionsSettings,+ saveSecuritySettings,+} from "@app/components/shared/config/configSections/security/securitySettingsTransformers";+import { useConnectionProviders } from "@app/components/shared/config/configSections/security/connectionProviders";+import { AuthenticationCard } from "@app/components/shared/config/configSections/security/AuthenticationCard";+import { SessionsJwtCard } from "@app/components/shared/config/configSections/security/SessionsJwtCard";+import { LinkedServicesCard } from "@app/components/shared/config/configSections/security/LinkedServicesCard";+import { UnlinkedServicesCard } from "@app/components/shared/config/configSections/security/UnlinkedServicesCard";+import { SsoAutoLoginCard } from "@app/components/shared/config/configSections/security/SsoAutoLoginCard";+import { HtmlUrlSecurityCard } from "@app/components/shared/config/configSections/security/HtmlUrlSecurityCard";+import { AuditLoggingCard } from "@app/components/shared/config/configSections/security/AuditLoggingCard";+import "@app/components/shared/config/configSections/security/AdminSecurityPage.css";++/**+ * Sign-in and security, previously four nav rows. Unlike the AI fold these are+ * four genuinely different backend sections, so the page keeps four fetches but+ * only one dirty flag, one footer and one save, and each card is handed the+ * slice of the draft its own section owns.+ */+export default function AdminSecurityPage() {+ const { t } = useTranslation();+ const location = useLocation();+ const { loginEnabled, validateLoginEnabled, getDisabledStyles } =+ useLoginRequired();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();++ const security = useAdminSettings<SecuritySettingsData>({+ sectionName: "security",+ enabled: loginEnabled,+ fetchTransformer: fetchSecuritySettings,+ saveTransformer: saveSecuritySettings,+ });++ const connections = useAdminSettings<ConnectionsSettingsData>({+ sectionName: "connections",+ enabled: loginEnabled,+ fetchTransformer: fetchConnectionsSettings,+ saveTransformer: saveConnectionsSettings,+ });++ // A disabled sub-fetch reports loading forever, so the ternary decides it -+ // a blanket OR would freeze the page on a loader when login is off.+ const loading = loginEnabled+ ? security.loading || connections.loading+ : false;++ const draft = useMemo(+ () => ({+ security: security.settings,+ connections: connections.settings,+ }),+ [security.settings, connections.settings],+ );++ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ draft,+ loading,+ );++ // Sign-in providers only; Telegram, Drive and SMTP live on Integrations.+ const { linkedProviders, availableProviders } = useConnectionProviders(+ connections.settings,+ "signin",+ );++ // Deep links land on a card id, so the jump waits for the cards to exist.+ useEffect(() => {+ if (location.hash && !loading) {+ const elementId = location.hash.substring(1); // Remove the #+ const element = document.getElementById(elementId);+ if (element) {+ setTimeout(() => {+ element.scrollIntoView({ behavior: "smooth", block: "start" });+ }, 100);+ }+ }+ }, [location.hash, loading]);++ const handleSave = async () => {+ if (!validateLoginEnabled()) {+ return;+ }++ const results: PromiseSettledResult<void>[] = [];+ for (const save of [security.saveSettings, connections.saveSettings]) {+ // Sequential, not Promise.all: several of these PUT the same flat+ // settings endpoint and would overwrite each other's merge.+ const [result] = await Promise.allSettled([save()]);+ results.push(result);+ }++ if (results.some((result) => result.status === "rejected")) {+ // No markSaved on a partial failure: re-snapshotting would clear the+ // footer while drafts that never reached the server are still on screen.+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ return;+ }++ markSaved();+ showRestartModal();+ };++ const handleDiscard = useCallback(() => {+ const original = resetToSnapshot();+ security.setSettings(original.security);+ connections.setSettings(original.connections);+ }, [resetToSnapshot, security.setSettings, connections.setSettings]);++ if (loading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ const securityCard = {+ settings: security.settings,+ setSettings: security.setSettings,+ isFieldPending: security.isFieldPending,+ loginEnabled,+ getDisabledStyles,+ };+ const connectionsCard = {+ settings: connections.settings,+ setSettings: connections.setSettings,+ isFieldPending: connections.isFieldPending,+ loginEnabled,+ getDisabledStyles,+ };++ // Both services sections are conditional, so the retired nav key rides+ // whichever renders first and #adminConnections still lands.+ const hasLinked = linkedProviders.length > 0;++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="securityAuthentication"+ title={t("admin.settings.security.authentication", "Authentication")}+ >+ <AuthenticationCard {...securityCard} />+ </SettingsCard>++ <SettingsCard+ id="securityJwt"+ title={t("admin.settings.security.jwt.label", "JWT Configuration")}+ >+ <SessionsJwtCard {...securityCard} />+ </SettingsCard>++ {hasLinked && (+ <SettingsCard+ id="adminConnections"+ title={t(+ "admin.settings.connections.linkedServices",+ "Linked Services",+ )}+ >+ <LinkedServicesCard+ {...connectionsCard}+ providers={linkedProviders}+ />+ </SettingsCard>+ )}++ {availableProviders.length > 0 && (+ <section className="admin-security__card">+ <h2+ className="admin-security__heading"+ id={hasLinked ? "connectionsUnlinked" : "adminConnections"}+ >+ {t(+ "admin.settings.connections.unlinkedServices",+ "Unlinked Services",+ )}+ </h2>+ <UnlinkedServicesCard+ {...connectionsCard}+ providers={availableProviders}+ />+ </section>+ )}++ <SettingsCard+ id="connectionsSsoAutoLogin"+ title={t(+ "admin.settings.connections.ssoAutoLogin.label",+ "SSO Auto Login",+ )}+ badge={<TierBadge tier="PRO" />}+ >+ <SsoAutoLoginCard {...connectionsCard} />+ </SettingsCard>++ <SettingsCard+ id="securityHtmlUrl"+ title={t(+ "admin.settings.security.htmlUrlSecurity.label",+ "HTML URL Security",+ )}+ description={t(+ "admin.settings.security.htmlUrlSecurity.description",+ "Configure URL access restrictions for HTML processing to prevent SSRF attacks",+ )}+ >+ <HtmlUrlSecurityCard {...securityCard} />+ </SettingsCard>++ <SettingsCard+ id="auditLogging"+ title={t("admin.settings.security.audit.label", "Audit Logging")}+ badge={<TierBadge tier="ENTERPRISE" />}+ >+ <AuditLoggingCard {...securityCard} />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={security.saving || connections.saving}+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AnalyticsTrackingCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AnalyticsTrackingCard.tsxnew file mode 100644index 0000000000..3a68194a1d--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AnalyticsTrackingCard.tsx@@ -0,0 +1,65 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { Stack, Paper } from "@mantine/core";+import type { PrivacyCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** Anonymous product analytics and the performance metrics endpoint. */+export function AnalyticsTrackingCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+ getDisabledStyles,+}: PrivacyCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.privacy.enableAnalytics.label",+ "Enable Analytics",+ )}+ info={t(+ "admin.settings.privacy.enableAnalytics.description",+ "Collect anonymous usage analytics to help improve the application",+ )}+ pending={isFieldPending("enableAnalytics")}+ checked={settings?.enableAnalytics || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ enableAnalytics: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.privacy.metricsEnabled.label",+ "Enable Metrics",+ )}+ info={t(+ "admin.settings.privacy.metricsEnabled.description",+ "Enable collection of performance and usage metrics",+ )}+ pending={isFieldPending("metricsEnabled")}+ checked={settings?.metricsEnabled || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ metricsEnabled: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AuditLoggingCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AuditLoggingCard.tsxnew file mode 100644index 0000000000..9faefa1f3d--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AuditLoggingCard.tsx@@ -0,0 +1,189 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { NumberInput, Stack, Paper, Group } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import type { SecurityCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** What the audit trail records and how long it is kept. */+export function AuditLoggingCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: SecurityCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.security.audit.enabled.label",+ "Enable Audit Logging",+ )}+ info={t(+ "admin.settings.security.audit.enabled.description",+ "Track user actions and system events for compliance and security monitoring",+ )}+ pending={isFieldPending("audit.enabled")}+ checked={settings?.audit?.enabled || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ audit: { ...settings?.audit, enabled: checked },+ })+ }+ disabled={!loginEnabled}+ />++ <div>+ <NumberInput+ name="audit_level"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.audit.level.label",+ "Audit Level",+ )}+ </span>+ <PendingBadge show={isFieldPending("audit.level")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.audit.level.description",+ "0=OFF, 1=BASIC, 2=STANDARD, 3=VERBOSE",+ )}+ />+ </Group>+ }+ value={settings?.audit?.level || 2}+ onChange={(value) =>+ setSettings({+ ...settings,+ audit: { ...settings?.audit, level: Number(value) },+ })+ }+ min={0}+ max={3}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ name="audit_retentionDays"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.audit.retentionDays.label",+ "Audit Retention (days)",+ )}+ </span>+ <PendingBadge show={isFieldPending("audit.retentionDays")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.audit.retentionDays.description",+ "Number of days to retain audit logs",+ )}+ />+ </Group>+ }+ value={settings?.audit?.retentionDays || 90}+ onChange={(value) =>+ setSettings({+ ...settings,+ audit: { ...settings?.audit, retentionDays: Number(value) },+ })+ }+ min={1}+ max={3650}+ disabled={!loginEnabled}+ />+ </div>++ <SettingsToggleRow+ label={t(+ "admin.settings.security.audit.captureFileHash.label",+ "Capture File Hash",+ )}+ info={t(+ "admin.settings.security.audit.captureFileHash.description",+ "Store MD5 hash of processed files for audit trail verification",+ )}+ pending={isFieldPending("audit.captureFileHash")}+ warnWhenOn={t(+ "admin.settings.security.audit.advancedOptions.cost",+ "Now increasing processing time and memory usage on every operation.",+ )}+ checked={settings?.audit?.captureFileHash || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ audit: {+ ...settings?.audit,+ captureFileHash: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.security.audit.capturePdfAuthor.label",+ "Capture PDF Author",+ )}+ info={t(+ "admin.settings.security.audit.capturePdfAuthor.description",+ "Extract author field from PDF documents during processing",+ )}+ pending={isFieldPending("audit.capturePdfAuthor")}+ warnWhenOn={t(+ "admin.settings.security.audit.advancedOptions.cost",+ "Now increasing processing time and memory usage on every operation.",+ )}+ checked={settings?.audit?.capturePdfAuthor || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ audit: {+ ...settings?.audit,+ capturePdfAuthor: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.security.audit.captureOperationResults.label",+ "Capture Operation Results",+ )}+ info={t(+ "admin.settings.security.audit.captureOperationResults.description",+ "Store output file information and processing results in audit logs",+ )}+ pending={isFieldPending("audit.captureOperationResults")}+ warnWhenOn={t(+ "admin.settings.security.audit.advancedOptions.cost",+ "Now increasing processing time and memory usage on every operation.",+ )}+ checked={settings?.audit?.captureOperationResults || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ audit: {+ ...settings?.audit,+ captureOperationResults: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AuthenticationCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AuthenticationCard.tsxnew file mode 100644index 0000000000..d3d8833e01--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AuthenticationCard.tsx@@ -0,0 +1,216 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { SettingsFieldLabel } from "@app/components/shared/config/SettingsFieldLabel";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { NumberInput, Stack, Paper, Group, Select } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { SecurityCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** Whether login is required at all, and how a failed one is throttled. */+export function AuthenticationCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: SecurityCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t("admin.settings.security.enableLogin.label", "Enable Login")}+ info={t(+ "admin.settings.security.enableLogin.description",+ "Require users to log in before accessing the application",+ )}+ pending={isFieldPending("enableLogin")}+ checked={settings?.enableLogin || false}+ onChange={(checked) =>+ setSettings({ ...settings, enableLogin: checked })+ }+ disabled={!loginEnabled}+ />++ <div>+ <Select+ name="loginMethod"+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.security.loginMethod.description",+ "The authentication method to use for user login",+ )}+ >+ {t("admin.settings.security.loginMethod.label", "Login Method")}+ </SettingsFieldLabel>+ }+ value={settings?.loginMethod || "all"}+ onChange={(value) =>+ setSettings({ ...settings, loginMethod: value || "all" })+ }+ data={[+ {+ value: "all",+ label: t(+ "admin.settings.security.loginMethod.all",+ "All Methods",+ ),+ },+ {+ value: "normal",+ label: t(+ "admin.settings.security.loginMethod.normal",+ "Username/Password Only",+ ),+ },+ {+ value: "oauth2",+ label: t(+ "admin.settings.security.loginMethod.oauth2",+ "OAuth2 Only",+ ),+ },+ {+ value: "saml2",+ label: t(+ "admin.settings.security.loginMethod.saml2",+ "SAML2 Only",+ ),+ },+ ]}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ {isFieldPending("loginMethod") && (+ <Group mt="xs">+ <PendingBadge show={true} />+ </Group>+ )}+ </div>++ <div>+ <NumberInput+ name="loginAttemptCount"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.loginAttemptCount.label",+ "Login Attempt Limit",+ )}+ </span>+ <PendingBadge show={isFieldPending("loginAttemptCount")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.loginAttemptCount.description",+ "Maximum number of failed login attempts before account lockout",+ )}+ />+ </Group>+ }+ value={settings?.loginAttemptCount || 0}+ onChange={(value) =>+ setSettings({ ...settings, loginAttemptCount: Number(value) })+ }+ min={0}+ max={100}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ name="loginResetTimeMinutes"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.loginResetTimeMinutes.label",+ "Login Reset Time (minutes)",+ )}+ </span>+ <PendingBadge show={isFieldPending("loginResetTimeMinutes")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.loginResetTimeMinutes.description",+ "Time before failed login attempts are reset",+ )}+ />+ </Group>+ }+ value={settings?.loginResetTimeMinutes || 0}+ onChange={(value) =>+ setSettings({+ ...settings,+ loginResetTimeMinutes: Number(value),+ })+ }+ min={0}+ max={1440}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <Select+ name="xFrameOptions"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.xFrameOptions.label",+ "X-Frame-Options",+ )}+ </span>+ <PendingBadge show={isFieldPending("xFrameOptions")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.xFrameOptions.description",+ "Controls whether the application can be embedded in iframes",+ )}+ />+ </Group>+ }+ value={settings?.xFrameOptions || "DENY"}+ onChange={(value) =>+ setSettings({ ...settings, xFrameOptions: value || "DENY" })+ }+ data={[+ {+ value: "DENY",+ label: t(+ "admin.settings.security.xFrameOptions.deny",+ "Deny (Prevents all framing)",+ ),+ },+ {+ value: "SAMEORIGIN",+ label: t(+ "admin.settings.security.xFrameOptions.sameorigin",+ "Same Origin (Allow framing from same domain)",+ ),+ },+ {+ value: "DISABLED",+ label: t(+ "admin.settings.security.xFrameOptions.disabled",+ "Disabled (No X-Frame-Options header)",+ ),+ },+ ]}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsxnew file mode 100644index 0000000000..7af0a30f79--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/HtmlUrlSecurityCard.tsx@@ -0,0 +1,409 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import {+ Stack,+ Paper,+ Text,+ Group,+ Select,+ Accordion,+ Textarea,+} from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { SecurityCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** Where HTML-to-PDF conversions are allowed to fetch from (SSRF guard). */+export function HtmlUrlSecurityCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: SecurityCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.security.htmlUrlSecurity.enabled.label",+ "Enable URL Security",+ )}+ info={t(+ "admin.settings.security.htmlUrlSecurity.enabled.description",+ "Enable URL security restrictions for HTML to PDF conversions",+ )}+ pending={isFieldPending("html.urlSecurity.enabled")}+ checked={settings?.html?.urlSecurity?.enabled || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ enabled: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />++ <div>+ <Select+ name="html_urlSecurity_level"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.htmlUrlSecurity.level.label",+ "Security Level",+ )}+ </span>+ <PendingBadge show={isFieldPending("html.urlSecurity.level")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.htmlUrlSecurity.level.description",+ "MAX: whitelist only, MEDIUM: block internal networks, OFF: no restrictions",+ )}+ />+ </Group>+ }+ value={settings?.html?.urlSecurity?.level || "MEDIUM"}+ onChange={(value) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ level: value || "MEDIUM",+ },+ },+ })+ }+ data={[+ {+ value: "MAX",+ label: t(+ "admin.settings.security.htmlUrlSecurity.level.max",+ "Maximum (Whitelist Only)",+ ),+ },+ {+ value: "MEDIUM",+ label: t(+ "admin.settings.security.htmlUrlSecurity.level.medium",+ "Medium (Block Internal)",+ ),+ },+ {+ value: "OFF",+ label: t(+ "admin.settings.security.htmlUrlSecurity.level.off",+ "Off (No Restrictions)",+ ),+ },+ ]}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>++ <Accordion variant="separated">+ <Accordion.Item value="advanced">+ <Accordion.Control>+ {t(+ "admin.settings.security.htmlUrlSecurity.advanced",+ "Advanced Settings",+ )}+ </Accordion.Control>+ <Accordion.Panel>+ <Stack gap="md">+ {/* Allowed Domains */}+ <div>+ <Textarea+ name="html_urlSecurity_allowedDomains"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.htmlUrlSecurity.allowedDomains.label",+ "Allowed Domains (Whitelist)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending(+ "html.urlSecurity.allowedDomains",+ )}+ />+ <InfoTooltip+ label={t(+ "admin.settings.security.htmlUrlSecurity.allowedDomains.description",+ "One domain per line (e.g., cdn.example.com). Only these domains allowed when level is MAX",+ )}+ />+ </Group>+ }+ value={+ settings?.html?.urlSecurity?.allowedDomains?.join("\n") ||+ ""+ }+ onChange={(e) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ allowedDomains: e.target.value+ ? e.target.value+ .split("\n")+ .filter((d) => d.trim())+ : [],+ },+ },+ })+ }+ placeholder="cdn.example.com images.google.com"+ minRows={3}+ autosize+ disabled={!loginEnabled}+ />+ </div>++ {/* Blocked Domains */}+ <div>+ <Textarea+ name="html_urlSecurity_blockedDomains"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.htmlUrlSecurity.blockedDomains.label",+ "Blocked Domains (Blacklist)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending(+ "html.urlSecurity.blockedDomains",+ )}+ />+ <InfoTooltip+ label={t(+ "admin.settings.security.htmlUrlSecurity.blockedDomains.description",+ "One domain per line (e.g., malicious.com). Additional domains to block",+ )}+ />+ </Group>+ }+ value={+ settings?.html?.urlSecurity?.blockedDomains?.join("\n") ||+ ""+ }+ onChange={(e) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ blockedDomains: e.target.value+ ? e.target.value+ .split("\n")+ .filter((d) => d.trim())+ : [],+ },+ },+ })+ }+ placeholder="malicious.com evil.org"+ minRows={3}+ autosize+ disabled={!loginEnabled}+ />+ </div>++ {/* Internal TLDs */}+ <div>+ <Textarea+ name="html_urlSecurity_internalTlds"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.htmlUrlSecurity.internalTlds.label",+ "Internal TLDs",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("html.urlSecurity.internalTlds")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.security.htmlUrlSecurity.internalTlds.description",+ "One TLD per line (e.g., .local, .internal). Block domains with these TLD patterns",+ )}+ />+ </Group>+ }+ value={+ settings?.html?.urlSecurity?.internalTlds?.join("\n") ||+ ""+ }+ onChange={(e) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ internalTlds: e.target.value+ ? e.target.value+ .split("\n")+ .filter((d) => d.trim())+ : [],+ },+ },+ })+ }+ placeholder=".local .internal .corp .home"+ minRows={3}+ autosize+ disabled={!loginEnabled}+ />+ </div>++ {/* Network Blocking Options */}+ <Text fw={600} size="sm" mt="md">+ {t(+ "admin.settings.security.htmlUrlSecurity.networkBlocking",+ "Network Blocking",+ )}+ </Text>++ <SettingsToggleRow+ label={t(+ "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.label",+ "Block Private Networks",+ )}+ info={t(+ "admin.settings.security.htmlUrlSecurity.blockPrivateNetworks.description",+ "Block RFC 1918 private networks (10.x.x.x, 192.168.x.x, 172.16-31.x.x)",+ )}+ pending={isFieldPending(+ "html.urlSecurity.blockPrivateNetworks",+ )}+ checked={+ settings?.html?.urlSecurity?.blockPrivateNetworks || false+ }+ onChange={(checked) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ blockPrivateNetworks: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.security.htmlUrlSecurity.blockLocalhost.label",+ "Block Localhost",+ )}+ info={t(+ "admin.settings.security.htmlUrlSecurity.blockLocalhost.description",+ "Block localhost and loopback addresses (127.x.x.x, ::1)",+ )}+ pending={isFieldPending("html.urlSecurity.blockLocalhost")}+ checked={settings?.html?.urlSecurity?.blockLocalhost || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ blockLocalhost: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.security.htmlUrlSecurity.blockLinkLocal.label",+ "Block Link-Local Addresses",+ )}+ info={t(+ "admin.settings.security.htmlUrlSecurity.blockLinkLocal.description",+ "Block link-local addresses (169.254.x.x, fe80::/10)",+ )}+ pending={isFieldPending("html.urlSecurity.blockLinkLocal")}+ checked={settings?.html?.urlSecurity?.blockLinkLocal || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ blockLinkLocal: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.label",+ "Block Cloud Metadata Endpoints",+ )}+ info={t(+ "admin.settings.security.htmlUrlSecurity.blockCloudMetadata.description",+ "Block cloud provider metadata endpoints (169.254.169.254)",+ )}+ pending={isFieldPending(+ "html.urlSecurity.blockCloudMetadata",+ )}+ checked={+ settings?.html?.urlSecurity?.blockCloudMetadata || false+ }+ onChange={(checked) =>+ setSettings({+ ...settings,+ html: {+ ...settings?.html,+ urlSecurity: {+ ...settings?.html?.urlSecurity,+ blockCloudMetadata: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />+ </Stack>+ </Accordion.Panel>+ </Accordion.Item>+ </Accordion>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/LegalDocumentsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/LegalDocumentsCard.tsxnew file mode 100644index 0000000000..313c578f29--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/LegalDocumentsCard.tsx@@ -0,0 +1,190 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { TextInput, Stack, Paper, Text, Group, Alert } from "@mantine/core";+import WarningIcon from "@mui/icons-material/Warning";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import type { LegalCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/**+ * Links to the instance's own legal documents. The responsibility warning sits+ * inside this card, not at page level, where it would read as covering the JWT+ * and SSRF settings above it too.+ */+export function LegalDocumentsCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: LegalCardProps) {+ const { t } = useTranslation();++ return (+ <>+ <Alert+ icon={<WarningIcon style={{ fontSize: 18 }} />}+ title={t(+ "admin.settings.legal.disclaimer.title",+ "Legal Responsibility Warning",+ )}+ color="yellow"+ variant="light"+ >+ <Text size="sm">+ {t(+ "admin.settings.legal.disclaimer.message",+ "By customizing these legal documents, you assume full responsibility for ensuring compliance with all applicable laws and regulations, including but not limited to GDPR and other EU data protection requirements. Only modify these settings if: (1) you are operating a personal/private instance, (2) you are outside EU jurisdiction and understand your local legal obligations, or (3) you have obtained proper legal counsel and accept sole responsibility for all user data and legal compliance. Stirling-PDF and its developers assume no liability for your legal obligations.",+ )}+ </Text>+ </Alert>++ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.legal.termsAndConditions.label",+ "Terms and Conditions",+ )}+ </span>+ <PendingBadge show={isFieldPending("termsAndConditions")} />+ <InfoTooltip+ label={t(+ "admin.settings.legal.termsAndConditions.description",+ "URL or filename to terms and conditions",+ )}+ />+ </Group>+ }+ value={settings.termsAndConditions || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ termsAndConditions: e.target.value,+ })+ }+ placeholder="https://example.com/terms"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.legal.privacyPolicy.label",+ "Privacy Policy",+ )}+ </span>+ <PendingBadge show={isFieldPending("privacyPolicy")} />+ <InfoTooltip+ label={t(+ "admin.settings.legal.privacyPolicy.description",+ "URL or filename to privacy policy",+ )}+ />+ </Group>+ }+ value={settings.privacyPolicy || ""}+ onChange={(e) =>+ setSettings({ ...settings, privacyPolicy: e.target.value })+ }+ placeholder="https://example.com/privacy"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.legal.accessibilityStatement.label",+ "Accessibility Statement",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("accessibilityStatement")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.legal.accessibilityStatement.description",+ "URL or filename to accessibility statement",+ )}+ />+ </Group>+ }+ value={settings.accessibilityStatement || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ accessibilityStatement: e.target.value,+ })+ }+ placeholder="https://example.com/accessibility"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.legal.cookiePolicy.label",+ "Cookie Policy",+ )}+ </span>+ <PendingBadge show={isFieldPending("cookiePolicy")} />+ <InfoTooltip+ label={t(+ "admin.settings.legal.cookiePolicy.description",+ "URL or filename to cookie policy",+ )}+ />+ </Group>+ }+ value={settings.cookiePolicy || ""}+ onChange={(e) =>+ setSettings({ ...settings, cookiePolicy: e.target.value })+ }+ placeholder="https://example.com/cookies"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.legal.impressum.label", "Impressum")}+ </span>+ <PendingBadge show={isFieldPending("impressum")} />+ <InfoTooltip+ label={t(+ "admin.settings.legal.impressum.description",+ "URL or filename to impressum (required in some jurisdictions)",+ )}+ />+ </Group>+ }+ value={settings.impressum || ""}+ onChange={(e) =>+ setSettings({ ...settings, impressum: e.target.value })+ }+ placeholder="https://example.com/impressum"+ disabled={!loginEnabled}+ />+ </div>+ </Stack>+ </Paper>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/LinkedServicesCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/LinkedServicesCard.tsxnew file mode 100644index 0000000000..38f417c4aa--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/LinkedServicesCard.tsx@@ -0,0 +1,44 @@+import { Stack } from "@mantine/core";+import ProviderCard from "@app/components/shared/config/configSections/ProviderCard";+import type { Provider } from "@app/components/shared/config/configSections/providerDefinitions";+import {+ getProviderSettings,+ updateProviderSettings,+} from "@app/components/shared/config/configSections/security/connectionProviders";+import type { ConnectionsCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++interface LinkedServicesCardProps extends ConnectionsCardProps {+ /** Already-configured providers, filtered by the page. */+ providers: Provider[];+}++export function LinkedServicesCard({+ settings,+ setSettings,+ loginEnabled,+ providers,+}: LinkedServicesCardProps) {+ return (+ <Stack gap="sm">+ {providers.map((provider) => (+ <ProviderCard+ key={provider.id}+ provider={provider}+ isConfigured={true}+ settings={+ getProviderSettings(settings, provider) as Record<string, unknown>+ }+ onChange={(updatedSettings) =>+ updateProviderSettings(+ settings,+ setSettings,+ provider,+ updatedSettings,+ )+ }+ disabled={!loginEnabled}+ />+ ))}+ </Stack>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/LoginAgreementCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/LoginAgreementCard.tsxnew file mode 100644index 0000000000..91a239410b--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/LoginAgreementCard.tsx@@ -0,0 +1,64 @@+import { useTranslation } from "react-i18next";+import { Stack, Paper, Divider } from "@mantine/core";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import LoginAgreementEditor from "@app/components/shared/config/configSections/LoginAgreementEditor";+import type { LegalCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** The disclaimer users accept after signing in, and its per-language text. */+export function LoginAgreementCard({+ settings,+ setSettings,+ loginEnabled,+}: LegalCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.legal.loginAgreement.enabled.label",+ "Enable login agreement",+ )}+ info={t(+ "admin.settings.legal.loginAgreement.restartNote",+ "Enabling or disabling the agreement applies after a restart, like other settings. Text edits below apply immediately.",+ )}+ checked={settings.loginAgreement?.enabled ?? false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ loginAgreement: {+ ...settings.loginAgreement,+ enabled: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.legal.loginAgreement.anonymous.label",+ "Show in anonymous (no-login) mode",+ )}+ checked={settings.loginAgreement?.showInAnonymousMode ?? true}+ onChange={(checked) =>+ setSettings({+ ...settings,+ loginAgreement: {+ ...settings.loginAgreement,+ showInAnonymousMode: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <Divider />++ <LoginAgreementEditor disabled={!loginEnabled} />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/MobileUploadQrCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/MobileUploadQrCard.tsxnew file mode 100644index 0000000000..8688a3224b--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/MobileUploadQrCard.tsx@@ -0,0 +1,298 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useNavigate } from "react-router-dom";+import {+ Stack,+ Paper,+ Text,+ Group,+ Switch,+ Select,+ Anchor,+ Collapse,+} from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { ConnectionsCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** QR-code handoff so a phone can push files into this session. */+export function MobileUploadQrCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+ getDisabledStyles,+}: ConnectionsCardProps) {+ const { t } = useTranslation();+ const navigate = useNavigate();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ {/* Documentation Link */}+ <Anchor+ href="https://docs.stirlingpdf.com/Functionality/Mobile-Scanner"+ target="_blank"+ size="xs"+ c="var(--c-accent-text)"+ >+ {t("admin.settings.connections.documentation", "View documentation")}{" "}+ ↗+ </Anchor>++ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ }}+ >+ <div style={{ flex: 1, minWidth: 0 }}>+ <Text fw={500} size="sm">+ {t(+ "admin.settings.connections.mobileScanner.enable",+ "Enable QR Code Upload",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.connections.mobileScanner.description",+ "Allow users to upload files from mobile devices by scanning a QR code",+ )}+ />+ </Text>+ <Text size="xs" c="var(--color-amber-dark)" mt={8} fw={500}>+ {t(+ "admin.settings.connections.mobileScanner.note",+ "Note: Requires Frontend URL to be configured. ",+ )}+ <Anchor+ href="#"+ onClick={(e) => {+ e.preventDefault();+ navigate("/settings/adminGeneral#frontendUrl");+ }}+ c="var(--color-amber-dark)"+ td="underline"+ >+ {t(+ "admin.settings.connections.mobileScanner.link",+ "Configure in System Settings",+ )}+ </Anchor>+ </Text>+ </div>+ <Group gap="xs">+ <Switch+ checked={settings?.enableMobileScanner || false}+ onChange={(e) => {+ if (!loginEnabled) return; // Block change when login disabled+ setSettings({+ ...settings,+ enableMobileScanner: e.target.checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ <PendingBadge show={isFieldPending("enableMobileScanner")} />+ </Group>+ </div>++ {/* Mobile Scanner Settings - Only show when enabled */}+ <Collapse in={settings?.enableMobileScanner || false}>+ <Stack+ gap="md"+ mt="md"+ ml="lg"+ style={{+ borderLeft: "2px solid var(--mantine-color-gray-3)",+ paddingLeft: "1rem",+ }}+ >+ {/* Convert to PDF */}+ <div>+ <Text size="sm" fw={500} mb="xs">+ {t(+ "admin.settings.connections.mobileScannerConvertToPdf",+ "Convert Images to PDF",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.connections.mobileScannerConvertToPdfDesc",+ "Automatically convert uploaded images to PDF format. If disabled, images will be kept as-is.",+ )}+ />+ </Text>+ <Group gap="xs">+ <Switch+ checked={settings?.mobileScannerConvertToPdf !== false}+ onChange={(e) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ mobileScannerConvertToPdf: e.target.checked,+ });+ }}+ disabled={!loginEnabled}+ />+ <PendingBadge+ show={isFieldPending("mobileScannerConvertToPdf")}+ />+ </Group>+ </div>++ {/* PDF Conversion Settings - Only show when convertToPdf is enabled */}+ {settings?.mobileScannerConvertToPdf !== false && (+ <>+ {/* Image Resolution */}+ <div>+ <Text size="sm" fw={500} mb="xs">+ {t(+ "admin.settings.connections.mobileScannerImageResolution",+ "Image Resolution",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.connections.mobileScannerImageResolutionDesc",+ 'Resolution of uploaded images. "Reduced" scales images to max 1200px to reduce file size.',+ )}+ />+ </Text>+ <Group gap="xs">+ <Select+ value={settings?.mobileScannerImageResolution || "full"}+ onChange={(value) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ mobileScannerImageResolution: value || "full",+ });+ }}+ data={[+ {+ value: "full",+ label: t(+ "admin.settings.connections.imageResolutionFull",+ "Full (Original Size)",+ ),+ },+ {+ value: "reduced",+ label: t(+ "admin.settings.connections.imageResolutionReduced",+ "Reduced (Max 1200px)",+ ),+ },+ ]}+ disabled={!loginEnabled}+ style={{ width: "250px" }}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />+ <PendingBadge+ show={isFieldPending("mobileScannerImageResolution")}+ />+ </Group>+ </div>++ {/* Page Format */}+ <div>+ <Text size="sm" fw={500} mb="xs">+ {t(+ "admin.settings.connections.mobileScannerPageFormat",+ "Page Format",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.connections.mobileScannerPageFormatDesc",+ 'PDF page size for converted images. "Keep" uses original image dimensions.',+ )}+ />+ </Text>+ <Group gap="xs">+ <Select+ value={settings?.mobileScannerPageFormat || "A4"}+ onChange={(value) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ mobileScannerPageFormat: value || "A4",+ });+ }}+ data={[+ {+ value: "keep",+ label: t(+ "admin.settings.connections.pageFormatKeep",+ "Keep (Original Dimensions)",+ ),+ },+ {+ value: "A4",+ label: t(+ "admin.settings.connections.pageFormatA4",+ "A4 (210×297mm)",+ ),+ },+ {+ value: "letter",+ label: t(+ "admin.settings.connections.pageFormatLetter",+ "Letter (8.5×11in)",+ ),+ },+ ]}+ disabled={!loginEnabled}+ style={{ width: "250px" }}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ />+ <PendingBadge+ show={isFieldPending("mobileScannerPageFormat")}+ />+ </Group>+ </div>++ {/* Stretch to Fit */}+ <div>+ <Text size="sm" fw={500} mb="xs">+ {t(+ "admin.settings.connections.mobileScannerStretchToFit",+ "Stretch to Fit",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.connections.mobileScannerStretchToFitDesc",+ "Stretch images to fill the entire page. If disabled, images are centered with preserved aspect ratio.",+ )}+ />+ </Text>+ <Group gap="xs">+ <Switch+ checked={settings?.mobileScannerStretchToFit || false}+ onChange={(e) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ mobileScannerStretchToFit: e.target.checked,+ });+ }}+ disabled={!loginEnabled}+ />+ <PendingBadge+ show={isFieldPending("mobileScannerStretchToFit")}+ />+ </Group>+ </div>+ </>+ )}+ </Stack>+ </Collapse>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/SearchEngineVisibilityCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/SearchEngineVisibilityCard.tsxnew file mode 100644index 0000000000..2f659e956a--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/SearchEngineVisibilityCard.tsx@@ -0,0 +1,43 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { Stack, Paper } from "@mantine/core";+import type { PrivacyCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** Whether search engines are allowed to index this instance. */+export function SearchEngineVisibilityCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+ getDisabledStyles,+}: PrivacyCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.privacy.googleVisibility.label",+ "Google Visibility",+ )}+ info={t(+ "admin.settings.privacy.googleVisibility.description",+ "Allow search engines to index this application",+ )}+ pending={isFieldPending("googleVisibility")}+ checked={settings?.googleVisibility || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ googleVisibility: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/SessionsJwtCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/SessionsJwtCard.tsxnew file mode 100644index 0000000000..d862bd56d1--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/SessionsJwtCard.tsx@@ -0,0 +1,215 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { NumberInput, Stack, Paper, Group } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import type { SecurityCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** How long a signed-in session lives, and the JWT knobs behind it. */+export function SessionsJwtCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: SecurityCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.security.jwt.enableKeyCleanup.label",+ "Enable Key Cleanup",+ )}+ info={t(+ "admin.settings.security.jwt.enableKeyCleanup.description",+ "Automatically remove old JWT keys after retention period",+ )}+ pending={isFieldPending("jwt.enableKeyCleanup")}+ checked={settings?.jwt?.enableKeyCleanup || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ jwt: {+ ...settings?.jwt,+ enableKeyCleanup: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <div>+ <NumberInput+ name="jwt_tokenExpiryMinutes"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.jwt.tokenExpiryMinutes.label",+ "Web Token Expiry (minutes)",+ )}+ </span>+ <PendingBadge show={isFieldPending("jwt.tokenExpiryMinutes")} />+ <InfoTooltip+ label={t(+ "admin.settings.security.jwt.tokenExpiryMinutes.description",+ "Access token lifetime in minutes for web clients (default: 1440 = 24 hours)",+ )}+ />+ </Group>+ }+ value={settings?.jwt?.tokenExpiryMinutes || 1440}+ onChange={(value) =>+ setSettings({+ ...settings,+ jwt: {+ ...settings?.jwt,+ tokenExpiryMinutes: Number(value),+ },+ })+ }+ min={1}+ max={43200}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ name="jwt_desktopTokenExpiryMinutes"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.jwt.desktopTokenExpiryMinutes.label",+ "Desktop Token Expiry (minutes)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("jwt.desktopTokenExpiryMinutes")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.security.jwt.desktopTokenExpiryMinutes.description",+ "Access token lifetime in minutes for desktop clients. Desktop apps automatically detected via User-Agent and receive longer sessions for better UX (default: 43200 = 30 days)",+ )}+ />+ </Group>+ }+ value={settings?.jwt?.desktopTokenExpiryMinutes || 43200}+ onChange={(value) =>+ setSettings({+ ...settings,+ jwt: {+ ...settings?.jwt,+ desktopTokenExpiryMinutes: Number(value),+ },+ })+ }+ min={1}+ max={525600}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ name="jwt_allowedClockSkewSeconds"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.jwt.allowedClockSkewSeconds.label",+ "Clock Skew Tolerance (seconds)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("jwt.allowedClockSkewSeconds")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.security.jwt.allowedClockSkewSeconds.description",+ "Tolerance for client/server time drift during token validation (default: 60 seconds)",+ )}+ />+ </Group>+ }+ value={settings?.jwt?.allowedClockSkewSeconds ?? 60}+ onChange={(value) =>+ setSettings({+ ...settings,+ jwt: {+ ...settings?.jwt,+ allowedClockSkewSeconds: Number(value),+ },+ })+ }+ min={0}+ max={300}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ name="jwt_refreshGraceMinutes"+ label={+ <Group component="span" gap="xs">+ <span>+ {t(+ "admin.settings.security.jwt.refreshGraceMinutes.label",+ "Refresh Grace Period (minutes)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("jwt.refreshGraceMinutes")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.security.jwt.refreshGraceMinutes.description",+ "Allow token refresh within this many minutes after expiry (default: 15 minutes, max 3 attempts)",+ )}+ />+ </Group>+ }+ value={settings?.jwt?.refreshGraceMinutes ?? 15}+ onChange={(value) =>+ setSettings({+ ...settings,+ jwt: {+ ...settings?.jwt,+ refreshGraceMinutes: Number(value),+ },+ })+ }+ min={0}+ max={120}+ disabled={!loginEnabled}+ />+ </div>++ <SettingsToggleRow+ label={t(+ "admin.settings.security.jwt.secureCookie.label",+ "Secure Cookie",+ )}+ info={t(+ "admin.settings.security.jwt.secureCookie.description",+ "Require HTTPS for JWT cookies (recommended for production)",+ )}+ pending={isFieldPending("jwt.secureCookie")}+ checked={settings?.jwt?.secureCookie || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ jwt: { ...settings?.jwt, secureCookie: checked },+ })+ }+ disabled={!loginEnabled}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/SsoAutoLoginCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/SsoAutoLoginCard.tsxnew file mode 100644index 0000000000..99958d7b6d--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/SsoAutoLoginCard.tsx@@ -0,0 +1,43 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { Stack, Paper } from "@mantine/core";+import type { ConnectionsCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++/** Send unauthenticated users straight to the SSO provider. */+export function SsoAutoLoginCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+ getDisabledStyles,+}: ConnectionsCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.connections.ssoAutoLogin.enable",+ "Enable SSO Auto Login",+ )}+ info={t(+ "admin.settings.connections.ssoAutoLogin.description",+ "Automatically redirect to SSO login when authentication is required",+ )}+ pending={isFieldPending("ssoAutoLogin")}+ checked={settings?.ssoAutoLogin || false}+ onChange={(checked) => {+ if (!loginEnabled) return; // Block change when login disabled+ setSettings({+ ...settings,+ ssoAutoLogin: checked,+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/UnlinkedServicesCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/UnlinkedServicesCard.tsxnew file mode 100644index 0000000000..f97ac9aafd--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/UnlinkedServicesCard.tsx@@ -0,0 +1,44 @@+import { Stack } from "@mantine/core";+import ProviderCard from "@app/components/shared/config/configSections/ProviderCard";+import type { Provider } from "@app/components/shared/config/configSections/providerDefinitions";+import {+ getProviderSettings,+ updateProviderSettings,+} from "@app/components/shared/config/configSections/security/connectionProviders";+import type { ConnectionsCardProps } from "@app/components/shared/config/configSections/security/securityCardProps";++interface UnlinkedServicesCardProps extends ConnectionsCardProps {+ /** Providers with nothing configured yet, filtered by the page. */+ providers: Provider[];+}++export function UnlinkedServicesCard({+ settings,+ setSettings,+ loginEnabled,+ providers,+}: UnlinkedServicesCardProps) {+ return (+ <Stack gap="sm">+ {providers.map((provider) => (+ <ProviderCard+ key={provider.id}+ provider={provider}+ isConfigured={false}+ settings={+ getProviderSettings(settings, provider) as Record<string, unknown>+ }+ onChange={(updatedSettings) =>+ updateProviderSettings(+ settings,+ setSettings,+ provider,+ updatedSettings,+ )+ }+ disabled={!loginEnabled}+ />+ ))}+ </Stack>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/connectionProviders.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/connectionProviders.tsnew file mode 100644index 0000000000..414a333e3c--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/connectionProviders.ts@@ -0,0 +1,154 @@+import {+ Provider,+ useAllProviders,+} from "@app/components/shared/config/configSections/providerDefinitions";+import type {+ ConnectionsSettingsData,+ GoogleDriveSettings,+ OAuth2ClientSettings,+ OAuth2GenericSettings,+ ProviderSettings,+} from "@app/components/shared/config/configSections/security/securitySettingsTypes";++// Shared by the linked and unlinked cards, and by the page, which needs the+// counts to decide whether either section renders at all.++export function isProviderConfigured(+ settings: ConnectionsSettingsData,+ provider: Provider,+): boolean {+ if (provider.id === "saml2") {+ return settings?.saml2?.enabled === true;+ }++ if (provider.id === "smtp") {+ return settings?.mail?.enabled === true;+ }++ if (provider.id === "telegram") {+ return settings?.telegram?.enabled === true;+ }++ if (provider.id === "googledrive") {+ return settings?.googleDriveEnabled === true;+ }++ if (provider.id === "oauth2-generic") {+ return settings?.oauth2?.enabled === true;+ }++ // Check if specific OAuth2 provider is configured (has clientId)+ const providerSettings = settings?.oauth2?.client?.[provider.id];+ return !!providerSettings?.clientId;+}++export function getProviderSettings(+ settings: ConnectionsSettingsData,+ provider: Provider,+): ProviderSettings {+ if (provider.id === "saml2") {+ return settings?.saml2 || {};+ }++ if (provider.id === "smtp") {+ return settings?.mail || {};+ }++ if (provider.id === "telegram") {+ return settings?.telegram || {};+ }++ if (provider.id === "googledrive") {+ const gd: GoogleDriveSettings = {+ enabled: settings?.googleDriveEnabled,+ clientId: settings?.googleDriveClientId,+ apiKey: settings?.googleDriveApiKey,+ appId: settings?.googleDriveAppId,+ };+ return gd;+ }++ if (provider.id === "oauth2-generic") {+ const generic: OAuth2GenericSettings = {+ enabled: settings?.oauth2?.enabled,+ provider: settings?.oauth2?.provider,+ issuer: settings?.oauth2?.issuer,+ clientId: settings?.oauth2?.clientId,+ clientSecret: settings?.oauth2?.clientSecret,+ scopes: settings?.oauth2?.scopes,+ useAsUsername: settings?.oauth2?.useAsUsername,+ autoCreateUser: settings?.oauth2?.autoCreateUser,+ blockRegistration: settings?.oauth2?.blockRegistration,+ };+ return generic;+ }++ // Specific OAuth2 provider settings+ return settings?.oauth2?.client?.[provider.id] || {};+}++export function updateProviderSettings(+ settings: ConnectionsSettingsData,+ setSettings: (next: ConnectionsSettingsData) => void,+ provider: Provider,+ updatedSettings: Record<string, unknown>,+) {+ if (provider.id === "smtp") {+ setSettings({ ...settings, mail: updatedSettings });+ } else if (provider.id === "telegram") {+ setSettings({+ ...settings,+ telegram: updatedSettings,+ });+ } else if (provider.id === "googledrive") {+ const gd = updatedSettings as GoogleDriveSettings;+ setSettings({+ ...settings,+ googleDriveEnabled: gd.enabled,+ googleDriveClientId: gd.clientId,+ googleDriveApiKey: gd.apiKey,+ googleDriveAppId: gd.appId,+ });+ } else if (provider.id === "saml2") {+ setSettings({ ...settings, saml2: updatedSettings });+ } else if (provider.id === "oauth2-generic") {+ const generic = updatedSettings as OAuth2GenericSettings;+ setSettings({ ...settings, oauth2: { ...settings.oauth2, ...generic } });+ } else {+ // Specific OAuth2 provider+ const clientSettings = updatedSettings as OAuth2ClientSettings;+ setSettings({+ ...settings,+ oauth2: {+ ...settings.oauth2,+ client: {+ ...settings.oauth2?.client,+ [provider.id]: clientSettings,+ },+ },+ });+ }+}++/**+ * Providers split by what they are for. Signing in belongs on the security+ * page; wiring the server to Telegram, Drive or a mail host does not.+ */+export function useConnectionProviders(+ settings: ConnectionsSettingsData,+ category: "signin" | "integration" = "signin",+): {+ linkedProviders: Provider[];+ availableProviders: Provider[];+} {+ const allProviders = useAllProviders().filter(+ (p) => (p.category ?? "signin") === category,+ );+ const linkedProviders = allProviders.filter((p) =>+ isProviderConfigured(settings, p),+ );+ const availableProviders = allProviders.filter(+ (p) => !isProviderConfigured(settings, p),+ );+ return { linkedProviders, availableProviders };+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securityCardProps.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securityCardProps.tsnew file mode 100644index 0000000000..ff07eae1e9--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securityCardProps.ts@@ -0,0 +1,30 @@+import type { useLoginRequired } from "@app/hooks/useLoginRequired";+import type {+ ConnectionsSettingsData,+ LegalSettingsData,+ PrivacySettingsData,+ SecuritySettingsData,+} from "@app/components/shared/config/configSections/security/securitySettingsTypes";++export type GetDisabledStyles = ReturnType<+ typeof useLoginRequired+>["getDisabledStyles"];++/**+ * What every card on the merged security page needs from the page that owns+ * them. This page is a composite of four backend sections, so a card gets the+ * slice of the draft its own sub-fetch owns rather than fetching for itself.+ */+export interface SettingsCardProps<T> {+ settings: T;+ setSettings: (next: T) => void;+ /** True while the backend still lists this key as awaiting a restart. */+ isFieldPending: (field: string) => boolean;+ loginEnabled: boolean;+ getDisabledStyles: GetDisabledStyles;+}++export type SecurityCardProps = SettingsCardProps<SecuritySettingsData>;+export type ConnectionsCardProps = SettingsCardProps<ConnectionsSettingsData>;+export type PrivacyCardProps = SettingsCardProps<PrivacySettingsData>;+export type LegalCardProps = SettingsCardProps<LegalSettingsData>;diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.tsnew file mode 100644index 0000000000..fc69a659cc--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts@@ -0,0 +1,415 @@+import apiClient from "@app/services/apiClient";+import type {+ ConnectionsSettingsData,+ LegalSettingsData,+ PrivacySettingsData,+ SecuritySettingsData,+} from "@app/components/shared/config/configSections/security/securitySettingsTypes";++// The fetch/save transformers for the merged page's four sub-fetches, kept out+// of the page file so it reads as hooks, one draft, one save.++interface SettingsSaveResult {+ sectionData: Record<string, unknown>;+ deltaSettings: Record<string, unknown>;+}++export async function fetchSecuritySettings(): Promise<+ SecuritySettingsData & { _pending?: Record<string, unknown> }+> {+ const [securityResponse, premiumResponse, systemResponse] = await Promise.all(+ [+ apiClient.get("/api/v1/admin/settings/section/security"),+ apiClient.get("/api/v1/admin/settings/section/premium"),+ apiClient.get("/api/v1/admin/settings/section/system"),+ ],+ );++ const securityData = securityResponse.data || {};+ const premiumData = premiumResponse.data || {};+ const systemData = systemResponse.data || {};++ const { _pending: securityPending, ...securityActive } = securityData;+ const { _pending: premiumPending, ...premiumActive } = premiumData;+ const { _pending: systemPending, ...systemActive } = systemData;++ const combined: SecuritySettingsData & {+ _pending?: Record<string, unknown>;+ } = {+ ...securityActive,+ };++ // Only add audit if it exists (don't create defaults)+ if (premiumActive.enterpriseFeatures?.audit) {+ combined.audit = premiumActive.enterpriseFeatures.audit;+ }++ // Only add html if it exists (don't create defaults)+ if (systemActive.html) {+ combined.html = systemActive.html;+ }++ // Merge all _pending blocks+ const mergedPending: Record<string, unknown> = {};+ if (securityPending) {+ Object.assign(mergedPending, securityPending);+ }+ if (premiumPending?.enterpriseFeatures?.audit) {+ mergedPending.audit = premiumPending.enterpriseFeatures.audit;+ }+ if (systemPending?.html) {+ mergedPending.html = systemPending.html;+ }++ if (Object.keys(mergedPending).length > 0) {+ combined._pending = mergedPending;+ }++ return combined;+}++export function saveSecuritySettings(+ settings: SecuritySettingsData,+): SettingsSaveResult {+ const { audit, html, ...securitySettings } = settings;++ const deltaSettings: Record<string, unknown> = {+ "security.enableLogin": securitySettings.enableLogin,+ "security.loginMethod": securitySettings.loginMethod,+ "security.loginAttemptCount": securitySettings.loginAttemptCount,+ "security.loginResetTimeMinutes": securitySettings.loginResetTimeMinutes,+ "security.xFrameOptions": securitySettings.xFrameOptions,+ "security.jwt.enableKeyCleanup": securitySettings.jwt?.enableKeyCleanup,+ "security.jwt.tokenExpiryMinutes": securitySettings.jwt?.tokenExpiryMinutes,+ "security.jwt.desktopTokenExpiryMinutes":+ securitySettings.jwt?.desktopTokenExpiryMinutes,+ "security.jwt.allowedClockSkewSeconds":+ securitySettings.jwt?.allowedClockSkewSeconds,+ "security.jwt.refreshGraceMinutes":+ securitySettings.jwt?.refreshGraceMinutes,+ "security.jwt.secureCookie": securitySettings.jwt?.secureCookie,+ // Premium audit settings+ "premium.enterpriseFeatures.audit.enabled": audit?.enabled,+ "premium.enterpriseFeatures.audit.level": audit?.level,+ "premium.enterpriseFeatures.audit.retentionDays": audit?.retentionDays,+ "premium.enterpriseFeatures.audit.captureFileHash": audit?.captureFileHash,+ "premium.enterpriseFeatures.audit.capturePdfAuthor":+ audit?.capturePdfAuthor,+ "premium.enterpriseFeatures.audit.captureOperationResults":+ audit?.captureOperationResults,+ };++ // System HTML settings+ if (html?.urlSecurity) {+ deltaSettings["system.html.urlSecurity.enabled"] = html.urlSecurity.enabled;+ deltaSettings["system.html.urlSecurity.level"] = html.urlSecurity.level;+ deltaSettings["system.html.urlSecurity.allowedDomains"] =+ html.urlSecurity.allowedDomains;+ deltaSettings["system.html.urlSecurity.blockedDomains"] =+ html.urlSecurity.blockedDomains;+ deltaSettings["system.html.urlSecurity.internalTlds"] =+ html.urlSecurity.internalTlds;+ deltaSettings["system.html.urlSecurity.blockPrivateNetworks"] =+ html.urlSecurity.blockPrivateNetworks;+ deltaSettings["system.html.urlSecurity.blockLocalhost"] =+ html.urlSecurity.blockLocalhost;+ deltaSettings["system.html.urlSecurity.blockLinkLocal"] =+ html.urlSecurity.blockLinkLocal;+ deltaSettings["system.html.urlSecurity.blockCloudMetadata"] =+ html.urlSecurity.blockCloudMetadata;+ }++ return {+ sectionData: {},+ deltaSettings,+ };+}++export async function fetchConnectionsSettings(): Promise<+ ConnectionsSettingsData & { _pending?: Record<string, unknown> }+> {+ // Fetch security settings (oauth2, saml2)+ const securityResponse = await apiClient.get(+ "/api/v1/admin/settings/section/security",+ );+ const securityData = securityResponse.data || {};++ // Fetch mail settings+ const mailResponse = await apiClient.get(+ "/api/v1/admin/settings/section/mail",+ );+ const mailData = mailResponse.data || {};++ // Fetch premium settings for SSO Auto Login+ const premiumResponse = await apiClient.get(+ "/api/v1/admin/settings/section/premium",+ );+ const premiumData = premiumResponse.data || {};++ // Fetch Telegram settings+ const telegramResponse = await apiClient.get(+ "/api/v1/admin/settings/section/telegram",+ );+ const telegramData = telegramResponse.data || {};++ // Fetch system settings for enableMobileScanner+ const systemResponse = await apiClient.get(+ "/api/v1/admin/settings/section/system",+ );+ const systemData = systemResponse.data || {};++ const result: ConnectionsSettingsData & {+ _pending?: Record<string, unknown>;+ } = {+ oauth2: securityData.oauth2 || {},+ saml2: securityData.saml2 || {},+ mail: mailData || {},+ telegram: telegramData || {},+ ssoAutoLogin: premiumData.proFeatures?.ssoAutoLogin || false,+ enableMobileScanner: systemData.enableMobileScanner || false,+ mobileScannerConvertToPdf:+ systemData.mobileScannerSettings?.convertToPdf !== false,+ mobileScannerImageResolution:+ systemData.mobileScannerSettings?.imageResolution || "full",+ mobileScannerPageFormat:+ systemData.mobileScannerSettings?.pageFormat || "A4",+ mobileScannerStretchToFit:+ systemData.mobileScannerSettings?.stretchToFit || false,+ googleDriveEnabled: premiumData.proFeatures?.googleDrive?.enabled || false,+ googleDriveClientId: premiumData.proFeatures?.googleDrive?.clientId || "",+ googleDriveApiKey: premiumData.proFeatures?.googleDrive?.apiKey || "",+ googleDriveAppId: premiumData.proFeatures?.googleDrive?.appId || "",+ };++ // Merge pending blocks from all endpoints+ const pendingBlock: Record<string, unknown> = {};+ if (securityData._pending?.oauth2) {+ pendingBlock.oauth2 = securityData._pending.oauth2;+ }+ if (securityData._pending?.saml2) {+ pendingBlock.saml2 = securityData._pending.saml2;+ }+ if (mailData._pending) {+ pendingBlock.mail = mailData._pending;+ }+ if (telegramData._pending) {+ pendingBlock.telegram = telegramData._pending;+ }+ if (premiumData._pending?.proFeatures?.ssoAutoLogin !== undefined) {+ pendingBlock.ssoAutoLogin = premiumData._pending.proFeatures.ssoAutoLogin;+ }+ if (systemData._pending?.enableMobileScanner !== undefined) {+ pendingBlock.enableMobileScanner = systemData._pending.enableMobileScanner;+ }+ if (systemData._pending?.mobileScannerSettings?.convertToPdf !== undefined) {+ pendingBlock.mobileScannerConvertToPdf =+ systemData._pending.mobileScannerSettings.convertToPdf;+ }+ if (+ systemData._pending?.mobileScannerSettings?.imageResolution !== undefined+ ) {+ pendingBlock.mobileScannerImageResolution =+ systemData._pending.mobileScannerSettings.imageResolution;+ }+ if (systemData._pending?.mobileScannerSettings?.pageFormat !== undefined) {+ pendingBlock.mobileScannerPageFormat =+ systemData._pending.mobileScannerSettings.pageFormat;+ }+ if (systemData._pending?.mobileScannerSettings?.stretchToFit !== undefined) {+ pendingBlock.mobileScannerStretchToFit =+ systemData._pending.mobileScannerSettings.stretchToFit;+ }+ if (premiumData._pending?.proFeatures?.googleDrive?.enabled !== undefined) {+ pendingBlock.googleDriveEnabled =+ premiumData._pending.proFeatures.googleDrive.enabled;+ }+ if (premiumData._pending?.proFeatures?.googleDrive?.clientId !== undefined) {+ pendingBlock.googleDriveClientId =+ premiumData._pending.proFeatures.googleDrive.clientId;+ }+ if (premiumData._pending?.proFeatures?.googleDrive?.apiKey !== undefined) {+ pendingBlock.googleDriveApiKey =+ premiumData._pending.proFeatures.googleDrive.apiKey;+ }+ if (premiumData._pending?.proFeatures?.googleDrive?.appId !== undefined) {+ pendingBlock.googleDriveAppId =+ premiumData._pending.proFeatures.googleDrive.appId;+ }++ if (Object.keys(pendingBlock).length > 0) {+ result._pending = pendingBlock;+ }++ return result;+}++export function saveConnectionsSettings(+ currentSettings: ConnectionsSettingsData,+): SettingsSaveResult {+ const deltaSettings: Record<string, unknown> = {};++ // Build delta for oauth2 settings+ if (currentSettings.oauth2) {+ Object.keys(currentSettings.oauth2).forEach((key) => {+ if (key !== "client") {+ deltaSettings[`security.oauth2.${key}`] = (+ currentSettings.oauth2 as Record<string, unknown>+ )[key];+ }+ });++ // Build delta for specific OAuth2 providers+ const oauth2Client = currentSettings.oauth2.client;+ if (oauth2Client) {+ Object.keys(oauth2Client).forEach((providerId) => {+ const providerSettings = oauth2Client[providerId] as Record<+ string,+ unknown+ >;+ Object.keys(providerSettings).forEach((key) => {+ deltaSettings[`security.oauth2.client.${providerId}.${key}`] =+ providerSettings[key];+ });+ });+ }+ }++ // Build delta for saml2 settings+ if (currentSettings.saml2) {+ const saml2 = currentSettings.saml2 as Record<string, unknown>;+ Object.keys(saml2).forEach((key) => {+ deltaSettings[`security.saml2.${key}`] = saml2[key];+ });+ }++ if (currentSettings.mail) {+ const mail = currentSettings.mail as Record<string, unknown>;+ Object.keys(mail).forEach((key) => {+ deltaSettings[`mail.${key}`] = mail[key];+ });+ }++ if (currentSettings.telegram) {+ const telegram = currentSettings.telegram as Record<string, unknown>;+ Object.keys(telegram).forEach((key) => {+ deltaSettings[`telegram.${key}`] = telegram[key];+ });+ }++ if (currentSettings?.ssoAutoLogin !== undefined) {+ deltaSettings["premium.proFeatures.ssoAutoLogin"] =+ currentSettings.ssoAutoLogin;+ }++ if (currentSettings?.enableMobileScanner !== undefined) {+ deltaSettings["system.enableMobileScanner"] =+ currentSettings.enableMobileScanner;+ }+ if (currentSettings?.mobileScannerConvertToPdf !== undefined) {+ deltaSettings["system.mobileScannerSettings.convertToPdf"] =+ currentSettings.mobileScannerConvertToPdf;+ }+ if (currentSettings?.mobileScannerImageResolution !== undefined) {+ deltaSettings["system.mobileScannerSettings.imageResolution"] =+ currentSettings.mobileScannerImageResolution;+ }+ if (currentSettings?.mobileScannerPageFormat !== undefined) {+ deltaSettings["system.mobileScannerSettings.pageFormat"] =+ currentSettings.mobileScannerPageFormat;+ }+ if (currentSettings?.mobileScannerStretchToFit !== undefined) {+ deltaSettings["system.mobileScannerSettings.stretchToFit"] =+ currentSettings.mobileScannerStretchToFit;+ }++ if (currentSettings?.googleDriveEnabled !== undefined) {+ deltaSettings["premium.proFeatures.googleDrive.enabled"] =+ currentSettings.googleDriveEnabled;+ }+ if (currentSettings?.googleDriveClientId !== undefined) {+ deltaSettings["premium.proFeatures.googleDrive.clientId"] =+ currentSettings.googleDriveClientId;+ }+ if (currentSettings?.googleDriveApiKey !== undefined) {+ deltaSettings["premium.proFeatures.googleDrive.apiKey"] =+ currentSettings.googleDriveApiKey;+ }+ if (currentSettings?.googleDriveAppId !== undefined) {+ deltaSettings["premium.proFeatures.googleDrive.appId"] =+ currentSettings.googleDriveAppId;+ }++ return {+ sectionData: {},+ deltaSettings,+ };+}++export async function fetchPrivacySettings(): Promise<+ PrivacySettingsData & { _pending?: Record<string, unknown> }+> {+ const [metricsResponse, systemResponse] = await Promise.all([+ apiClient.get("/api/v1/admin/settings/section/metrics"),+ apiClient.get("/api/v1/admin/settings/section/system"),+ ]);++ const metrics = metricsResponse.data;+ const system = systemResponse.data;++ const result: PrivacySettingsData & {+ _pending?: Record<string, unknown>;+ } = {+ enableAnalytics: system.enableAnalytics || false,+ googleVisibility: system.googlevisibility || false,+ metricsEnabled: metrics.enabled || false,+ };++ // Merge pending blocks from both endpoints+ const pendingBlock: Record<string, unknown> = {};+ if (system._pending?.enableAnalytics !== undefined) {+ pendingBlock.enableAnalytics = system._pending.enableAnalytics;+ }+ if (system._pending?.googlevisibility !== undefined) {+ pendingBlock.googleVisibility = system._pending.googlevisibility;+ }+ if (metrics._pending?.enabled !== undefined) {+ pendingBlock.metricsEnabled = metrics._pending.enabled;+ }++ if (Object.keys(pendingBlock).length > 0) {+ result._pending = pendingBlock;+ }++ return result;+}++export function savePrivacySettings(+ settings: PrivacySettingsData,+): SettingsSaveResult {+ const deltaSettings = {+ "system.enableAnalytics": settings.enableAnalytics,+ "system.googlevisibility": settings.googleVisibility,+ "metrics.enabled": settings.metricsEnabled,+ };++ return {+ sectionData: {},+ deltaSettings,+ };+}++// loginAgreement goes through the flat endpoint: a partial nested object sent+// to the section endpoint replaces the node and drops fallbackText, unedited.+export function saveLegalSettings(+ current: LegalSettingsData,+): SettingsSaveResult {+ const { loginAgreement, ...flat } = current;+ const deltaSettings: Record<string, unknown> = {};+ if (loginAgreement) {+ deltaSettings["legal.loginAgreement.enabled"] =+ loginAgreement.enabled ?? false;+ deltaSettings["legal.loginAgreement.showInAnonymousMode"] =+ loginAgreement.showInAnonymousMode ?? true;+ }+ return { sectionData: flat, deltaSettings };+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.tsnew file mode 100644index 0000000000..cbd8087ba6--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts@@ -0,0 +1,173 @@+// The four drafts the merged page edits. They are four different backend+// sections, so they stay four shapes even though one footer now saves them.++export interface SecuritySettingsData {+ enableLogin?: boolean;+ loginMethod?: string;+ loginAttemptCount?: number;+ loginResetTimeMinutes?: number;+ xFrameOptions?: string;+ jwt?: {+ enableKeyCleanup?: boolean;+ tokenExpiryMinutes?: number;+ desktopTokenExpiryMinutes?: number;+ allowedClockSkewSeconds?: number;+ refreshGraceMinutes?: number;+ secureCookie?: boolean;+ };+ audit?: {+ enabled?: boolean;+ level?: number;+ retentionDays?: number;+ captureFileHash?: boolean;+ capturePdfAuthor?: boolean;+ captureOperationResults?: boolean;+ };+ html?: {+ urlSecurity?: {+ enabled?: boolean;+ level?: string;+ allowedDomains?: string[];+ blockedDomains?: string[];+ internalTlds?: string[];+ blockPrivateNetworks?: boolean;+ blockLocalhost?: boolean;+ blockLinkLocal?: boolean;+ blockCloudMetadata?: boolean;+ };+ };+}++export interface PrivacySettingsData {+ enableAnalytics?: boolean;+ googleVisibility?: boolean;+ metricsEnabled?: boolean;+}++export interface LegalSettingsData {+ termsAndConditions?: string;+ privacyPolicy?: string;+ accessibilityStatement?: string;+ cookiePolicy?: string;+ impressum?: string;+ loginAgreement?: {+ enabled?: boolean;+ showInAnonymousMode?: boolean;+ fallbackText?: string;+ };+}++export interface FeedbackFlags {+ noValidDocument?: boolean;+ errorProcessing?: boolean;+ errorMessage?: boolean;+}++export interface FeedbackSettings {+ general?: { enabled?: boolean };+ channel?: FeedbackFlags;+ user?: FeedbackFlags;+}++export interface TelegramSettingsData {+ enabled?: boolean;+ botToken?: string;+ botUsername?: string;+ pipelineInboxFolder?: string;+ customFolderSuffix?: boolean;+ enableAllowUserIDs?: boolean;+ allowUserIDs?: number[];+ enableAllowChannelIDs?: boolean;+ allowChannelIDs?: number[];+ processingTimeoutSeconds?: number;+ pollingIntervalMillis?: number;+ feedback?: FeedbackSettings;+}++export interface MailSettings {+ enabled?: boolean;+ enableInvites?: boolean;+ host?: string;+ port?: number;+ username?: string;+ password?: string;+ from?: string;+}++export interface GoogleDriveSettings {+ enabled?: boolean;+ clientId?: string;+ apiKey?: string;+ appId?: string;+}++export interface OAuth2GenericSettings {+ enabled?: boolean;+ provider?: string;+ issuer?: string;+ clientId?: string;+ clientSecret?: string;+ scopes?: string;+ useAsUsername?: string;+ autoCreateUser?: boolean;+ blockRegistration?: boolean;+}++export interface Saml2Settings {+ enabled?: boolean;+ provider?: string;+ registrationId?: string;+ idpMetadataUri?: string;+ idpSingleLoginUrl?: string;+ idpSingleLogoutUrl?: string;+ idpIssuer?: string;+ idpCert?: string;+ privateKey?: string;+ spCert?: string;+ autoCreateUser?: boolean;+ blockRegistration?: boolean;+}++export interface OAuth2ClientSettings {+ clientId?: string;+ clientSecret?: string;+ scopes?: string;+ useAsUsername?: string;+ issuer?: string;+}++export type ProviderSettings =+ | MailSettings+ | TelegramSettingsData+ | GoogleDriveSettings+ | OAuth2GenericSettings+ | Saml2Settings+ | OAuth2ClientSettings;++export interface ConnectionsSettingsData {+ oauth2?: {+ enabled?: boolean;+ issuer?: string;+ clientId?: string;+ clientSecret?: string;+ provider?: string;+ autoCreateUser?: boolean;+ blockRegistration?: boolean;+ useAsUsername?: string;+ scopes?: string;+ client?: Record<string, OAuth2ClientSettings>;+ };+ saml2?: Saml2Settings;+ mail?: MailSettings;+ telegram?: TelegramSettingsData;+ ssoAutoLogin?: boolean;+ enableMobileScanner?: boolean;+ mobileScannerConvertToPdf?: boolean;+ mobileScannerImageResolution?: string;+ mobileScannerPageFormat?: string;+ mobileScannerStretchToFit?: boolean;+ googleDriveEnabled?: boolean;+ googleDriveClientId?: string;+ googleDriveApiKey?: string;+ googleDriveAppId?: string;+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.css b/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.cssnew file mode 100644index 0000000000..b20e17a880--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.css@@ -0,0 +1,24 @@+.admin-system__card {+ display: flex;+ flex-direction: column;+ gap: var(--space-3, 0.75rem);+}++/* Permanent, not just during the focus pulse: an anchored jump would otherwise+ land the heading under the sticky search bar. */+.admin-system__heading {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin: 0;+ scroll-margin-top: 1rem;+ font-size: 0.9375rem;+ font-weight: var(--font-weight-semibold, 600);+ color: var(--c-text);+}++.admin-system__description {+ margin: -0.35rem 0 0;+ font-size: 0.8125rem;+ color: var(--c-text-subtle);+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsxnew file mode 100644index 0000000000..b9d282f76d--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsx@@ -0,0 +1,620 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { useLocation, useNavigate } from "react-router-dom";+import { Badge, Loader, Stack } from "@mantine/core";+import { useQueryClient } from "@tanstack/react-query";+import { alert } from "@app/components/toast";+import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";+import { useRestartServer } from "@app/components/shared/config/useRestartServer";+import { useAdminSettings } from "@app/hooks/useAdminSettings";+import { useSettingsDirty } from "@app/hooks/useSettingsDirty";+import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";+import apiClient from "@app/services/apiClient";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import { usePreferences } from "@app/contexts/PreferencesContext";+import { useUnsavedChanges } from "@app/contexts/UnsavedChangesContext";+import { qk } from "@app/query/keys";+import { toUnderscoreLanguages } from "@app/i18n";+import type {+ EndpointsSettingsData,+ FolderAccessSettingsData,+ GeneralSettingsData,+ StorageSharingSettingsData,+ UiDefaultsSettingsData,+} from "@app/components/shared/config/configSections/server/serverSettings";+import { SystemCard } from "@app/components/shared/config/configSections/server/SystemCard";+import { UserDefaultsCard } from "@app/components/shared/config/configSections/server/UserDefaultsCard";+import { EndpointManagementCard } from "@app/components/shared/config/configSections/server/EndpointManagementCard";+import { StorageSharingCard } from "@app/components/shared/config/configSections/server/StorageSharingCard";+import { FolderAccessCard } from "@app/components/shared/config/configSections/server/FolderAccessCard";+import { CustomPathsCard } from "@app/components/shared/config/configSections/server/CustomPathsCard";+import { CustomMetadataCard } from "@app/components/shared/config/configSections/server/CustomMetadataCard";+import { ServerCertificateCard } from "@app/components/shared/config/configSections/server/ServerCertificateCard";+import AdminFormDetectionSection from "@app/components/shared/config/configSections/AdminFormDetectionSection";+import "@app/components/shared/config/configSections/server/AdminSystemSection.css";++/** Every admin section this page drafts, and so every key a save invalidates. */+const SECTION_NAMES = [+ "general",+ "ui",+ "endpoints",+ "storage",+ "policies",+] as const;++/**+ * The server settings, previously six nav rows. Six sections' drafts sit+ * under one Save bar, so the page owns one composite dirty flag rather than a+ * flag per hook, and the cards below are presentational.+ *+ * Two things the split rows got away with and this page cannot: saves run one+ * after another (several sections PUT the same flat settings endpoint), and a+ * save refetches every section, because the System card writes+ * system.frontendUrl that the storage section reads under its own key.+ */+export default function AdminSystemSection() {+ const { t } = useTranslation();+ const location = useLocation();+ const navigate = useNavigate();+ const queryClient = useQueryClient();+ const { loginEnabled, validateLoginEnabled } = useLoginRequired();+ const {+ restartModalOpened,+ showRestartModal,+ closeRestartModal,+ restartServer,+ } = useRestartServer();+ const { updatePreference } = usePreferences();+ const { markClean } = useUnsavedChanges();+ // The folder-access entry box: page state so Discard clears it with the draft.+ const [newRoot, setNewRoot] = useState("");++ const {+ settings: general,+ setSettings: setGeneral,+ loading: generalLoading,+ saving: generalSaving,+ saveSettings: saveGeneral,+ isFieldPending: isGeneralFieldPending,+ } = useAdminSettings<GeneralSettingsData>({+ sectionName: "general",+ enabled: loginEnabled,+ fetchTransformer: async (): Promise<+ GeneralSettingsData & { _pending?: Record<string, unknown> }+ > => {+ const [uiResponse, systemResponse, premiumResponse] = await Promise.all([+ apiClient.get("/api/v1/admin/settings/section/ui"),+ apiClient.get("/api/v1/admin/settings/section/system"),+ apiClient.get("/api/v1/admin/settings/section/premium"),+ ]);++ const ui = { ...(uiResponse.data || {}) };+ const system = { ...(systemResponse.data || {}) };+ const premium = { ...(premiumResponse.data || {}) };++ ui.languages = Array.isArray(ui.languages)+ ? toUnderscoreLanguages(ui.languages)+ : [];++ const pipelinePaths = system.customPaths?.pipeline || {};+ const watchedFoldersDirs = Array.isArray(pipelinePaths.watchedFoldersDirs)+ ? pipelinePaths.watchedFoldersDirs+ : [];+ const normalizedWatchedFoldersDirs =+ watchedFoldersDirs.length > 0+ ? watchedFoldersDirs+ : pipelinePaths.watchedFoldersDir+ ? [pipelinePaths.watchedFoldersDir]+ : [];++ const result: GeneralSettingsData & {+ _pending?: Record<string, unknown>;+ } = {+ ui,+ system,+ // Was the Features row's own hook and its own GET of this same section.+ serverCertificate: system.serverCertificate || {+ enabled: true,+ organizationName: "Stirling PDF Inc",+ validity: 365,+ regenerateOnStartup: false,+ },+ customPaths: {+ ...(system.customPaths || {}),+ pipeline: {+ ...pipelinePaths,+ pipelineDir: pipelinePaths.pipelineDir || "",+ watchedFoldersDir: pipelinePaths.watchedFoldersDir || "",+ watchedFoldersDirs: normalizedWatchedFoldersDirs,+ finishedFoldersDir: pipelinePaths.finishedFoldersDir || "",+ },+ operations: {+ ...(system.customPaths?.operations || {}),+ weasyprint: system.customPaths?.operations?.weasyprint || "",+ unoconvert: system.customPaths?.operations?.unoconvert || "",+ },+ },+ customMetadata: premium.proFeatures?.customMetadata || {+ autoUpdateMetadata: false,+ author: "",+ creator: "",+ producer: "",+ },+ };++ // Merge pending blocks from all three endpoints+ const pendingBlock: Record<string, unknown> = {};+ if (ui._pending) {+ pendingBlock.ui = ui._pending;+ }+ if (system._pending) {+ pendingBlock.system = system._pending;+ }+ if (system._pending?.customPaths) {+ pendingBlock.customPaths = system._pending.customPaths;+ }+ if (system._pending?.serverCertificate) {+ pendingBlock.serverCertificate = system._pending.serverCertificate;+ }+ if (premium._pending?.proFeatures?.customMetadata) {+ pendingBlock.customMetadata =+ premium._pending.proFeatures.customMetadata;+ }++ if (Object.keys(pendingBlock).length > 0) {+ result._pending = pendingBlock;+ }++ return result;+ },+ saveTransformer: (settings: GeneralSettingsData) => {+ const deltaSettings: Record<string, unknown> = {+ "ui.appNameNavbar": settings.ui?.appNameNavbar,+ "ui.languages": settings.ui?.languages,+ "ui.logoStyle": settings.ui?.logoStyle,+ "ui.hideDisabledTools.googleDrive":+ settings.ui?.hideDisabledTools?.googleDrive,+ "ui.hideDisabledTools.mobileQRScanner":+ settings.ui?.hideDisabledTools?.mobileQRScanner,+ "system.defaultLocale": settings.system?.defaultLocale,+ "system.showUpdate": settings.system?.showUpdate,+ "system.showUpdateOnlyAdmin": settings.system?.showUpdateOnlyAdmin,+ "system.customHTMLFiles": settings.system?.customHTMLFiles,+ "system.fileUploadLimit": settings.system?.fileUploadLimit,+ "system.frontendUrl": settings.system?.frontendUrl,+ "premium.proFeatures.customMetadata.autoUpdateMetadata":+ settings.customMetadata?.autoUpdateMetadata,+ "premium.proFeatures.customMetadata.author":+ settings.customMetadata?.author,+ "premium.proFeatures.customMetadata.creator":+ settings.customMetadata?.creator,+ "premium.proFeatures.customMetadata.producer":+ settings.customMetadata?.producer,+ };++ if (settings.serverCertificate) {+ deltaSettings["system.serverCertificate.enabled"] =+ settings.serverCertificate.enabled;+ deltaSettings["system.serverCertificate.organizationName"] =+ settings.serverCertificate.organizationName;+ deltaSettings["system.serverCertificate.validity"] =+ settings.serverCertificate.validity;+ deltaSettings["system.serverCertificate.regenerateOnStartup"] =+ settings.serverCertificate.regenerateOnStartup;+ }++ if (settings.customPaths) {+ deltaSettings["system.customPaths.pipeline.pipelineDir"] =+ settings.customPaths?.pipeline?.pipelineDir;+ deltaSettings["system.customPaths.pipeline.watchedFoldersDir"] =+ settings.customPaths?.pipeline?.watchedFoldersDir;+ deltaSettings["system.customPaths.pipeline.watchedFoldersDirs"] =+ settings.customPaths?.pipeline?.watchedFoldersDirs;+ deltaSettings["system.customPaths.pipeline.finishedFoldersDir"] =+ settings.customPaths?.pipeline?.finishedFoldersDir;+ deltaSettings["system.customPaths.operations.weasyprint"] =+ settings.customPaths?.operations?.weasyprint;+ deltaSettings["system.customPaths.operations.unoconvert"] =+ settings.customPaths?.operations?.unoconvert;+ }++ return {+ sectionData: {},+ deltaSettings,+ };+ },+ });++ const {+ settings: uiDefaults,+ setSettings: setUiDefaults,+ loading: uiLoading,+ saving: uiSaving,+ saveSettings: saveUiDefaults,+ isFieldPending: isUiFieldPending,+ } = useAdminSettings<UiDefaultsSettingsData>({+ sectionName: "ui",+ enabled: loginEnabled,+ });++ const {+ settings: endpoints,+ setSettings: setEndpoints,+ loading: endpointsLoading,+ saving: endpointsSaving,+ saveSettings: saveEndpoints,+ isFieldPending: isEndpointsFieldPending,+ } = useAdminSettings<EndpointsSettingsData>({+ sectionName: "endpoints",+ enabled: loginEnabled,+ });++ const {+ settings: storage,+ setSettings: setStorage,+ loading: storageLoading,+ saving: storageSaving,+ saveSettings: saveStorage,+ isFieldPending: isStorageFieldPending,+ } = useAdminSettings<StorageSharingSettingsData>({+ sectionName: "storage",+ enabled: loginEnabled,+ fetchTransformer: async () => {+ const [storageResponse, systemResponse, mailResponse] = await Promise.all(+ [+ apiClient.get("/api/v1/admin/settings/section/storage"),+ apiClient.get("/api/v1/admin/settings/section/system"),+ apiClient.get("/api/v1/admin/settings/section/mail"),+ ],+ );++ const storageData = storageResponse.data || {};+ const systemData = systemResponse.data || {};+ const mailData = mailResponse.data || {};++ return {+ ...storageData,+ system: { frontendUrl: systemData.frontendUrl || "" },+ mail: { enabled: mailData.enabled || false },+ };+ },+ saveTransformer: (currentSettings) => ({+ sectionData: {+ enabled: currentSettings.enabled,+ sharing: {+ enabled: currentSettings.sharing?.enabled,+ linkEnabled: currentSettings.sharing?.linkEnabled,+ emailEnabled: currentSettings.sharing?.emailEnabled,+ },+ signing: {+ enabled: currentSettings.signing?.enabled,+ },+ },+ }),+ });++ const {+ settings: folderAccess,+ setSettings: setFolderAccess,+ loading: policiesLoading,+ saving: policiesSaving,+ saveSettings: savePolicies,+ isFieldPending: isPoliciesFieldPending,+ } = useAdminSettings<FolderAccessSettingsData>({+ sectionName: "policies",+ enabled: loginEnabled,+ });++ // Every hook's loading, and the ternary because a disabled query never+ // settles: a composite draft always has keys, so this is the only guard left+ // between useSettingsDirty and a snapshot taken mid-fetch.+ const loading = loginEnabled+ ? generalLoading ||+ uiLoading ||+ endpointsLoading ||+ storageLoading ||+ policiesLoading+ : false;++ const composite = useMemo(+ () => ({ general, uiDefaults, endpoints, storage, folderAccess }),+ [general, uiDefaults, endpoints, storage, folderAccess],+ );++ const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(+ composite,+ loading,+ );++ // Sync local preference with server setting on initial load+ useEffect(() => {+ if (loading || !loginEnabled || !general.ui?.logoStyle) return;++ // This ensures localStorage always reflects the server's authoritative value+ updatePreference("logoVariant", general.ui.logoStyle);+ }, [loading, loginEnabled, general.ui?.logoStyle, updatePreference]);++ // Handle hash navigation for deep linking to specific fields+ useEffect(() => {+ if (location.hash && !loading) {+ const elementId = location.hash.substring(1); // Remove the #+ const element = document.getElementById(elementId);+ if (element) {+ setTimeout(() => {+ element.scrollIntoView({ behavior: "smooth", block: "start" });+ }, 100);+ }+ }+ }, [location.hash, loading]);++ const handleSave = async () => {+ // Block save if login is disabled+ if (!validateLoginEnabled()) {+ return;+ }++ const results: PromiseSettledResult<void>[] = [];+ for (const save of [+ saveGeneral,+ saveUiDefaults,+ saveEndpoints,+ saveStorage,+ savePolicies,+ ]) {+ // Sequential, not Promise.all: these sections PUT the same flat settings+ // endpoint and would overwrite each other's merge. A clean section's save+ // is a no-op, so running all six costs nothing.+ const [result] = await Promise.allSettled([save()]);+ results.push(result);+ }++ if (results.some((result) => result.status === "rejected")) {+ // No markSaved on a partial failure: re-snapshotting would clear the+ // footer while drafts that never reached the server are still on screen.+ alert({+ alertType: "error",+ title: t("admin.error", "Error"),+ body: t("admin.settings.saveError", "Failed to save settings"),+ });+ return;+ }++ // Each hook invalidates only its own key, but these sections read each+ // other: storage decides whether Share Links is usable from the+ // system.frontendUrl the System card just wrote.+ for (const section of SECTION_NAMES) {+ queryClient.invalidateQueries({ queryKey: qk.adminSection(section) });+ }++ // Update local preference after successful save so the app reflects the saved logo style+ if (general.ui?.logoStyle) {+ updatePreference("logoVariant", general.ui.logoStyle);+ }++ markSaved();+ markClean();+ showRestartModal();+ };++ const handleDiscard = useCallback(() => {+ const original = resetToSnapshot();+ setGeneral(original.general);+ setUiDefaults(original.uiDefaults);+ setEndpoints(original.endpoints);+ setStorage(original.storage);+ setFolderAccess(original.folderAccess);+ setNewRoot("");+ }, [+ resetToSnapshot,+ setGeneral,+ setUiDefaults,+ setEndpoints,+ setStorage,+ setFolderAccess,+ ]);++ if (loading) {+ return (+ <Stack align="center" justify="center" h={200}>+ <Loader size="lg" />+ </Stack>+ );+ }++ const generalCard = {+ settings: general,+ setSettings: setGeneral,+ isFieldPending: isGeneralFieldPending,+ loginEnabled,+ };++ return (+ <div className="settings-section-container">+ <Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminGeneral"+ title={t("admin.settings.general.branding", "Branding & appearance")}+ >+ <SystemCard {...generalCard} />+ </SettingsCard>++ <SettingsCard+ id="adminUserDefaults"+ title={t(+ "admin.settings.endpoints.userDefaults",+ "User Preference Defaults",+ )}+ description={t(+ "admin.settings.endpoints.userDefaultsDescription",+ "Set default values for user preferences. Users can override these in their personal settings.",+ )}+ >+ <UserDefaultsCard+ settings={uiDefaults}+ setSettings={setUiDefaults}+ isFieldPending={isUiFieldPending}+ loginEnabled={loginEnabled}+ />+ </SettingsCard>++ <SettingsCard+ id="adminEndpoints"+ title={t(+ "admin.settings.endpoints.management",+ "Endpoint Management",+ )}+ description={t(+ "admin.settings.endpoints.description",+ "Turn individual tools or whole groups off for everyone on this server.",+ )}+ >+ <EndpointManagementCard+ settings={endpoints}+ setSettings={setEndpoints}+ isFieldPending={isEndpointsFieldPending}+ loginEnabled={loginEnabled}+ />+ </SettingsCard>++ <SettingsCard+ id="adminStorageSharing"+ title={t(+ "settings.configuration.storageSharing",+ "File Storage & Sharing",+ )}+ description={t(+ "admin.settings.storage.description",+ "Where files are stored, and whether people can share them by link or email.",+ )}+ badge={+ <Badge component="span" color="orange" size="sm">+ {t("toolPanel.alpha", "Alpha")}+ </Badge>+ }+ >+ <StorageSharingCard+ settings={storage}+ setSettings={setStorage}+ isFieldPending={isStorageFieldPending}+ loginEnabled={loginEnabled}+ />+ </SettingsCard>++ <SettingsCard+ id="adminFolderAccess"+ title={t("settings.configuration.folderAccess", "Folder Access")}+ description={t(+ "admin.settings.folderAccess.description",+ "Directories that folder sources and folder outputs are allowed to read from and write to.",+ )}+ >+ <FolderAccessCard+ settings={folderAccess}+ setSettings={setFolderAccess}+ isFieldPending={isPoliciesFieldPending}+ loginEnabled={loginEnabled}+ newRoot={newRoot}+ setNewRoot={setNewRoot}+ />+ </SettingsCard>++ <SettingsCard+ id="adminGeneralCustomPaths"+ title={t("admin.settings.general.customPaths.label", "Custom Paths")}+ description={t(+ "admin.settings.general.customPaths.description",+ "Configure custom file system paths for pipeline processing and external tools",+ )}+ >+ <CustomPathsCard {...generalCard} />+ </SettingsCard>++ <SettingsCard+ id="adminGeneralCustomMetadata"+ title={t(+ "admin.settings.general.customMetadata.label",+ "Custom Metadata",+ )}+ badge={+ <Badge+ component="span"+ color="grape"+ size="sm"+ style={{ cursor: "pointer" }}+ onClick={() => navigate("/settings/adminPlan")}+ title={t(+ "admin.settings.badge.clickToUpgrade",+ "Click to view plan details",+ )}+ >+ PRO+ </Badge>+ }+ >+ <CustomMetadataCard {...generalCard} />+ </SettingsCard>++ <SettingsCard+ id="adminFeatures"+ title={t(+ "admin.settings.features.serverCertificate.label",+ "Certificate Signing",+ )}+ description={t(+ "admin.settings.features.serverCertificate.description",+ 'Generate the certificate that backs the "Sign with Stirling-PDF" signing feature.',+ )}+ badge={+ <Badge+ component="span"+ color="grape"+ size="sm"+ style={{ cursor: "pointer" }}+ onClick={() => navigate("/settings/adminPlan")}+ title={t(+ "admin.settings.badge.clickToUpgrade",+ "Click to view plan details",+ )}+ >+ PRO+ </Badge>+ }+ >+ <ServerCertificateCard {...generalCard} />+ </SettingsCard>++ <SettingsCard+ id="adminFormDetection"+ title={t("admin.formDetection.title", "AI Form Detection")}+ description={t(+ "admin.formDetection.description",+ "Detects text fields, checkboxes and signature areas in a PDF and turns them into fillable form fields. Detection runs on this server with the model you install below.",+ )}+ >+ <AdminFormDetectionSection />+ </SettingsCard>+ </Stack>++ <SettingsStickyFooter+ isDirty={isDirty}+ saving={+ generalSaving ||+ uiSaving ||+ endpointsSaving ||+ storageSaving ||+ policiesSaving+ }+ loginEnabled={loginEnabled}+ onSave={handleSave}+ onDiscard={handleDiscard}+ />++ <RestartConfirmationModal+ opened={restartModalOpened}+ onClose={closeRestartModal}+ onRestart={restartServer}+ />+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/CustomMetadataCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/CustomMetadataCard.tsxnew file mode 100644index 0000000000..09ab64e17b--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/CustomMetadataCard.tsx@@ -0,0 +1,149 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { TextInput, Stack, Paper, Group } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import type { GeneralCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/** Metadata stamped onto every processed document. Saved under premium.proFeatures. */+export function CustomMetadataCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: GeneralCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.general.customMetadata.autoUpdate.label",+ "Auto Update Metadata",+ )}+ info={t(+ "admin.settings.general.customMetadata.autoUpdate.description",+ "Automatically update PDF metadata on all processed documents",+ )}+ pending={isFieldPending("customMetadata.autoUpdateMetadata")}+ checked={settings.customMetadata?.autoUpdateMetadata || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ customMetadata: {+ ...settings.customMetadata,+ autoUpdateMetadata: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customMetadata.author.label",+ "Default Author",+ )}+ </span>+ <PendingBadge show={isFieldPending("customMetadata.author")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.customMetadata.author.description",+ "Default author for PDF metadata (e.g., username)",+ )}+ />+ </Group>+ }+ value={settings.customMetadata?.author || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customMetadata: {+ ...settings.customMetadata,+ author: e.target.value,+ },+ })+ }+ placeholder="username"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customMetadata.creator.label",+ "Default Creator",+ )}+ </span>+ <PendingBadge show={isFieldPending("customMetadata.creator")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.customMetadata.creator.description",+ "Default creator for PDF metadata",+ )}+ />+ </Group>+ }+ value={settings.customMetadata?.creator || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customMetadata: {+ ...settings.customMetadata,+ creator: e.target.value,+ },+ })+ }+ placeholder="Stirling-PDF"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customMetadata.producer.label",+ "Default Producer",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("customMetadata.producer")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.general.customMetadata.producer.description",+ "Default producer for PDF metadata",+ )}+ />+ </Group>+ }+ value={settings.customMetadata?.producer || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customMetadata: {+ ...settings.customMetadata,+ producer: e.target.value,+ },+ })+ }+ placeholder="Stirling-PDF"+ disabled={!loginEnabled}+ />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/CustomPathsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/CustomPathsCard.tsxnew file mode 100644index 0000000000..2779682aa2--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/CustomPathsCard.tsx@@ -0,0 +1,330 @@+import { useCallback, useMemo } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useTranslation } from "react-i18next";+import { TextInput, Textarea, Stack, Paper, Text, Group } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import type { GeneralCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/** Pipeline directories and external tool paths, all under system.customPaths. */+export function CustomPathsCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: GeneralCardProps) {+ const { t } = useTranslation();++ const parseWatchedFoldersInput = useCallback((value: string) => {+ const paths = value+ .split(/[\n,;]+/)+ .map((entry) => entry.trim())+ .filter(Boolean);++ // Deduplicate paths (case-sensitive, exact match)+ const uniquePaths = Array.from(new Set(paths));++ return uniquePaths;+ }, []);++ const watchedFoldersInput = useMemo(+ () => (settings.customPaths?.pipeline?.watchedFoldersDirs || []).join("\n"),+ [settings.customPaths?.pipeline?.watchedFoldersDirs],+ );++ const watchedFoldersValidation = useMemo(() => {+ const paths = settings.customPaths?.pipeline?.watchedFoldersDirs || [];+ const finishedPath =+ settings.customPaths?.pipeline?.finishedFoldersDir || "";+ const warnings: string[] = [];++ // Normalize paths for comparison (handle both Windows and Unix paths)+ const normalizePath = (p: string) =>+ p.replace(/\\/g, "/").replace(/\/+$/, "");++ // Check for overlapping watched folders+ if (paths.length >= 2) {+ for (let i = 0; i < paths.length; i++) {+ for (let j = i + 1; j < paths.length; j++) {+ const path1 = normalizePath(paths[i]);+ const path2 = normalizePath(paths[j]);++ if (path1 === path2) {+ warnings.push(`Duplicate path detected: '${paths[i]}'`);+ } else if (path1.startsWith(path2 + "/")) {+ warnings.push(+ `'${paths[i]}' is nested inside '${paths[j]}' - may cause duplicate processing`,+ );+ } else if (path2.startsWith(path1 + "/")) {+ warnings.push(+ `'${paths[j]}' is nested inside '${paths[i]}' - may cause duplicate processing`,+ );+ }+ }+ }+ }++ // Check for conflicts with finished folder+ if (finishedPath && paths.length > 0) {+ const normalizedFinished = normalizePath(finishedPath);+ for (const watchedPath of paths) {+ const normalizedWatched = normalizePath(watchedPath);++ if (normalizedWatched === normalizedFinished) {+ warnings.push(+ `CRITICAL: Watched folder '${watchedPath}' is the same as finished folder - will cause processing loops!`,+ );+ } else if (normalizedFinished.startsWith(normalizedWatched + "/")) {+ warnings.push(+ `Finished folder is nested inside watched folder '${watchedPath}' - may cause issues`,+ );+ } else if (normalizedWatched.startsWith(normalizedFinished + "/")) {+ warnings.push(+ `CRITICAL: Watched folder '${watchedPath}' is nested inside finished folder - will cause processing loops!`,+ );+ }+ }+ }++ return warnings.length > 0 ? warnings : null;+ }, [+ settings.customPaths?.pipeline?.watchedFoldersDirs,+ settings.customPaths?.pipeline?.finishedFoldersDir,+ ]);++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Text fw={500} size="sm" mt="xs">+ {t(+ "admin.settings.general.customPaths.pipeline.label",+ "Pipeline Directories",+ )}+ </Text>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customPaths.pipeline.pipelineDir.label",+ "Pipeline Directory",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("customPaths.pipeline.pipelineDir")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.general.customPaths.pipeline.pipelineDir.description",+ "Base directory for pipeline resources (leave empty for default: /pipeline)",+ )}+ />+ </Group>+ }+ value={settings.customPaths?.pipeline?.pipelineDir || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customPaths: {+ ...settings.customPaths,+ pipeline: {+ ...settings.customPaths?.pipeline,+ pipelineDir: e.target.value,+ },+ },+ })+ }+ placeholder="/pipeline"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <Textarea+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customPaths.pipeline.watchedFoldersDirs.label",+ "Watched Folders Directories",+ )}+ </span>+ <PendingBadge+ show={+ isFieldPending("customPaths.pipeline.watchedFoldersDirs") ||+ isFieldPending("customPaths.pipeline.watchedFoldersDir")+ }+ />+ <InfoTooltip+ label={t(+ "admin.settings.general.customPaths.pipeline.watchedFoldersDirs.description",+ "Directories where pipeline monitors for incoming PDFs (one per line or comma-separated; leave empty for default: /pipeline/watchedFolders)",+ )}+ />+ </Group>+ }+ value={watchedFoldersInput}+ onChange={(e) => {+ const parsedDirs = parseWatchedFoldersInput(e.target.value);+ setSettings({+ ...settings,+ customPaths: {+ ...settings.customPaths,+ pipeline: {+ ...settings.customPaths?.pipeline,+ watchedFoldersDir: parsedDirs[0] || "",+ watchedFoldersDirs: parsedDirs,+ },+ },+ });+ }}+ placeholder="/pipeline/watchedFolders"+ minRows={3}+ autosize+ disabled={!loginEnabled}+ />+ {watchedFoldersValidation && (+ <Stack gap="xs" mt="xs">+ {watchedFoldersValidation.map((warning, idx) => (+ <Text+ key={idx}+ size="sm"+ c={warning.includes("CRITICAL") ? "red" : "yellow"}+ >+ {warning}+ </Text>+ ))}+ </Stack>+ )}+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customPaths.pipeline.finishedFoldersDir.label",+ "Finished Folders Directory",+ )}+ </span>+ <PendingBadge+ show={isFieldPending(+ "customPaths.pipeline.finishedFoldersDir",+ )}+ />+ <InfoTooltip+ label={t(+ "admin.settings.general.customPaths.pipeline.finishedFoldersDir.description",+ "Directory where processed PDFs are outputted (leave empty for default: /pipeline/finishedFolders)",+ )}+ />+ </Group>+ }+ value={settings.customPaths?.pipeline?.finishedFoldersDir || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customPaths: {+ ...settings.customPaths,+ pipeline: {+ ...settings.customPaths?.pipeline,+ finishedFoldersDir: e.target.value,+ },+ },+ })+ }+ placeholder="/pipeline/finishedFolders"+ disabled={!loginEnabled}+ />+ </div>++ <Text fw={500} size="sm" mt="md">+ {t(+ "admin.settings.general.customPaths.operations.label",+ "External Tool Paths",+ )}+ </Text>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customPaths.operations.weasyprint.label",+ "WeasyPrint Executable",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("customPaths.operations.weasyprint")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.general.customPaths.operations.weasyprint.description",+ "Path to WeasyPrint executable for HTML to PDF conversion (leave empty for default: /opt/venv/bin/weasyprint)",+ )}+ />+ </Group>+ }+ value={settings.customPaths?.operations?.weasyprint || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customPaths: {+ ...settings.customPaths,+ operations: {+ ...settings.customPaths?.operations,+ weasyprint: e.target.value,+ },+ },+ })+ }+ placeholder="/opt/venv/bin/weasyprint"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.customPaths.operations.unoconvert.label",+ "Unoconvert Executable",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("customPaths.operations.unoconvert")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.general.customPaths.operations.unoconvert.description",+ "Path to LibreOffice unoconvert for document conversions (leave empty for default: /opt/venv/bin/unoconvert)",+ )}+ />+ </Group>+ }+ value={settings.customPaths?.operations?.unoconvert || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ customPaths: {+ ...settings.customPaths,+ operations: {+ ...settings.customPaths?.operations,+ unoconvert: e.target.value,+ },+ },+ })+ }+ placeholder="/opt/venv/bin/unoconvert"+ disabled={!loginEnabled}+ />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsxnew file mode 100644index 0000000000..e038ebe1f0--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsx@@ -0,0 +1,215 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { Stack, Paper, Group, MultiSelect } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { EndpointsCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++// Complete list of all endpoints from frontend tool registry (alphabetical)+const commonEndpoints = [+ "add-attachments",+ "add-image",+ "add-page-numbers",+ "add-password",+ "add-stamp",+ "add-watermark",+ "adjust-contrast",+ "auto-redact",+ "auto-rename",+ "auto-split-pdf",+ "automate",+ "booklet-imposition",+ "cert-sign",+ "compare",+ "compress-pdf",+ "crop",+ "dev-airgapped-docs",+ "dev-api-docs",+ "dev-folder-scanning-docs",+ "dev-sso-guide-docs",+ "edit-table-of-contents",+ "eml-to-pdf",+ "extract-image-scans",+ "extract-images",+ "file-to-pdf",+ "flatten",+ "get-info-on-pdf",+ "handleData",+ "html-to-pdf",+ "img-to-pdf",+ "markdown-to-pdf",+ "merge-pdfs",+ "multi-page-layout",+ "multi-tool",+ "ocr-pdf",+ "overlay-pdf",+ "pdf-to-csv",+ "pdf-to-xlsx",+ "pdf-to-epub",+ "pdf-to-html",+ "pdf-to-img",+ "pdf-to-markdown",+ "pdf-to-pdfa",+ "pdf-to-presentation",+ "pdf-to-single-page",+ "pdf-to-text",+ "pdf-to-word",+ "pdf-to-xml",+ "pipeline",+ "rearrange-pages",+ "remove-annotations",+ "remove-blanks",+ "remove-cert-sign",+ "remove-image-pdf",+ "remove-pages",+ "remove-password",+ "repair",+ "replace-invert-pdf",+ "rotate-pdf",+ "sanitize-pdf",+ "scale-pages",+ "scanner-effect",+ "show-javascript",+ "sign",+ "split-by-size-or-count",+ "split-pages",+ "split-pdf-by-chapters",+ "split-pdf-by-sections",+ "text-editor-pdf",+ "unlock-pdf-forms",+ "update-metadata",+ "validate-signature",+ "view-pdf",+];++// Complete list of functional and tool groups from EndpointConfiguration.java+const commonGroups = [+ // Functional Groups+ "PageOps",+ "Convert",+ "Security",+ "Other",+ "Advance",+ "Automation",+ "DeveloperTools",+ "DeveloperDocs",+ // Tool Groups+ "CLI",+ "Python",+ "OpenCV",+ "LibreOffice",+ "Unoconvert",+ "Java",+ "Javascript",+ "qpdf",+ "Ghostscript",+ "ImageMagick",+ "tesseract",+ "OCRmyPDF",+ "Weasyprint",+ "Pdftohtml",+ "Calibre",+ "FFmpeg",+ "veraPDF",+ "rar",+];++/** Which endpoints and endpoint groups the server refuses to expose. */+export function EndpointManagementCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: EndpointsCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div>+ <MultiSelect+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.endpoints.toRemove.label",+ "Disabled Endpoints",+ )}+ </span>+ <PendingBadge show={isFieldPending("toRemove")} />+ <InfoTooltip+ label={t(+ "admin.settings.endpoints.toRemove.description",+ "Select individual endpoints to disable",+ )}+ />+ </Group>+ }+ value={settings.toRemove || []}+ onChange={(value) => {+ if (!loginEnabled) return;+ setSettings({ ...settings, toRemove: value });+ }}+ data={commonEndpoints.map((endpoint) => ({+ value: endpoint,+ label: endpoint,+ }))}+ searchable+ clearable+ placeholder={t(+ "admin.settings.endpoints.toRemove.placeholder",+ "Select endpoints to disable",+ )}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <MultiSelect+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.endpoints.groupsToRemove.label",+ "Disabled Endpoint Groups",+ )}+ </span>+ <PendingBadge show={isFieldPending("groupsToRemove")} />+ <InfoTooltip+ label={t(+ "admin.settings.endpoints.groupsToRemove.description",+ "Select endpoint groups to disable",+ )}+ />+ </Group>+ }+ value={settings.groupsToRemove || []}+ onChange={(value) => {+ if (!loginEnabled) return;+ setSettings({ ...settings, groupsToRemove: value });+ }}+ data={commonGroups.map((group) => ({+ value: group,+ label: group,+ }))}+ searchable+ clearable+ placeholder={t(+ "admin.settings.endpoints.groupsToRemove.placeholder",+ "Select groups to disable",+ )}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsxnew file mode 100644index 0000000000..a8cc1a666d--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsx@@ -0,0 +1,217 @@+import { useCallback, useEffect, useState } from "react";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useTranslation } from "react-i18next";+import {+ Code,+ Divider,+ Group,+ Paper,+ Stack,+ Text,+ TextInput,+} from "@mantine/core";+import { Button } from "@app/ui/Button";+import LocalIcon from "@app/components/shared/LocalIcon";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import apiClient from "@app/services/apiClient";+import type { ImpliedFolderRoot } from "@app/components/shared/config/configSections/server/serverSettings";+import type { FolderAccessCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/** The directories folder sources and outputs may touch. A security boundary. */+export function FolderAccessCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+ newRoot,+ setNewRoot,+}: FolderAccessCardProps) {+ const { t } = useTranslation();+ const { getDisabledStyles } = useLoginRequired();++ const [impliedRoots, setImpliedRoots] = useState<ImpliedFolderRoot[]>([]);++ useEffect(() => {+ if (!loginEnabled) return;+ apiClient+ .get<ImpliedFolderRoot[]>(+ "/api/v1/admin/settings/policies/implied-folder-roots",+ )+ .then((res) => setImpliedRoots(res.data ?? []))+ .catch(() => setImpliedRoots([]));+ }, [loginEnabled]);++ const roots = settings.allowedFolderRoots ?? [];++ const reasonLabel = (reason: string) => {+ switch (reason) {+ case "serverStorage":+ return t(+ "admin.settings.folderAccess.implied.serverStorage",+ "Server file storage",+ );+ case "watchedFolder":+ return t(+ "admin.settings.folderAccess.implied.watchedFolder",+ "Pipeline watched folder",+ );+ default:+ return reason;+ }+ };++ const setRoots = useCallback(+ (next: string[]) => {+ setSettings({ ...settings, allowedFolderRoots: next });+ },+ [settings, setSettings],+ );++ const addRoot = useCallback(() => {+ const value = newRoot.trim();+ if (!value) return;+ if (roots.includes(value)) {+ setNewRoot("");+ return;+ }+ setRoots([...roots, value]);+ setNewRoot("");+ }, [newRoot, roots, setNewRoot, setRoots]);++ const removeRoot = useCallback(+ (value: string) => {+ setRoots(roots.filter((root) => root !== value));+ },+ [roots, setRoots],+ );++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Group gap="xs" align="center">+ <Text fw={500} size="sm">+ {t(+ "admin.settings.folderAccess.roots.label",+ "Allowed folder roots",+ )}+ </Text>+ <PendingBadge show={isFieldPending("allowedFolderRoots")} />+ <InfoTooltip+ label={t(+ "admin.settings.folderAccess.roots.hint",+ "Enter absolute paths, for example /data/inbox.",+ )}+ />+ </Group>++ <Text size="xs" c="dimmed">+ {t(+ "admin.settings.folderAccess.securityNote",+ "Leave this empty to disable folder sources and outputs entirely. Stirling's own configuration directory is always off-limits, and folder access is always disabled in hosted (SaaS) mode.",+ )}+ </Text>++ {roots.length === 0 ? (+ <Text size="sm" c="dimmed" fs="italic">+ {t(+ "admin.settings.folderAccess.roots.empty",+ "No folders allowed. Folder sources and outputs are currently disabled.",+ )}+ </Text>+ ) : (+ <Stack gap="xs">+ {roots.map((root) => (+ <Group key={root} justify="space-between" wrap="nowrap" gap="xs">+ <Code style={{ wordBreak: "break-all" }}>{root}</Code>+ <Button+ variant="tertiary"+ aria-label={t(+ "admin.settings.folderAccess.roots.remove",+ "Remove folder root",+ )}+ leftSection={+ <LocalIcon+ icon="close-rounded"+ width="1.1rem"+ height="1.1rem"+ />+ }+ onClick={() => removeRoot(root)}+ disabled={!loginEnabled}+ style={{ flexShrink: 0 }}+ />+ </Group>+ ))}+ </Stack>+ )}++ <Group gap="xs" align="flex-end" wrap="nowrap">+ <TextInput+ style={{ flex: 1 }}+ value={newRoot}+ onChange={(e) => setNewRoot(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ addRoot();+ }+ }}+ placeholder={t(+ "admin.settings.folderAccess.roots.placeholder",+ "/data/inbox",+ )}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ <Button+ variant="secondary"+ onClick={addRoot}+ disabled={!loginEnabled || newRoot.trim().length === 0}+ >+ {t("admin.settings.folderAccess.roots.add", "Add")}+ </Button>+ </Group>++ {impliedRoots.length > 0 && (+ <>+ <Divider />+ <Group gap="xs" align="center">+ <Text fw={500} size="sm">+ {t(+ "admin.settings.folderAccess.implied.title",+ "Always allowed",+ )}+ </Text>+ <InfoTooltip+ label={t(+ "admin.settings.folderAccess.implied.description",+ "These Stirling-managed directories are always permitted and can't be changed here.",+ )}+ />+ </Group>+ <Stack gap="xs">+ {impliedRoots.map((root) => (+ <Group+ key={root.path}+ justify="space-between"+ wrap="nowrap"+ gap="xs"+ align="center"+ >+ <Code style={{ wordBreak: "break-all" }}>{root.path}</Code>+ <Group gap={6} wrap="nowrap" style={{ flexShrink: 0 }}>+ <Text size="xs" c="dimmed">+ {reasonLabel(root.reason)}+ </Text>+ <LocalIcon icon="lock" width="1rem" height="1rem" />+ </Group>+ </Group>+ ))}+ </Stack>+ </>+ )}+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/McpCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/McpCard.tsxnew file mode 100644index 0000000000..a2fc807972--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/McpCard.tsx@@ -0,0 +1,455 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import {+ TextInput,+ Textarea,+ Switch,+ Select,+ Stack,+ Paper,+ Text,+ Group,+ Alert,+ Code,+ List,+} from "@mantine/core";+import LocalIcon from "@app/components/shared/LocalIcon";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { McpAuthData } from "@app/components/shared/config/configSections/server/serverSettings";+import type { McpCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/** Parse a comma/space/newline separated list into a string[]. */+function parseOpList(raw: string): string[] {+ return raw+ .split(/[\s,]+/)+ .map((s) => s.trim())+ .filter(Boolean);+}++/** The MCP endpoint, how it authenticates, and which tools it exposes. */+export function McpCard({+ settings,+ setSettings,+ isFieldPending,+}: McpCardProps) {+ const { t } = useTranslation();++ const setAuth = (patch: Partial<McpAuthData>) =>+ setSettings({ ...settings, auth: { ...(settings.auth || {}), ...patch } });++ const baseUrl =+ typeof window !== "undefined"+ ? window.location.origin+ : "https://your-host";+ const mcpUrl = `${baseUrl}/mcp`;+ const metadataUrl = `${baseUrl}/.well-known/oauth-protected-resource`;+ const authMode = settings.auth?.mode || "oauth";++ return (+ <>+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <div>+ <Text fw={500} size="sm">+ {t("admin.settings.mcp.enabled.label", "Enable MCP Server")}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.mcp.enabled.description",+ "When off (default), no /mcp endpoint, metadata, or MCP beans are loaded.",+ )}+ />+ </Text>+ </div>+ <Group gap="xs">+ <Switch+ checked={settings.enabled || false}+ onChange={(e) =>+ setSettings({ ...settings, enabled: e.target.checked })+ }+ />+ <PendingBadge show={isFieldPending("enabled")} />+ </Group>+ </Group>++ <Select+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.mcp.mode.label", "Authentication mode")}+ </span>+ <PendingBadge show={isFieldPending("auth.mode")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.mode.description",+ "OAuth needs an external IdP. API key uses a Stirling per-user API key (X-API-KEY) - simplest for self-host.",+ )}+ />+ </Group>+ }+ data={[+ { value: "oauth", label: "OAuth 2.1 (external IdP)" },+ { value: "apikey", label: "API key (Stirling per-user key)" },+ ]}+ value={authMode}+ onChange={(v) => setAuth({ mode: v || "oauth" })}+ allowDeselect={false}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!settings.enabled}+ />++ {authMode === "apikey" && (+ <Alert variant="light" color="gray">+ <Text size="xs">+ {t(+ "admin.settings.mcp.apikeyNote",+ "Clients send a Stirling API key in the X-API-KEY header (or Authorization: Bearer <key>). The key maps to its owning Stirling user - only provisioned accounts get in, and actions are audited as that user. Manage keys under Account → API Keys.",+ )}+ </Text>+ </Alert>+ )}++ {authMode === "oauth" && (+ <>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.mcp.issuerUri.label",+ "OAuth Issuer URL",+ )}+ </span>+ <PendingBadge show={isFieldPending("auth.issuerUri")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.issuerUri.description",+ "Your OAuth2 authorization server (must publish /.well-known/openid-configuration). Required when enabled.",+ )}+ />+ </Group>+ }+ value={settings.auth?.issuerUri || ""}+ onChange={(e) => setAuth({ issuerUri: e.target.value })}+ placeholder="https://auth.example.com"+ disabled={!settings.enabled}+ />++ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.mcp.resourceId.label", "Resource ID")}+ </span>+ <PendingBadge show={isFieldPending("auth.resourceId")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.resourceId.description",+ "This server's public /mcp URL. Tokens must list it in their audience (RFC 8707) or they are rejected.",+ )}+ />+ </Group>+ }+ value={settings.auth?.resourceId || ""}+ onChange={(e) => setAuth({ resourceId: e.target.value })}+ placeholder={mcpUrl}+ disabled={!settings.enabled}+ />++ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.mcp.acceptedAudiences.label",+ "Additional accepted audiences (optional)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("auth.acceptedAudiences")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.acceptedAudiences.description",+ "Extra token audience values accepted besides the Resource ID (comma or space separated). Leave blank for strict RFC 8707. Needed for IdPs that cannot mint resource audiences - e.g. Supabase's OAuth server always issues aud=authenticated.",+ )}+ />+ </Group>+ }+ value={(settings.auth?.acceptedAudiences || []).join(" ")}+ onChange={(e) =>+ setAuth({ acceptedAudiences: parseOpList(e.target.value) })+ }+ placeholder="authenticated"+ disabled={!settings.enabled}+ />++ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.mcp.jwksUri.label",+ "JWKS URL (optional)",+ )}+ </span>+ <PendingBadge show={isFieldPending("auth.jwksUri")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.jwksUri.description",+ "Leave blank to discover it from the issuer. Set only if your IdP serves keys at a non-standard URL.",+ )}+ />+ </Group>+ }+ value={settings.auth?.jwksUri || ""}+ onChange={(e) => setAuth({ jwksUri: e.target.value })}+ placeholder={t(+ "admin.settings.mcp.jwksUri.placeholder",+ "Auto-discovered from issuer",+ )}+ disabled={!settings.enabled}+ />++ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <div>+ <Text fw={500} size="sm">+ {t(+ "admin.settings.mcp.scopes.label",+ "Enforce OAuth scopes",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.mcp.scopes.description",+ "Require mcp.tools.read for read ops and mcp.tools.write for write/AI ops.",+ )}+ />+ </Text>+ </div>+ <Group gap="xs">+ <Switch+ checked={settings.scopesEnabled ?? true}+ onChange={(e) =>+ setSettings({+ ...settings,+ scopesEnabled: e.target.checked,+ })+ }+ disabled={!settings.enabled}+ />+ <PendingBadge show={isFieldPending("scopesEnabled")} />+ </Group>+ </Group>++ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <div>+ <Text fw={500} size="sm">+ {t(+ "admin.settings.mcp.requireAccount.label",+ "Require an existing Stirling account",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.mcp.requireAccount.description",+ "Only let tokens through if their subject maps to a provisioned, enabled Stirling user.",+ )}+ />+ </Text>+ </div>+ <Group gap="xs">+ <Switch+ checked={settings.auth?.requireExistingAccount ?? true}+ onChange={(e) =>+ setAuth({ requireExistingAccount: e.target.checked })+ }+ disabled={!settings.enabled}+ />+ <PendingBadge+ show={isFieldPending("auth.requireExistingAccount")}+ />+ </Group>+ </Group>++ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.mcp.usernameClaim.label",+ "Username claim",+ )}+ </span>+ <PendingBadge show={isFieldPending("auth.usernameClaim")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.usernameClaim.description",+ "JWT claim matched against a Stirling username (e.g. sub, email, preferred_username).",+ )}+ />+ </Group>+ }+ value={settings.auth?.usernameClaim || ""}+ onChange={(e) => setAuth({ usernameClaim: e.target.value })}+ placeholder="sub"+ disabled={!settings.enabled}+ />+ </>+ )}++ <Textarea+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.mcp.allowedOps.label", "Allowed tools")}+ </span>+ <PendingBadge show={isFieldPending("allowedOperations")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.allowedOps.description",+ "If set, ONLY these operation ids are exposed (an allow-list; comma or space separated). Leave blank to expose all enabled tools except any blocked below.",+ )}+ />+ </Group>+ }+ value={(settings.allowedOperations || []).join(" ")}+ onChange={(e) =>+ setSettings({+ ...settings,+ allowedOperations: parseOpList(e.target.value),+ })+ }+ placeholder="merge-pdfs split-pdf rotate-pdf"+ autosize+ minRows={1}+ maxRows={3}+ disabled={!settings.enabled}+ />++ <Textarea+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.mcp.blockedOps.label", "Blocked tools")}+ </span>+ <PendingBadge show={isFieldPending("blockedOperations")} />+ <InfoTooltip+ label={t(+ "admin.settings.mcp.blockedOps.description",+ "Operation ids to hide from MCP (comma or space separated), e.g. add-password remove-password. Leave blank to expose all enabled tools.",+ )}+ />+ </Group>+ }+ value={(settings.blockedOperations || []).join(" ")}+ onChange={(e) =>+ setSettings({+ ...settings,+ blockedOperations: parseOpList(e.target.value),+ })+ }+ placeholder="add-password sanitize-pdf"+ autosize+ minRows={1}+ maxRows={3}+ disabled={!settings.enabled}+ />+ </Stack>+ </Paper>++ {/* Compact in-page setup guide */}+ <Alert+ variant="light"+ color="blue"+ title={t("admin.settings.mcp.guide.title", "Connect an MCP client")}+ icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}+ >+ <Stack gap={6}>+ <List size="xs" type="ordered" spacing={4}>+ {authMode === "oauth" ? (+ <>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step1",+ "Enter your OAuth issuer + resource ID above, Save, and restart.",+ )}+ </List.Item>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step2",+ "In your MCP client add a",+ )}{" "}+ <b>streamable-HTTP</b>{" "}+ {t("admin.settings.mcp.guide.step2b", "server pointing at:")}{" "}+ <Code>{mcpUrl}</Code>+ </List.Item>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step3",+ "The client auto-discovers OAuth from:",+ )}{" "}+ <Code>{metadataUrl}</Code>+ </List.Item>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step4",+ "Approve the sign-in; the client retries with a token. Tools appear grouped: convert, pages, misc, security, ai.",+ )}+ </List.Item>+ </>+ ) : (+ <>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step1ApiKey",+ "Create an API key under Account → API Keys (each user uses their own).",+ )}+ </List.Item>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step2",+ "In your MCP client add a",+ )}{" "}+ <b>streamable-HTTP</b>{" "}+ {t("admin.settings.mcp.guide.step2b", "server pointing at:")}{" "}+ <Code>{mcpUrl}</Code>+ </List.Item>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step3ApiKey",+ "Send the key in an",+ )}{" "}+ <Code>X-API-KEY</Code>{" "}+ {t(+ "admin.settings.mcp.guide.step3ApiKeyb",+ "header (or Authorization: Bearer <key>). No OAuth or metadata discovery is used.",+ )}+ </List.Item>+ <List.Item>+ {t(+ "admin.settings.mcp.guide.step4ApiKey",+ "Tools appear grouped: convert, pages, misc, security, ai - and every call is audited as the key's owner.",+ )}+ </List.Item>+ </>+ )}+ </List>+ <Text size="xs" c="dimmed">+ {authMode === "oauth"+ ? t(+ "admin.settings.mcp.guide.tip",+ "Tip: register the resource ID as an allowed audience in your IdP. Tested with MCP Inspector and Claude Desktop.",+ )+ : t(+ "admin.settings.mcp.guide.tipApiKey",+ "Tip: API-key mode needs no external IdP - simplest for self-host. The key maps to its owning Stirling user.",+ )}+ </Text>+ </Stack>+ </Alert>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/ServerCertificateCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/ServerCertificateCard.tsxnew file mode 100644index 0000000000..9c89d11d03--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/ServerCertificateCard.tsx@@ -0,0 +1,153 @@+import { useTranslation } from "react-i18next";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { TextInput, NumberInput, Stack, Paper, Group } from "@mantine/core";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type { GeneralCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/**+ * The certificate behind "Sign with Stirling-PDF". This was the whole Features+ * row: one hook whose key said "features" while it read and wrote the system+ * section, so it rides the general draft now.+ */+export function ServerCertificateCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: GeneralCardProps) {+ const { t } = useTranslation();+ const { getDisabledStyles } = useLoginRequired();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.features.serverCertificate.enabled.label",+ "Enable Certificate Signing",+ )}+ info={t(+ "admin.settings.features.serverCertificate.enabled.description",+ 'Offer "Sign with Stirling-PDF" using a certificate this server generates',+ )}+ pending={isFieldPending("serverCertificate.enabled")}+ checked={settings.serverCertificate?.enabled ?? true}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ serverCertificate: {+ ...settings.serverCertificate,+ enabled: checked,+ },+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.features.serverCertificate.organizationName.label",+ "Organization Name",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("serverCertificate.organizationName")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.features.serverCertificate.organizationName.description",+ "Organization name for generated certificates",+ )}+ />+ </Group>+ }+ value={+ settings.serverCertificate?.organizationName || "Stirling PDF Inc"+ }+ onChange={(e) =>+ setSettings({+ ...settings,+ serverCertificate: {+ ...settings.serverCertificate,+ organizationName: e.target.value,+ },+ })+ }+ placeholder="Stirling-PDF"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.features.serverCertificate.validity.label",+ "Certificate Validity (days)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("serverCertificate.validity")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.features.serverCertificate.validity.description",+ "Number of days the certificate will be valid",+ )}+ />+ </Group>+ }+ value={settings.serverCertificate?.validity ?? 365}+ onChange={(value) =>+ setSettings({+ ...settings,+ serverCertificate: {+ ...settings.serverCertificate,+ validity: Number(value),+ },+ })+ }+ min={1}+ max={3650}+ disabled={!loginEnabled}+ />+ </div>++ <SettingsToggleRow+ label={t(+ "admin.settings.features.serverCertificate.regenerateOnStartup.label",+ "Regenerate on Startup",+ )}+ info={t(+ "admin.settings.features.serverCertificate.regenerateOnStartup.description",+ "Generate new certificate on each application startup",+ )}+ pending={isFieldPending("serverCertificate.regenerateOnStartup")}+ checked={settings.serverCertificate?.regenerateOnStartup ?? false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ serverCertificate: {+ ...settings.serverCertificate,+ regenerateOnStartup: checked,+ },+ });+ }}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsxnew file mode 100644index 0000000000..976f148c78--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsx@@ -0,0 +1,183 @@+import { useTranslation } from "react-i18next";+import { Anchor, Paper, Stack } from "@mantine/core";+import { useNavigate } from "react-router-dom";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { useLoginRequired } from "@app/hooks/useLoginRequired";+import type { StorageSharingCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/**+ * Server-side file storage and what may be shared from it. The Frontend URL it+ * gates Share Links on is the System card's field, one draft over; the page+ * refetches this section after any save so filling that field in unlocks it.+ */+export function StorageSharingCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: StorageSharingCardProps) {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { getDisabledStyles } = useLoginRequired();++ const storageEnabled = settings.enabled ?? false;+ const sharingEnabled = storageEnabled && (settings.sharing?.enabled ?? false);+ const frontendUrlConfigured = Boolean(settings.system?.frontendUrl?.trim());+ const mailEnabled = Boolean(settings.mail?.enabled);++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.storage.enabled.label",+ "Enable Server File Storage",+ )}+ info={t(+ "admin.settings.storage.enabled.description",+ "Allow users to store files on the server.",+ )}+ pending={isFieldPending("enabled")}+ checked={storageEnabled}+ onChange={(checked) => setSettings({ ...settings, enabled: checked })}+ disabled={!loginEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.storage.sharing.enabled.label",+ "Enable Sharing",+ )}+ info={t(+ "admin.settings.storage.sharing.enabled.description",+ "Allow users to share stored files.",+ )}+ pending={isFieldPending("sharing.enabled")}+ checked={settings.sharing?.enabled ?? false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ sharing: { ...settings.sharing, enabled: checked },+ })+ }+ disabled={!loginEnabled || !storageEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.storage.sharing.links.label",+ "Enable Share Links",+ )}+ info={t(+ "admin.settings.storage.sharing.links.description",+ "Allow sharing via signed-in links.",+ )}+ pending={isFieldPending("sharing.linkEnabled")}+ note={+ !frontendUrlConfigured && (+ <>+ {t(+ "admin.settings.storage.sharing.links.frontendUrlNote",+ "Requires a Frontend URL. ",+ )}+ <Anchor+ href="#frontendUrl"+ onClick={(e) => {+ e.preventDefault();+ document+ .getElementById("frontendUrl")+ ?.scrollIntoView({ behavior: "smooth", block: "start" });+ }}+ inherit+ td="underline"+ >+ {t(+ "admin.settings.storage.sharing.links.frontendUrlLink",+ "Configure in System Settings",+ )}+ </Anchor>+ </>+ )+ }+ checked={settings.sharing?.linkEnabled ?? false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ sharing: { ...settings.sharing, linkEnabled: checked },+ })+ }+ disabled={!loginEnabled || !sharingEnabled || !frontendUrlConfigured}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.storage.sharing.email.label",+ "Enable Email Sharing",+ )}+ info={t(+ "admin.settings.storage.sharing.email.description",+ "Allow sharing with email addresses.",+ )}+ pending={isFieldPending("sharing.emailEnabled")}+ note={+ !mailEnabled && (+ <>+ {t(+ "admin.settings.storage.sharing.email.mailNote",+ "Requires mail configuration. ",+ )}+ <Anchor+ href="#adminConnections"+ onClick={(e) => {+ e.preventDefault();+ navigate("/settings/adminConnections#adminConnections");+ }}+ inherit+ td="underline"+ >+ {t(+ "admin.settings.storage.sharing.email.mailLink",+ "Configure Mail Settings",+ )}+ </Anchor>+ </>+ )+ }+ checked={settings.sharing?.emailEnabled ?? false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ sharing: { ...settings.sharing, emailEnabled: checked },+ })+ }+ disabled={!loginEnabled || !sharingEnabled || !mailEnabled}+ styles={getDisabledStyles()}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.storage.signing.enabled.label",+ "Enable Group Signing",+ )}+ info={t(+ "admin.settings.storage.signing.enabled.description",+ "Allow users to create multi-participant document signing sessions. Requires server file storage to be enabled.",+ )}+ pending={isFieldPending("signing.enabled")}+ checked={settings.signing?.enabled ?? false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ signing: { ...settings.signing, enabled: checked },+ })+ }+ disabled={!loginEnabled || !storageEnabled}+ styles={getDisabledStyles()}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/SystemCard.test.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/SystemCard.test.tsxnew file mode 100644index 0000000000..5ad2267440--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/SystemCard.test.tsx@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";++vi.mock("@app/contexts/PreferencesContext", () => ({+ usePreferences: () => ({ preferences: {}, updatePreference: vi.fn() }),+}));+vi.mock("react-i18next", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-i18next")>()),+ useTranslation: () => ({+ t: (_key: string, fallback?: string) => fallback ?? _key,+ i18n: { changeLanguage: vi.fn() },+ }),+}));++import { SystemCard } from "@app/components/shared/config/configSections/server/SystemCard";+import type { GeneralSettingsData } from "@app/components/shared/config/configSections/server/serverSettings";++function renderWithLocale(defaultLocale: string) {+ const settings = { ui: {}, system: { defaultLocale } } as GeneralSettingsData;+ render(+ <MantineProvider>+ <SystemCard+ settings={settings}+ setSettings={vi.fn()}+ isFieldPending={() => false}+ loginEnabled+ />+ </MantineProvider>,+ );+ return screen.getByPlaceholderText("en_US") as HTMLInputElement;+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("SystemCard default locale", () => {+ // The Select's options are keyed on the underscore form, but+ // SYSTEM_DEFAULTLOCALE accepts a hyphenated tag too, and the backend stores+ // whichever form was configured.+ it("shows the configured language for the underscore form", () => {+ expect(renderWithLocale("en_GB").value).toBe("English (UK) (en-GB)");+ });++ it("shows the configured language for the hyphenated form", () => {+ expect(renderWithLocale("en-GB").value).toBe("English (UK) (en-GB)");+ });++ it("matches a lowercased region tag", () => {+ expect(renderWithLocale("en-gb").value).toBe("English (UK) (en-GB)");+ });++ it("leaves the field empty when no locale is configured", () => {+ expect(renderWithLocale("").value).toBe("");+ });+});diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/SystemCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/SystemCard.tsxnew file mode 100644index 0000000000..ab674a8ea2--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/SystemCard.tsx@@ -0,0 +1,476 @@+import { useMemo } from "react";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import { InfoTooltip } from "@app/ui/InfoTooltip";+import { useTranslation } from "react-i18next";+import {+ TextInput,+ Stack,+ Paper,+ Text,+ Group,+ MultiSelect,+ Select,+} from "@mantine/core";+import { SegmentedControl } from "@app/ui/SegmentedControl";+import PendingBadge from "@app/components/shared/config/PendingBadge";+import { usePreferences } from "@app/contexts/PreferencesContext";+import {+ normalizeLanguageCode,+ supportedLanguages,+ toUnderscoreFormat,+ toUnderscoreLanguages,+} from "@app/i18n";+import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";+import type { GeneralCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/** Branding, languages and the system-wide toggles. Writes ui.* and system.*. */+export function SystemCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: GeneralCardProps) {+ const { t } = useTranslation();+ const { preferences, updatePreference } = usePreferences();++ const languageOptions = useMemo(+ () =>+ Object.entries(supportedLanguages)+ .map(([code, label]) => ({+ value: toUnderscoreFormat(code),+ label: `${label} (${code})`,+ }))+ .sort((a, b) => a.label.localeCompare(b.label)),+ [],+ );++ const selectedLanguages = useMemo(+ () => toUnderscoreLanguages(settings.ui?.languages || []),+ [settings.ui?.languages],+ );++ // SYSTEM_DEFAULTLOCALE accepts en-GB as well as en_GB, but every option below+ // is keyed on the underscore form, so match the stored value to it before+ // handing it to the Select. Normalising only what is displayed keeps the+ // configured value untouched when the field is left alone.+ const defaultLocaleValue = useMemo(+ () =>+ toUnderscoreFormat(+ normalizeLanguageCode(settings.system?.defaultLocale || ""),+ ),+ [settings.system?.defaultLocale],+ );++ // Filter default locale options based on available languages setting+ const defaultLocaleOptions = useMemo(() => {+ // If no languages are selected (empty), show all languages+ if (!selectedLanguages || selectedLanguages.length === 0) {+ return languageOptions;+ }+ // Otherwise, only show languages that are in the selected list+ return languageOptions.filter((option) =>+ selectedLanguages.includes(option.value),+ );+ }, [selectedLanguages, languageOptions]);++ // Show the server setting when loaded (for admin config), otherwise show user's preference+ // Note: User's preference in localStorage is separate and takes precedence in the app via useLogoVariant hook+ const logoStyleValue = loginEnabled+ ? (settings.ui?.logoStyle ?? preferences.logoVariant ?? "modern")+ : (preferences.logoVariant ?? "modern");++ const handleLogoStyleChange = (value: string) => {+ const nextValue = value === "classic" ? "classic" : "modern";++ // Only update local settings state - don't update the actual preference until save+ // When login is disabled, update preference immediately since there's no server to save to+ if (!loginEnabled) {+ updatePreference("logoVariant", nextValue);+ return;+ }++ setSettings({+ ...settings,+ ui: {+ ...settings.ui,+ logoStyle: nextValue,+ },+ });+ };++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.appNameNavbar.label",+ "Navbar Brand",+ )}+ </span>+ <PendingBadge show={isFieldPending("ui.appNameNavbar")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.appNameNavbar.description",+ "The name displayed in the navigation bar",+ )}+ />+ </Group>+ }+ value={settings.ui?.appNameNavbar || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ ui: { ...settings.ui, appNameNavbar: e.target.value },+ })+ }+ placeholder="Stirling PDF"+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <Text component="div" size="sm" fw={500} mb={4}>+ <Group gap="xs">+ <span>+ {t("admin.settings.general.logoStyle.label", "Logo Style")}+ </span>+ <PendingBadge show={isFieldPending("ui.logoStyle")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.logoStyle.description",+ "Choose between the modern minimalist logo or the classic S icon",+ )}+ />+ </Group>+ </Text>+ <SegmentedControl+ value={logoStyleValue}+ onChange={handleLogoStyleChange}+ options={[+ {+ value: "classic",+ label: (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ gap: "0.5rem",+ padding: "0.25rem 0",+ }}+ >+ <img+ src="classic-logo/favicon.ico"+ alt={t(+ "admin.settings.general.logoStyle.classicAlt",+ "Classic logo",+ )}+ style={{ width: "24px", height: "24px" }}+ />+ <span>+ {t("admin.settings.general.logoStyle.classic", "Classic")}+ </span>+ </div>+ ),+ },+ {+ value: "modern",+ label: (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ gap: "0.5rem",+ padding: "0.25rem 0",+ }}+ >+ <img+ src="modern-logo/StirlingPDFLogoNoTextLight.svg"+ alt={t(+ "admin.settings.general.logoStyle.modernAlt",+ "Modern logo",+ )}+ style={{ width: "24px", height: "24px" }}+ />+ <span>+ {t("admin.settings.general.logoStyle.modern", "Modern")}+ </span>+ </div>+ ),+ },+ ]}+ />+ </div>++ <div>+ <MultiSelect+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.languages.label",+ "Available Languages",+ )}+ </span>+ <PendingBadge show={isFieldPending("ui.languages")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.languages.description",+ "Limit which languages are available (empty = all languages)",+ )}+ />+ </Group>+ }+ value={selectedLanguages}+ onChange={(value) =>+ setSettings({+ ...settings,+ ui: { ...settings.ui, languages: value },+ })+ }+ data={languageOptions}+ searchable+ clearable+ placeholder={t(+ "admin.settings.general.languages.placeholder",+ "Select languages",+ )}+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <Select+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.defaultLocale.label",+ "Default Locale",+ )}+ </span>+ <PendingBadge show={isFieldPending("system.defaultLocale")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.defaultLocale.description",+ "The default language for new users (e.g., en_US, es_ES)",+ )}+ />+ </Group>+ }+ value={defaultLocaleValue}+ onChange={(value) =>+ setSettings({+ ...settings,+ system: { ...settings.system, defaultLocale: value || "" },+ })+ }+ data={defaultLocaleOptions}+ searchable+ clearable+ placeholder="en_US"+ comboboxProps={{+ withinPortal: true,+ zIndex: Z_INDEX_OVER_CONFIG_MODAL,+ }}+ disabled={!loginEnabled}+ />+ </div>++ <div>+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.fileUploadLimit.label",+ "File Upload Limit",+ )}+ </span>+ <PendingBadge show={isFieldPending("system.fileUploadLimit")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.fileUploadLimit.description",+ "Maximum file upload size (e.g., 100MB, 1GB)",+ )}+ />+ </Group>+ }+ value={settings.system?.fileUploadLimit || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ system: {+ ...settings.system,+ fileUploadLimit: e.target.value,+ },+ })+ }+ placeholder="100MB"+ disabled={!loginEnabled}+ />+ </div>++ <div id="frontendUrl">+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.general.frontendUrl.label",+ "Frontend URL",+ )}+ </span>+ <PendingBadge show={isFieldPending("system.frontendUrl")} />+ <InfoTooltip+ label={t(+ "admin.settings.general.frontendUrl.description",+ "Base URL for frontend (e.g., https://pdf.example.com). Used for email invite links and mobile QR code uploads. Leave empty to use backend URL.",+ )}+ />+ </Group>+ }+ value={settings.system?.frontendUrl || ""}+ onChange={(e) =>+ setSettings({+ ...settings,+ system: { ...settings.system, frontendUrl: e.target.value },+ })+ }+ placeholder="https://pdf.example.com"+ disabled={!loginEnabled}+ />+ </div>++ {/* Hide Disabled Tools Settings */}+ <SettingsToggleRow+ label={t(+ "admin.settings.general.hideDisabledTools.googleDrive.label",+ "Hide Google Drive",+ )}+ info={t(+ "admin.settings.general.hideDisabledTools.googleDrive.description",+ "Hide Google Drive button when not enabled",+ )}+ pending={isFieldPending("ui.hideDisabledTools.googleDrive")}+ checked={settings.ui?.hideDisabledTools?.googleDrive || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ ui: {+ ...settings.ui,+ hideDisabledTools: {+ ...settings.ui?.hideDisabledTools,+ googleDrive: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.general.hideDisabledTools.mobileScanner.label",+ "Hide Mobile Scanner",+ )}+ info={t(+ "admin.settings.general.hideDisabledTools.mobileScanner.description",+ "Hide mobile QR scanner button when not enabled",+ )}+ pending={isFieldPending("ui.hideDisabledTools.mobileQRScanner")}+ checked={settings.ui?.hideDisabledTools?.mobileQRScanner || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ ui: {+ ...settings.ui,+ hideDisabledTools: {+ ...settings.ui?.hideDisabledTools,+ mobileQRScanner: checked,+ },+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.general.showUpdate.label",+ "Show Update Notifications",+ )}+ info={t(+ "admin.settings.general.showUpdate.description",+ "Display notifications when a new version is available",+ )}+ pending={isFieldPending("system.showUpdate")}+ checked={settings.system?.showUpdate || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ system: {+ ...settings.system,+ showUpdate: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.general.showUpdateOnlyAdmin.label",+ "Show Updates to Admins Only",+ )}+ info={t(+ "admin.settings.general.showUpdateOnlyAdmin.description",+ "Restrict update notifications to admin users only",+ )}+ pending={isFieldPending("system.showUpdateOnlyAdmin")}+ checked={settings.system?.showUpdateOnlyAdmin || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ system: {+ ...settings.system,+ showUpdateOnlyAdmin: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.general.customHTMLFiles.label",+ "Custom HTML Files",+ )}+ info={t(+ "admin.settings.general.customHTMLFiles.description",+ "Allow serving custom HTML files from the customFiles directory",+ )}+ pending={isFieldPending("system.customHTMLFiles")}+ checked={settings.system?.customHTMLFiles || false}+ onChange={(checked) =>+ setSettings({+ ...settings,+ system: {+ ...settings.system,+ customHTMLFiles: checked,+ },+ })+ }+ disabled={!loginEnabled}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsxnew file mode 100644index 0000000000..5537ff6fd1--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsx@@ -0,0 +1,65 @@+import { useTranslation } from "react-i18next";+import { Stack, Paper } from "@mantine/core";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";+import type { UiDefaultsCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";++/**+ * Starting values for two per-user preferences. Its own `ui` draft, kept apart+ * from the System card's ui.* keys so each save still sends only what changed.+ */+export function UserDefaultsCard({+ settings,+ setSettings,+ isFieldPending,+ loginEnabled,+}: UiDefaultsCardProps) {+ const { t } = useTranslation();++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <SettingsToggleRow+ label={t(+ "admin.settings.endpoints.defaultHideUnavailableTools.label",+ "Hide unavailable tools by default",+ )}+ info={t(+ "admin.settings.endpoints.defaultHideUnavailableTools.description",+ "Remove disabled tools instead of showing them greyed out",+ )}+ pending={isFieldPending("defaultHideUnavailableTools")}+ checked={settings.defaultHideUnavailableTools || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ defaultHideUnavailableTools: checked,+ });+ }}+ disabled={!loginEnabled}+ />++ <SettingsToggleRow+ label={t(+ "admin.settings.endpoints.defaultHideUnavailableConversions.label",+ "Hide unavailable conversions by default",+ )}+ info={t(+ "admin.settings.endpoints.defaultHideUnavailableConversions.description",+ "Remove disabled conversion options instead of showing them greyed out",+ )}+ pending={isFieldPending("defaultHideUnavailableConversions")}+ checked={settings.defaultHideUnavailableConversions || false}+ onChange={(checked) => {+ if (!loginEnabled) return;+ setSettings({+ ...settings,+ defaultHideUnavailableConversions: checked,+ });+ }}+ disabled={!loginEnabled}+ />+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverCardProps.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverCardProps.tsnew file mode 100644index 0000000000..1d291ee7b9--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverCardProps.ts@@ -0,0 +1,38 @@+import type {+ EndpointsSettingsData,+ FolderAccessSettingsData,+ GeneralSettingsData,+ McpSettingsData,+ StorageSharingSettingsData,+ UiDefaultsSettingsData,+} from "@app/components/shared/config/configSections/server/serverSettings";++/**+ * What every System card needs from the page that owns them. The six server+ * rows shared one Save bar's worth of state, so the merged page keeps the+ * drafts and hands each card the one slice it edits rather than letting each+ * card fetch and save on its own.+ */+export interface ServerCardProps<T> {+ settings: T;+ setSettings: (next: T) => void;+ /** True while the backend still lists this key as awaiting a restart. */+ isFieldPending: (field: string) => boolean;+ loginEnabled: boolean;+}++export type GeneralCardProps = ServerCardProps<GeneralSettingsData>;+export type UiDefaultsCardProps = ServerCardProps<UiDefaultsSettingsData>;+export type EndpointsCardProps = ServerCardProps<EndpointsSettingsData>;+export type StorageSharingCardProps =+ ServerCardProps<StorageSharingSettingsData>;+export type McpCardProps = ServerCardProps<McpSettingsData>;++/**+ * The "add a root" box is page state: Discard clears it alongside the draft,+ * exactly as the standalone section did.+ */+export interface FolderAccessCardProps extends ServerCardProps<FolderAccessSettingsData> {+ newRoot: string;+ setNewRoot: (value: string) => void;+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.tsnew file mode 100644index 0000000000..b4e5f66d6b--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.ts@@ -0,0 +1,109 @@+/**+ * The settings shapes the merged System page edits, one per admin section it+ * still saves: general, ui, endpoints, storage, policies and mcp.+ *+ * `features` is not among them. Its query key was "features" but it GET the+ * system section and wrote only system.serverCertificate.*, so it folds into+ * the general draft as `serverCertificate` - one hook and one GET fewer.+ */++export interface GeneralSettingsData {+ ui: {+ appNameNavbar?: string;+ languages?: string[];+ logoStyle?: "modern" | "classic";+ hideDisabledTools?: {+ googleDrive?: boolean;+ mobileQRScanner?: boolean;+ };+ };+ system: {+ defaultLocale?: string;+ showUpdate?: boolean;+ showUpdateOnlyAdmin?: boolean;+ customHTMLFiles?: boolean;+ fileUploadLimit?: string;+ frontendUrl?: string;+ };+ serverCertificate?: {+ enabled?: boolean;+ organizationName?: string;+ validity?: number;+ regenerateOnStartup?: boolean;+ };+ customPaths?: {+ pipeline?: {+ pipelineDir?: string;+ watchedFoldersDir?: string;+ watchedFoldersDirs?: string[];+ finishedFoldersDir?: string;+ };+ operations?: {+ weasyprint?: string;+ unoconvert?: string;+ };+ };+ customMetadata?: {+ autoUpdateMetadata?: boolean;+ author?: string;+ creator?: string;+ producer?: string;+ };+}++/** The `ui` section's user-preference defaults, saved on their own key. */+export interface UiDefaultsSettingsData {+ defaultHideUnavailableTools?: boolean;+ defaultHideUnavailableConversions?: boolean;+}++export interface EndpointsSettingsData {+ toRemove?: string[];+ groupsToRemove?: string[];+}++export interface StorageSharingSettingsData {+ enabled?: boolean;+ sharing?: {+ enabled?: boolean;+ linkEnabled?: boolean;+ emailEnabled?: boolean;+ };+ signing?: {+ enabled?: boolean;+ };+ system?: {+ frontendUrl?: string;+ };+ mail?: {+ enabled?: boolean;+ };+}++/** Folder roots live in the `policies` section, not a folderAccess one. */+export interface FolderAccessSettingsData {+ allowedFolderRoots?: string[];+}++export interface ImpliedFolderRoot {+ path: string;+ reason: string;+}++export interface McpAuthData {+ mode?: string;+ issuerUri?: string;+ jwksUri?: string;+ resourceId?: string;+ acceptedAudiences?: string[];+ usernameClaim?: string;+ requireExistingAccount?: boolean;+}++export interface McpSettingsData {+ enabled?: boolean;+ scopesEnabled?: boolean;+ allowedOperations?: string[];+ blockedOperations?: string[];+ auth?: McpAuthData;+}diff --git a/frontend/editor/src/proprietary/data/processorSearchIndex.ts b/frontend/editor/src/proprietary/data/processorSearchIndex.tsindex f00d47a242..026770e267 100644--- a/frontend/editor/src/proprietary/data/processorSearchIndex.ts+++ b/frontend/editor/src/proprietary/data/processorSearchIndex.ts@@ -2,6 +2,7 @@ import {PORTAL_BASENAME,PORTAL_REVIEW_PATH,} from "@app/routes/portalBasename";+import { DOCS_PATH } from "@app/routes/docsRoute";// A static leaf module (its portal import is type-only), so it doesn't pull// the lazy portal chunk into the main bundle the way @portal/* values would.import { usersCapabilities } from "@app/portal/usersCapabilities";@@ -24,13 +25,6 @@ const VIEWS: ProcessorSearchEntry[] = [path: PORTAL_BASENAME,keywords: ["portal", "processor", "admin"],},- {- id: "users",- labelKey: "portal.nav.users",- labelFallback: "Users",- path: `${PORTAL_BASENAME}/users`,- keywords: ["team", "members", "roles", "admin"],- },{id: "sources",labelKey: "portal.nav.sources",@@ -73,25 +67,11 @@ const VIEWS: ProcessorSearchEntry[] = [path: `${PORTAL_BASENAME}/integrations`,keywords: ["connections", "external", "api", "webhooks"],},- {- id: "infrastructure",- labelKey: "portal.nav.infrastructure",- labelFallback: "Infrastructure",- path: `${PORTAL_BASENAME}/infrastructure`,- keywords: ["deployment", "instances", "health"],- },- {- id: "usage",- labelKey: "portal.nav.usage",- labelFallback: "Usage & Billing",- path: `${PORTAL_BASENAME}/usage`,- keywords: ["billing", "invoices", "plan", "wallet", "payg", "bundles"],- },{id: "docs",labelKey: "portal.nav.docs",labelFallback: "Documentation",- path: `${PORTAL_BASENAME}/docs`,+ path: DOCS_PATH,keywords: ["api", "documentation", "reference", "guides"],},];diff --git a/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts b/frontend/editor/src/proprietary/data/settingsSectionRegistry.tsindex e72582a0b1..fd53303bb4 100644--- a/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts+++ b/frontend/editor/src/proprietary/data/settingsSectionRegistry.ts@@ -2,6 +2,7 @@ import {SETTINGS_SECTION_REGISTRY as CORE_SETTINGS_SECTION_REGISTRY,type SettingsSectionEntry,} from "@core/data/settingsSectionRegistry";+import { HAS_PORTAL } from "@app/routes/hasPortal";export type { SettingsSectionEntry };@@ -32,8 +33,8 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [labelFallback: "API Keys",keywords: ["api", "token", "developer", "key"],requiresLogin: true,- groupLabelKey: "settings.developer.title",- groupLabelFallback: "Developer",+ groupLabelKey: "settings.preferences.title",+ groupLabelFallback: "Preferences",},// --- Workspace ---{@@ -59,129 +60,93 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [key: "adminGeneral",labelKey: "settings.configuration.systemSettings",labelFallback: "System Settings",- keywords: ["system", "config", "server"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",- },- {- key: "adminFeatures",- labelKey: "settings.configuration.features",- labelFallback: "Features",- keywords: ["features", "toggles", "flags"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",- },- {- key: "adminStorageSharing",- labelKey: "settings.configuration.storageSharing",- labelFallback: "File Storage & Sharing",- keywords: ["storage", "sharing", "files"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",- },- {- key: "adminEndpoints",- labelKey: "settings.configuration.endpoints",- labelFallback: "Endpoints",- keywords: ["endpoints", "api", "routes"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",- },- {- key: "adminMcp",- labelKey: "settings.configuration.mcp",- labelFallback: "MCP Server",- keywords: ["mcp", "server", "ai", "model context protocol"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",- },- {- key: "adminDatabase",- labelKey: "settings.configuration.database",- labelFallback: "Database",- keywords: ["database", "db", "backup"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",- },- {- key: "adminFolderAccess",- labelKey: "settings.configuration.folderAccess",- labelFallback: "Folder Access",- keywords: ["folders", "access", "permissions", "scanning"],- adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",+ keywords: [+ "system",+ "config",+ "server",+ "features",+ "toggles",+ "flags",+ "storage",+ "sharing",+ "files",+ "folders",+ "access",+ "permissions",+ "scanning",+ "endpoints",+ "api",+ "routes",+ "mcp",+ "server",+ "ai",+ "model context protocol",+ ],+ adminArea: true,+ groupLabelKey: "settings.server.title",+ groupLabelFallback: "Server",},{key: "adminAdvanced",labelKey: "settings.configuration.advanced",labelFallback: "Advanced",- keywords: ["advanced", "expert"],+ keywords: ["advanced", "expert", "database", "db", "backup"],adminArea: true,- groupLabelKey: "settings.configuration.title",- groupLabelFallback: "Configuration",+ groupLabelKey: "settings.server.title",+ groupLabelFallback: "Server",},// --- AI ---{- key: "adminAiGeneral",+ key: "adminAi",labelKey: "settings.ai.general",- labelFallback: "General",- keywords: ["ai", "assistant", "enable"],- adminArea: true,- groupLabelKey: "settings.ai.title",- groupLabelFallback: "AI",- },- {- key: "adminAiModels",- labelKey: "settings.ai.models",- labelFallback: "Models & Providers",- keywords: ["ai", "models", "providers", "llm", "openai", "anthropic"],- adminArea: true,- groupLabelKey: "settings.ai.title",- groupLabelFallback: "AI",- },- {- key: "adminAiDocuments",- labelKey: "settings.ai.documents",- labelFallback: "Documents & RAG",- keywords: ["ai", "rag", "embedding", "retrieval", "documents"],- adminArea: true,- groupLabelKey: "settings.ai.title",- groupLabelFallback: "AI",- },- {- key: "adminAiLimits",- labelKey: "settings.ai.limits",- labelFallback: "Limits & Performance",- keywords: ["ai", "limits", "tokens", "rate", "performance"],- adminArea: true,- groupLabelKey: "settings.ai.title",- groupLabelFallback: "AI",+ labelFallback: "AI Engine",+ keywords: [+ "ai",+ "assistant",+ "enable",+ "models",+ "providers",+ "llm",+ "openai",+ "anthropic",+ "rag",+ "embedding",+ "retrieval",+ "documents",+ "limits",+ "tokens",+ "rate",+ "performance",+ ],+ adminArea: true,+ groupLabelKey: "settings.server.title",+ groupLabelFallback: "Server",},// --- Security & Authentication ---{key: "adminSecurity",labelKey: "settings.securityAuth.security",labelFallback: "Security",- keywords: ["security", "authentication", "auth", "password", "sessions"],- adminArea: true,- groupLabelKey: "settings.securityAuth.title",- groupLabelFallback: "Security & Authentication",- },- {- key: "adminConnections",- labelKey: "settings.securityAuth.connections",- labelFallback: "Connections",- keywords: ["connections", "oauth", "sso", "integrations"],- adminArea: true,- groupLabelKey: "settings.securityAuth.title",- groupLabelFallback: "Security & Authentication",+ keywords: [+ "security",+ "authentication",+ "auth",+ "password",+ "sessions",+ "connections",+ "oauth",+ "sso",+ "integrations",+ "privacy",+ "gdpr",+ "data",+ "legal",+ "terms",+ "agreement",+ ],+ adminArea: true,+ groupLabelKey: "settings.server.title",+ groupLabelFallback: "Server",},// --- Licensing & Analytics ---{@@ -190,8 +155,8 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [labelFallback: "Plan",keywords: ["plan", "license", "billing", "subscription", "enterprise"],adminArea: true,- groupLabelKey: "settings.licensingAnalytics.title",- groupLabelFallback: "Licensing & Analytics",+ groupLabelKey: "settings.workspace.title",+ groupLabelFallback: "Workspace",},{key: "adminAudit",@@ -199,8 +164,8 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [labelFallback: "Audit",keywords: ["audit", "logs", "events", "history"],adminArea: true,- groupLabelKey: "settings.licensingAnalytics.title",- groupLabelFallback: "Licensing & Analytics",+ groupLabelKey: "settings.monitoring.title",+ groupLabelFallback: "Monitoring",},{key: "adminUsage",@@ -208,26 +173,50 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [labelFallback: "Usage Analytics",keywords: ["usage", "analytics", "stats", "metrics"],adminArea: true,- groupLabelKey: "settings.licensingAnalytics.title",- groupLabelFallback: "Licensing & Analytics",- },+ groupLabelKey: "settings.monitoring.title",+ groupLabelFallback: "Monitoring",+ },+ // --- Workspace (moved off the processor's own nav). Present only where the+ // nav can actually show them: a processor build, and a session that can+ // enter it. ---+ ...(HAS_PORTAL+ ? ([+ {+ key: "users",+ labelKey: "portal.nav.users",+ labelFallback: "Users",+ keywords: [+ "users",+ "members",+ "roster",+ "invite",+ "roles",+ "teams",+ "processor access",+ ],+ adminArea: true,+ requiresPortalAccess: true,+ groupLabelKey: "settings.workspace.title",+ groupLabelFallback: "Workspace",+ },+ {+ key: "billing",+ labelKey: "portal.nav.usage",+ labelFallback: "Usage & Billing",+ keywords: [+ "billing",+ "wallet",+ "credits",+ "invoice",+ "spend",+ "payg",+ ],+ adminArea: true,+ requiresPortalAccess: true,+ groupLabelKey: "settings.workspace.title",+ groupLabelFallback: "Workspace",+ },+ ] satisfies SettingsSectionEntry[])+ : []),// --- Policies & Privacy ---- {- key: "adminLegal",- labelKey: "settings.policiesPrivacy.legal",- labelFallback: "Legal",- keywords: ["legal", "terms", "agreement"],- adminArea: true,- groupLabelKey: "settings.policiesPrivacy.title",- groupLabelFallback: "Policies & Privacy",- },- {- key: "adminPrivacy",- labelKey: "settings.policiesPrivacy.privacy",- labelFallback: "Privacy",- keywords: ["privacy", "gdpr", "data"],- adminArea: true,- groupLabelKey: "settings.policiesPrivacy.title",- groupLabelFallback: "Policies & Privacy",- },];diff --git a/frontend/editor/src/proprietary/hooks/usePortalAccess.ts b/frontend/editor/src/proprietary/hooks/usePortalAccess.tsnew file mode 100644index 0000000000..1f6e4a6649--- /dev/null+++ b/frontend/editor/src/proprietary/hooks/usePortalAccess.ts@@ -0,0 +1,18 @@+import { useAuth } from "@app/auth/context";+import type { PortalAccessState } from "@core/hooks/usePortalAccess";++export type { PortalAccessState };++/**+ * Self-hosted (and desktop): the Spring session carries `portalAccess`, so the+ * shared auth context is both the answer and the settled signal. See the core+ * seam for the contract.+ */+export function usePortalAccessState(): PortalAccessState {+ const { portalAccess, loading } = useAuth();+ return { granted: portalAccess === true, settled: !loading };+}++export function usePortalAccess(): boolean {+ return usePortalAccessState().granted;+}diff --git a/frontend/editor/src/proprietary/portal/usersCapabilities.ts b/frontend/editor/src/proprietary/portal/usersCapabilities.tsindex fce47ff2b6..9c90ef2cc5 100644--- a/frontend/editor/src/proprietary/portal/usersCapabilities.ts+++ b/frontend/editor/src/proprietary/portal/usersCapabilities.ts@@ -22,5 +22,6 @@ export const usersCapabilities: UsersCapabilities = {seats: false,manageGrants: true,removeScope: "org",+ removeMember: true,listingRequiresAdmin: true,};diff --git a/frontend/editor/src/proprietary/routes/Landing.tsx b/frontend/editor/src/proprietary/routes/Landing.tsxindex 7406078d30..df65aa9597 100644--- a/frontend/editor/src/proprietary/routes/Landing.tsx+++ b/frontend/editor/src/proprietary/routes/Landing.tsx@@ -3,7 +3,7 @@ import { Navigate, useLocation, useNavigate } from "react-router-dom";import { useAuth } from "@app/auth/UseSession";import { useAppConfig } from "@app/contexts/AppConfigContext";import { useSuppressQuickNavRail } from "@app/contexts/QuickNavHostContext";-import HomePage from "@app/pages/HomePage";+import { AppRoot } from "@app/components/layout/AppRoot";import { useBackendProbe } from "@app/hooks/useBackendProbe";import { EDITOR_BASENAME } from "@app/routes/editorBasename";import AuthLayout from "@app/routes/authShared/AuthLayout";@@ -14,8 +14,8 @@ import { Button } from "@app/ui/Button";/*** Landing component - Smart router based on authentication status*- * If login is disabled: Show HomePage directly (anonymous mode)- * If user is authenticated: Show HomePage+ * If login is disabled: Show the app directly (anonymous mode)+ * If user is authenticated: Show the app* If user is not authenticated: Show Login or redirect to /login*/export default function Landing() {@@ -125,7 +125,7 @@ export default function Landing() {// If login is disabled, show app directly (anonymous mode)if (config?.enableLogin === false || backendProbe.loginDisabled) {console.debug("[Landing] Login disabled - showing app in anonymous mode");- return <HomePage />;+ return <AppRoot />;}// If backend is not up yet and user is not authenticated, show a branded status screen@@ -175,7 +175,7 @@ export default function Landing() {// If we have a session, show the main app// Note: First login password change is now handled by the onboarding flowif (session) {- return <HomePage />;+ return <AppRoot />;}// No session - redirect to login page. The URL always shows /login when not@@ -190,6 +190,6 @@ export default function Landing() {state={{ from: location }}/>) : (- <HomePage />+ <AppRoot />);}diff --git a/frontend/editor/src/proprietary/services/apiClientSetup.test.ts b/frontend/editor/src/proprietary/services/apiClientSetup.test.tsnew file mode 100644index 0000000000..7928579c73--- /dev/null+++ b/frontend/editor/src/proprietary/services/apiClientSetup.test.ts@@ -0,0 +1,125 @@+import type { AxiosInstance } from "axios";+import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";+import { allowConsole, expectConsole } from "@app/tests/failOnConsole";++vi.mock("@app/auth/spring/springAuthClient", () => ({+ setPostLoginRedirectPath: vi.fn(),+}));+vi.mock("@app/utils/browserIdentifier", () => ({+ getBrowserId: () => "browser-1",+}));++import { setupApiInterceptors } from "@app/services/apiClientSetup";++type Rejected = (error: unknown) => Promise<unknown>;++/** An axios-like client just rich enough to drive the response interceptor. */+function makeClient() {+ let onRejected: Rejected = async (e) => Promise.reject(e);+ const post = vi.fn();+ const retry = vi.fn().mockResolvedValue({ data: "retried" });++ const client = Object.assign(retry, {+ interceptors: {+ request: { use: vi.fn() },+ response: {+ use: (_ok: unknown, rejected: Rejected) => {+ onRejected = rejected;+ },+ },+ },+ post,+ }) as unknown as AxiosInstance;++ setupApiInterceptors(client);+ return { client, post, retry, fail: (e: unknown) => onRejected(e) };+}++function axiosError(status: number | undefined, url = "/api/v1/admin/thing") {+ return {+ config: { url, headers: {} as Record<string, string> },+ response: status === undefined ? undefined : { status },+ isAxiosError: true,+ message: status === undefined ? "Network Error" : `status ${status}`,+ };+}++describe("self-hosted API client 401 handling", () => {+ let href: string;++ beforeEach(() => {+ localStorage.setItem("stirling_jwt", "old-token");+ href = "";+ Object.defineProperty(window, "location", {+ configurable: true,+ value: {+ pathname: "/settings/adminGeneral",+ search: "",+ get href() {+ return href;+ },+ set href(next: string) {+ href = next;+ },+ },+ });+ });++ afterEach(() => {+ localStorage.clear();+ vi.restoreAllMocks();+ });++ test("a refresh that never completes leaves the session alone", async () => {+ const { post, fail } = makeClient();+ // No `response` on the error: the refresh call never reached the server.+ post.mockRejectedValueOnce(axiosError(undefined, "/api/v1/auth/refresh"));+ expectConsole.error(/Token refresh failed/);+ allowConsole.warn(/./);++ await expect(fail(axiosError(401))).rejects.toMatchObject({+ response: { status: 401 },+ });++ expect(localStorage.getItem("stirling_jwt")).toBe("old-token");+ expect(href).toBe("");+ });++ test("a rejected refresh clears the token and goes to login", async () => {+ const { post, fail } = makeClient();+ post.mockRejectedValueOnce(axiosError(401, "/api/v1/auth/refresh"));+ expectConsole.error(/Token refresh failed/);+ allowConsole.warn(/./);++ await expect(fail(axiosError(401))).rejects.toBeTruthy();++ expect(localStorage.getItem("stirling_jwt")).toBeNull();+ expect(href).toContain("/login");+ });++ test("the caller sees its own error, not the refresh's", async () => {+ const { post, fail } = makeClient();+ post.mockRejectedValueOnce(axiosError(500, "/api/v1/auth/refresh"));+ expectConsole.error(/Token refresh failed/);+ allowConsole.warn(/./);++ const caught = (await fail(axiosError(401, "/api/v1/admin/mine")).catch(+ (e) => e,+ )) as { config: { url: string } };++ expect(caught.config.url).toBe("/api/v1/admin/mine");+ });++ test("a successful refresh retries the original request", async () => {+ const { post, retry, fail } = makeClient();+ post.mockResolvedValueOnce({+ data: { session: { access_token: "new-token" } },+ });+ allowConsole.warn(/./);++ await expect(fail(axiosError(401))).resolves.toEqual({ data: "retried" });++ expect(localStorage.getItem("stirling_jwt")).toBe("new-token");+ expect(retry).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/editor/src/proprietary/services/apiClientSetup.ts b/frontend/editor/src/proprietary/services/apiClientSetup.tsindex 459f527080..659a2635c5 100644--- a/frontend/editor/src/proprietary/services/apiClientSetup.ts+++ b/frontend/editor/src/proprietary/services/apiClientSetup.ts@@ -66,6 +66,31 @@ function processQueue(error: Error | null, token: string | null = null): void {failedQueue = [];}+/**+ * Did the server reject the refresh, or did the call merely not get through?+ *+ * Only a rejection proves the session is dead. A network drop, timeout or 5xx+ * says nothing about the credentials, and signing the user out over one would+ * lose whatever they had unsaved.+ */+function isSessionRejected(error: unknown): boolean {+ const status = (error as AxiosError)?.response?.status;+ return status === 401 || status === 403;+}++function redirectToLogin(): void {+ const loginPath = withBasePath("/login");+ // Already there: another assignment would just reload the login page.+ if (window.location.pathname === loginPath) return;+ // Router-relative: Login replays this through navigate(), which applies+ // the basename itself. See the same note in httpErrorHandler.+ setPostLoginRedirectPath(+ stripBasePath(window.location.pathname) + window.location.search,+ );+ console.log("[API Client] Redirecting to login page...");+ window.location.href = loginPath;+}+async function refreshAuthToken(client: AxiosInstance): Promise<string> {console.log("[API Client] Refreshing expired JWT token...");@@ -89,18 +114,15 @@ async function refreshAuthToken(client: AxiosInstance): Promise<string> {return newToken;} catch (error) {console.error("[API Client] ❌ Token refresh failed:", error);- clearJwtTokenFromStorage();-- // Redirect to login- const loginPath = withBasePath("/login");- if (window.location.pathname !== loginPath) {- // Router-relative: Login replays this through navigate(), which applies- // the basename itself. See the same note in httpErrorHandler.- setPostLoginRedirectPath(- stripBasePath(window.location.pathname) + window.location.search,++ if (isSessionRejected(error)) {+ clearJwtTokenFromStorage();+ redirectToLogin();+ } else {+ // Keep the token: the session may well still be good once the network is.+ console.warn(+ "[API Client] Refresh did not complete; keeping the session and failing the request",);- console.log("[API Client] Redirecting to login page...");- window.location.href = loginPath;}throw error;@@ -193,7 +215,10 @@ export function setupApiInterceptors(client: AxiosInstance): void {return client(originalRequest);} catch (refreshError) {processQueue(refreshError as Error, null);- return Promise.reject(refreshError);+ // The caller asked for its own endpoint, so hand back its own failure;+ // a refresh error here would make every `catch` branch read the wrong+ // status.+ return Promise.reject(error);} finally {isRefreshing = false;}diff --git a/frontend/editor/src/prototypes/components/docs/DocsPage.tsx b/frontend/editor/src/prototypes/components/docs/DocsPage.tsxnew file mode 100644index 0000000000..7df5c6d217--- /dev/null+++ b/frontend/editor/src/prototypes/components/docs/DocsPage.tsx@@ -0,0 +1,5 @@+/**+ * The prototypes sandbox has no @portal alias, so it must not resolve the+ * portal-authored docs view — shadow the seam back to the stub.+ */+export { default } from "@core/components/docs/DocsPage";diff --git a/frontend/editor/src/prototypes/components/settings/useSettingsNav.tsx b/frontend/editor/src/prototypes/components/settings/useSettingsNav.tsxnew file mode 100644index 0000000000..9c4386f601--- /dev/null+++ b/frontend/editor/src/prototypes/components/settings/useSettingsNav.tsx@@ -0,0 +1,6 @@+/**+ * The prototypes sandbox has no @portal alias, so it must not resolve the+ * processor's settings sections — shadow the seam back to the core sections.+ */+export { useSettingsNav } from "@core/components/settings/useSettingsNav";+export type { SettingsNav } from "@app/components/settings/settingsNavTypes";diff --git a/frontend/editor/src/prototypes/routes/docsRoute.ts b/frontend/editor/src/prototypes/routes/docsRoute.tsnew file mode 100644index 0000000000..3fb5587298--- /dev/null+++ b/frontend/editor/src/prototypes/routes/docsRoute.ts@@ -0,0 +1,2 @@+/** The prototypes sandbox ships no docs manifest. */+export { DOCS_PATH, HAS_DOCS } from "@core/routes/docsRoute";diff --git a/frontend/editor/src/saas/components/settings/useSettingsNav.tsx b/frontend/editor/src/saas/components/settings/useSettingsNav.tsxnew file mode 100644index 0000000000..58f54aed96--- /dev/null+++ b/frontend/editor/src/saas/components/settings/useSettingsNav.tsx@@ -0,0 +1,95 @@+import { useCallback, useMemo, useState } from "react";+import { Modal, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { useAuth } from "@app/auth/UseSession";+import { usePortalAccessState } from "@app/hooks/usePortalAccess";+import { isUserAnonymous } from "@app/auth/supabase";+import Overview from "@app/components/shared/config/configSections/Overview";+import { createSaasConfigNavSections } from "@app/components/shared/config/saasConfigNavSections";+import { withBasePath } from "@app/constants/app";+import { Z_INDEX_OVER_SETTINGS_MODAL } from "@app/styles/zIndex";+import type { SettingsNav } from "@app/components/settings/settingsNavTypes";+import {+ buildPortalSettingsSections,+ PORTAL_SECTION_ALIASES,+ PORTAL_SUPERSEDED_SECTION_KEYS,+} from "@app/components/settings/portalSettingsNav";+import { mergeSettingsGroups } from "@app/components/settings/mergeSettingsGroups";++export type { SettingsNav };++/**+ * SaaS settings sections. The cloud nav is a plain factory rather than a hook,+ * and its Overview tab owns the sign-out action, so this seam also supplies the+ * confirm dialog as the page's overlay. Members with processor access also get+ * the processor's former Users / Infrastructure / Usage tabs here, the same way+ * self-hosted does; the processor's redirects for those routes rely on it.+ */+export function useSettingsNav(onLeave: () => void): SettingsNav {+ const { t } = useTranslation();+ const { signOut, user } = useAuth();+ // Not from useAuth: the editor's Supabase context never carries permission+ // flags, so only this seam knows. The processor has its own auth context.+ const { granted: portalAccess, settled: accessSettled } =+ usePortalAccessState();+ const [confirmOpen, setConfirmOpen] = useState(false);+ const openLogoutConfirm = useCallback(() => setConfirmOpen(true), []);+ const isAnonymous = user ? isUserAnonymous(user) : false;++ const sections = useMemo(() => {+ const own = createSaasConfigNavSections(Overview, openLogoutConfirm, {+ isAnonymous,+ t,+ onRequestClose: onLeave,+ });+ if (!portalAccess) return own;+ const portal = buildPortalSettingsSections(t, {+ includeAccountLink: false,+ includeAudit: true,+ });+ if (portal.length === 0) return own;+ return mergeSettingsGroups(own, portal, PORTAL_SUPERSEDED_SECTION_KEYS);+ }, [openLogoutConfirm, isAnonymous, t, onLeave, portalAccess]);++ const overlay = (+ <Modal+ opened={confirmOpen}+ onClose={() => setConfirmOpen(false)}+ title={t("settings.signOut.title", "Sign out")}+ centered+ zIndex={Z_INDEX_OVER_SETTINGS_MODAL}+ >+ <div className="confirm-modal-content">+ <Text>+ {t("settings.signOut.confirm", "Are you sure you want to sign out?")}+ </Text>+ <div className="confirm-modal-buttons">+ <Button variant="secondary" onClick={() => setConfirmOpen(false)}>+ {t("common.cancel", "Cancel")}+ </Button>+ <Button+ accent="danger"+ onClick={async () => {+ try {+ await signOut();+ } finally {+ setConfirmOpen(false);+ window.location.href = withBasePath("/login");+ }+ }}+ >+ {t("settings.signOut.submit", "Sign out")}+ </Button>+ </div>+ </div>+ </Modal>+ );++ return {+ sections,+ overlay,+ aliases: portalAccess ? PORTAL_SECTION_ALIASES : undefined,+ pending: !accessSettled,+ };+}diff --git a/frontend/editor/src/saas/components/shared/AppConfigModal.tsx b/frontend/editor/src/saas/components/shared/AppConfigModal.tsxdeleted file mode 100644index 11b8957deb..0000000000--- a/frontend/editor/src/saas/components/shared/AppConfigModal.tsx+++ /dev/null@@ -1,393 +0,0 @@-import React, { useCallback, useMemo, useState, useEffect } from "react";-import { Group, Modal, Text } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { ActionIcon } from "@app/ui/ActionIcon";-import { useIsMobile } from "@app/hooks/useIsMobile";-import { useLocation } from "react-router-dom";-import { useAuth } from "@app/auth/UseSession";-import { isUserAnonymous } from "@app/auth/supabase";-import { useTranslation } from "react-i18next";-import LocalIcon from "@app/components/shared/LocalIcon";-import { SettingsMobileBackButton } from "@app/components/shared/config/SettingsMobileBackButton";-import { SettingsMobileNavHeader } from "@app/components/shared/config/SettingsMobileNavHeader";-import { SettingsNavChevron } from "@app/components/shared/config/SettingsNavChevron";-import Overview from "@app/components/shared/config/configSections/Overview";-import { createSaasConfigNavSections } from "@app/components/shared/config/saasConfigNavSections";-import { consumePendingSettingsNav } from "@app/utils/appSettings";-import {- NavKey,- type ConfigNavSection,-} from "@app/components/shared/config/types";-import { stripBasePath, withBasePath } from "@app/constants/app";-import { COOKIE_CONSENT_SCROLL_SHARD } from "@app/hooks/useCookieConsent";-import "@app/components/shared/AppConfigModal.css";-import {- Z_INDEX_OVER_FULLSCREEN_SURFACE,- Z_INDEX_OVER_SETTINGS_MODAL,-} from "@app/styles/zIndex";--interface AppConfigModalProps {- opened: boolean;- onClose: () => void;- /** Accepted for interface parity with the core shell; this shell never- * URL-syncs, so it has no effect. */- urlSync?: boolean;- /** Section to land on when opening (used by non-URL hosts like the portal). */- initialSection?: NavKey | null;- /** Accepted for interface parity with the core shell; this shell ignores it. */- initialFocus?: string | null;- /** Host-specific sections appended after the saas registry sections. */- extraSections?: ConfigNavSection[];- /** Registry section keys to drop, for hosts a section can't run in. */- hiddenSectionKeys?: NavKey[];-}--const AppConfigModal: React.FC<AppConfigModalProps> = ({- opened,- onClose,- initialSection,- extraSections,- hiddenSectionKeys,-}) => {- const isMobile = useIsMobile();-- const { signOut, user } = useAuth();- const { t } = useTranslation();- const [confirmOpen, setConfirmOpen] = useState(false);- const [active, setActive] = useState<NavKey>("overview");- const [mobilePane, setMobilePane] = useState<"nav" | "content">("nav");- const [notice, setNotice] = useState<string | null>(null);- const location = useLocation();-- // The modal mounts lazily on first open, so a synchronous `appConfig:navigate`- // dispatched by the opener can arrive before the listener below is attached.- // Consume any section stashed by openAppSettings on mount to land on it.- useEffect(() => {- const pending = consumePendingSettingsNav();- if (pending) {- setActive(pending);- setMobilePane("content");- }- }, []);-- // Check if user can access billing features (non-anonymous users only)- const isAnonymous = user ? isUserAnonymous(user) : false;- useEffect(() => {- const handler = (ev: Event) => {- const detail = (ev as CustomEvent).detail as { key?: NavKey } | undefined;- if (detail?.key) {- setActive(detail.key);- setMobilePane("content");- }- };- window.addEventListener("appConfig:navigate", handler);- return () => window.removeEventListener("appConfig:navigate", handler);- }, []);-- // When the modal opens via a /settings/<section> deep link (navigateToSettings — e.g. the- // usage-limit modal CTAs, which need to land on the Plan section), select that section. The- // opener (QuickAccessBar) opens the modal whenever the path is /settings/*, but doesn't carry- // the section, and `active` defaults to "overview" — so without this a deep link would open on- // Overview rather than the linked section. Non-URL hosts (the portal) pass the- // section directly instead.- useEffect(() => {- if (!opened) return;- if (initialSection) {- setActive(initialSection);- setMobilePane("content");- return;- }- const match = stripBasePath(location.pathname).match(- /^\/settings\/([^/?#]+)/,- );- if (match) {- setActive(match[1] as NavKey);- setMobilePane("content");- } else {- setMobilePane("nav");- }- }, [opened, initialSection, location.pathname]);-- // Listen for notice updates (e.g., "Not enough credits..." next to Plan title)- useEffect(() => {- const handler = (ev: Event) => {- const detail = (ev as CustomEvent).detail as- | { key?: NavKey; notice?: string }- | undefined;- if (detail?.notice && (detail?.key ? detail.key === "plan" : true)) {- setNotice(detail.notice);- }- };- window.addEventListener("appConfig:notice", handler);- return () => window.removeEventListener("appConfig:notice", handler);- }, []);-- // Full-screen overlays that live inside our React tree (e.g. the PAYG- // UpgradeModal, portal'd to document.body) announce themselves here so we- // can hide — not unmount — while they're up. Unmounting would kill the- // overlay itself since it's our descendant; hiding keeps all section state- // (active tab, scroll, wallet data) intact for when the overlay closes.- const [overlayActive, setOverlayActive] = useState(false);- useEffect(() => {- const handler = (ev: Event) => {- const detail = (ev as CustomEvent).detail as- | { open?: boolean }- | undefined;- setOverlayActive(Boolean(detail?.open));- };- window.addEventListener("appConfig:overlay", handler);- return () => window.removeEventListener("appConfig:overlay", handler);- }, []);-- const colors = useMemo(- () => ({- navBg: "var(--c-bg-raised)",- sectionTitle: "var(--c-text-subtle)",- navItem: "var(--modal-nav-item)",- navItemActive: "var(--c-accent-fg)",- navItemActiveBg: "var(--c-primary-subtle)",- contentBg: "var(--c-surface)",- headerBorder: "var(--c-border-subtle)",- }),- [],- );- const isDev = process.env.NODE_ENV === "development";-- const openLogoutConfirm = useCallback(() => setConfirmOpen(true), []);-- // Left navigation structure and icons. The Plan tab now internally branches- // free vs subscribed × leader vs member via useWallet(), so the modal no- // longer plumbs paygEnabled / isLeader through to the nav builder.- const configNavSections = useMemo(() => {- const sections = createSaasConfigNavSections(Overview, openLogoutConfirm, {- isDev,- isAnonymous,- t,- });- const base = hiddenSectionKeys?.length- ? sections- .map((sec) => ({- ...sec,- items: sec.items.filter((i) => !hiddenSectionKeys.includes(i.key)),- }))- .filter((sec) => sec.items.length > 0)- : sections;- return extraSections?.length ? [...base, ...extraSections] : base;- }, [- openLogoutConfirm,- isDev,- isAnonymous,- t,- extraSections,- hiddenSectionKeys,- ]);-- const activeLabel = useMemo(() => {- for (const section of configNavSections) {- const found = section.items.find((i) => i.key === active);- if (found) return found.label;- }- return "";- }, [configNavSections, active]);-- const activeComponent = useMemo(() => {- for (const section of configNavSections) {- const found = section.items.find((i) => i.key === active);- if (found) return found.component;- }- return null;- }, [configNavSections, active]);-- return (- <>- <Modal- opened={opened}- onClose={onClose}- title={null}- size={isMobile ? "100%" : 1200}- centered- radius="lg"- withCloseButton={false}- zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}- overlayProps={{ opacity: 0.35, blur: 2 }}- padding={0}- fullScreen={isMobile}- removeScrollProps={{ shards: [COOKIE_CONSENT_SCROLL_SHARD] }}- // Hidden (not closed) while a child overlay like the PAYG UpgradeModal- // is up — see the appConfig:overlay listener above. The focus trap and- // escape/outside-close must release too: the trap would steal focus- // from the Stripe card iframe, and Escape would close US underneath- // the overlay — unmounting the checkout mid-payment.- styles={{- root: { display: overlayActive ? "none" : undefined },- }}- trapFocus={!overlayActive}- closeOnEscape={!overlayActive}- closeOnClickOutside={!overlayActive}- >- <div className="modal-container" data-tour="settings-modal">- {/* Left navigation */}- <div- className={`modal-nav ${isMobile ? "mobile" : ""}`}- style={{- background: colors.navBg,- ...(isMobile- ? { display: mobilePane === "nav" ? undefined : "none" }- : { borderRight: `1px solid ${colors.headerBorder}` }),- }}- >- <SettingsMobileNavHeader- show={isMobile}- onClose={onClose}- background={colors.navBg}- borderColor={colors.headerBorder}- />- <div className="modal-nav-scroll">- {configNavSections.map((section) => (- <div key={section.title} className="modal-nav-section">- <Text- size="xs"- fw={600}- c={colors.sectionTitle}- style={{ textTransform: "uppercase", letterSpacing: 0.4 }}- >- {section.title}- </Text>- <div className="modal-nav-section-items">- {section.items.map((item) => {- const isActive = active === item.key;- const color = isActive- ? colors.navItemActive- : colors.navItem;- const iconSize = 18;- return (- <div- key={item.key}- data-tour={`admin-${item.key}-nav`}- onClick={() => {- setActive(item.key);- setMobilePane("content");- }}- className={`modal-nav-item ${isMobile ? "mobile" : ""}`}- style={{- background: isActive- ? colors.navItemActiveBg- : "transparent",- }}- >- <LocalIcon- icon={item.icon}- width={iconSize}- height={iconSize}- style={{ color, flexShrink: 0 }}- />- <Text- size="sm"- fw={500}- truncate- style={{ color, minWidth: 0, flex: 1 }}- >- {item.label}- </Text>- <SettingsNavChevron show={isMobile} />- </div>- );- })}- </div>- </div>- ))}- </div>- </div>-- {/* Right content */}- <div- className="modal-content"- style={- isMobile && mobilePane !== "content"- ? { display: "none" }- : undefined- }- >- <div className="modal-content-scroll">- {/* Sticky header with section title and small close button */}- <div- className="modal-header"- style={{- background: colors.contentBg,- borderBottom: `1px solid ${colors.headerBorder}`,- }}- >- <Group gap="xs" wrap="nowrap" style={{ minWidth: 0 }}>- <SettingsMobileBackButton- show={isMobile}- onClick={() => setMobilePane("nav")}- />- <Text fw={700} size="lg" truncate>- {activeLabel}- {active === "plan" && notice ? (- <span- style={{- marginLeft: 8,- fontWeight: 600,- color: "var(--mantine-color-yellow-7)",- }}- >- – {notice}- </span>- ) : null}- </Text>- </Group>- <ActionIcon- variant="tertiary"- onClick={onClose}- aria-label={t("common.close", "Close")}- >- <LocalIcon icon="close-rounded" width={18} height={18} />- </ActionIcon>- </div>- <div className="modal-body">{activeComponent}</div>- </div>- </div>- </div>- </Modal>- {/* Confirm logout modal */}- <Modal- opened={confirmOpen}- onClose={() => setConfirmOpen(false)}- title={t("settings.signOut.title", "Sign out")}- centered- zIndex={Z_INDEX_OVER_SETTINGS_MODAL}- >- <div className="confirm-modal-content">- <Text>- {t(- "settings.signOut.confirm",- "Are you sure you want to sign out?",- )}- </Text>- <div className="confirm-modal-buttons">- <Button variant="secondary" onClick={() => setConfirmOpen(false)}>- {t("common.cancel", "Cancel")}- </Button>- <Button- accent="danger"- onClick={async () => {- try {- await signOut();- } finally {- setConfirmOpen(false);- onClose();- window.location.href = withBasePath("/login");- }- }}- >- {t("settings.signOut.submit", "Sign out")}- </Button>- </div>- </div>- </Modal>- </>- );-};--export default AppConfigModal;diff --git a/frontend/editor/src/saas/components/shared/config/configSections/McpSection.tsx b/frontend/editor/src/saas/components/shared/config/configSections/McpSection.tsxindex 705032da58..8a485b6c6e 100644--- a/frontend/editor/src/saas/components/shared/config/configSections/McpSection.tsx+++ b/frontend/editor/src/saas/components/shared/config/configSections/McpSection.tsx@@ -10,7 +10,6 @@ import {CopyButton,Tabs,Tooltip,- ThemeIcon,} from "@mantine/core";import { Button } from "@app/ui/Button";import LocalIcon from "@app/components/shared/LocalIcon";@@ -146,23 +145,6 @@ export default function McpSection() {return (<div className="settings-section-container"><Stack gap="md" className="settings-section-content">- <div>- <Group gap="sm" align="center">- <ThemeIcon variant="light" size="lg" radius="md">- <LocalIcon icon="smart-toy-rounded" width={22} height={22} />- </ThemeIcon>- <Text fw={600} size="lg">- {t("config.mcp.title", "MCP Server")}- </Text>- </Group>- <Text size="sm" c="dimmed" mt={6}>- {t(- "config.mcp.description",- "Model Context Protocol (MCP) lets AI assistants like Claude use your Stirling PDF tools directly. Connect a client once and your assistant can convert, edit, secure and process documents on your behalf.",- )}- </Text>- </div>-{isAnonymous ? (<Paper withBorder p="md" radius="md"><Stack gap={10}>diff --git a/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.test.tsx b/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.test.tsxindex 890cb604b4..5c5f7a2e43 100644--- a/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.test.tsx+++ b/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.test.tsx@@ -18,7 +18,10 @@ function itemKeys(sections: Sections): string[] {// Admin AI settings pages exist only in the self-hosted proprietary flavor; this locks in that// the AI group can never leak into the SaaS nav (fails loudly if wired into the SaaS cascade).describe("saasConfigNavSections", () => {+ // The four AI rows merged into one; the old keys stay listed so this still+ // fails if an older nav is ever wired back in.const AI_ITEM_KEYS = [+ "adminAi","adminAiGeneral","adminAiModels","adminAiDocuments",diff --git a/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.tsx b/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.tsxindex c8caf022c0..9d5822230b 100644--- a/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.tsx+++ b/frontend/editor/src/saas/components/shared/config/saasConfigNavSections.tsx@@ -6,6 +6,7 @@ import {} from "@core/components/shared/config/configNavSections";import HotkeysSection from "@app/components/shared/config/configSections/HotkeysSection";import GeneralSection from "@app/components/shared/config/configSections/GeneralSection";+import PreferencesSection from "@core/components/shared/config/configSections/preferences/PreferencesSection";import PasswordSecurity from "@app/components/shared/config/configSections/PasswordSecurity";import ApiKeys from "@app/components/shared/config/configSections/ApiKeys";import McpSection from "@app/components/shared/config/configSections/McpSection";@@ -19,7 +20,6 @@ import {type OverviewComponent = React.ComponentType<{ onLogoutClick: () => void }>;interface CreateSaasConfigNavSectionsOptions {- isDev?: boolean;isAnonymous?: boolean;t: TFunction<"translation", undefined>;/** Close the settings modal — the Help tours need it to start the tour. */@@ -122,6 +122,10 @@ function appendMcpSection(const mcpItem = {key: "mcp" as const,label: t("config.mcp.navLabel", "MCP Server"),+ description: t(+ "config.mcp.description",+ "Model Context Protocol (MCP) lets AI assistants like Claude use your Stirling PDF tools directly. Connect a client once and your assistant can convert, edit, secure and process documents on your behalf.",+ ),icon: "smart-toy-rounded",component: <McpSection />,};@@ -208,13 +212,12 @@ export function createSaasConfigNavSections(Overview: OverviewComponent,onLogoutClick: () => void,{- isDev = false,isAnonymous = false,t,onRequestClose = () => {},}: CreateSaasConfigNavSectionsOptions,): ConfigNavSection[] {- const baseSections = createCoreConfigNavSections(false, false, false);+ const baseSections = createCoreConfigNavSections(t);// Create Account section as the first section with Overview and Passwords & Securityconst accountSection: ConfigNavSection = {@@ -249,7 +252,7 @@ export function createSaasConfigNavSections(item.key === "general"? {...item,- component: <GeneralSection hideUpdateSection hideAdminBanner />,+ component: <PreferencesSection hideUpdateSection hideAdminBanner />,}: item,),@@ -269,9 +272,5 @@ export function createSaasConfigNavSections(sections = appendHelpSection(sections, t, onRequestClose);sections = appendLegalSection(sections, t);- if (isDev) {- console.debug("[AppConfigModal] SaaS navigation sections", sections);- }-return sections;}diff --git a/frontend/editor/src/saas/components/shared/config/types.ts b/frontend/editor/src/saas/components/shared/config/types.tsindex ebaff637d5..867451d7d3 100644--- a/frontend/editor/src/saas/components/shared/config/types.ts+++ b/frontend/editor/src/saas/components/shared/config/types.ts@@ -1,4 +1,7 @@-import type React from "react";+import type {+ ConfigNavItem as CoreConfigNavItem,+ ConfigNavSection as CoreConfigNavSection,+} from "@core/components/shared/config/types";import { VALID_NAV_KEYS as CORE_NAV_KEYS } from "@core/components/shared/config/types";// SaaS adds an "overview" account section and an "mcp" integrations tab. All@@ -9,20 +12,13 @@ export const VALID_NAV_KEYS = [...CORE_NAV_KEYS, "overview", "mcp"] as const;export type NavKey = (typeof VALID_NAV_KEYS)[number];-// Mirrors the core shape over the widened saas NavKey union — see the core-// module for why these live in types rather than configNavSections.-export interface ConfigNavItem {+// Core's item over this flavor's widened key union. Derived, not copied: a new+// field on the core shape must reach every flavor or the shared settings page+// stops compiling for one of them.+export interface ConfigNavItem extends Omit<CoreConfigNavItem, "key"> {key: NavKey;- label: string;- icon: string;- component: React.ReactNode;- disabled?: boolean;- disabledTooltip?: string;- badge?: string;- badgeColor?: string;}-export interface ConfigNavSection {- title: string;+export interface ConfigNavSection extends Omit<CoreConfigNavSection, "items"> {items: ConfigNavItem[];}diff --git a/frontend/editor/src/saas/data/settingsSectionRegistry.ts b/frontend/editor/src/saas/data/settingsSectionRegistry.tsindex 6d2e770889..70103b1e01 100644--- a/frontend/editor/src/saas/data/settingsSectionRegistry.ts+++ b/frontend/editor/src/saas/data/settingsSectionRegistry.ts@@ -64,6 +64,15 @@ export const SETTINGS_SECTION_REGISTRY: SettingsSectionEntry[] = [groupLabelKey: "settings.developer.title",groupLabelFallback: "Developer",},+ {+ key: "audit",+ labelKey: "settings.licensingAnalytics.audit",+ labelFallback: "Audit log",+ keywords: ["audit", "logs", "events", "history"],+ requiresPortalAccess: true,+ groupLabelKey: "settings.securityAuth.title",+ groupLabelFallback: "Security & sign-in",+ },{key: "mcp",labelKey: "config.mcp.navLabel",diff --git a/frontend/editor/src/saas/hooks/usePortalAccess.ts b/frontend/editor/src/saas/hooks/usePortalAccess.tsindex 6e91f0864c..1bf22c79d5 100644--- a/frontend/editor/src/saas/hooks/usePortalAccess.ts+++ b/frontend/editor/src/saas/hooks/usePortalAccess.ts@@ -7,6 +7,9 @@ import {writeCachedOtherApp,} from "@app/services/navFooterCache";import { qk } from "@app/query/keys";+import type { PortalAccessState } from "@core/hooks/usePortalAccess";++export type { PortalAccessState };async function fetchPortalAccess(): Promise<boolean> {const res = await apiClient.get<{ user?: { portalAccess?: boolean } }>(@@ -33,7 +36,7 @@ async function fetchPortalAccess(): Promise<boolean> {* and coming back resolves from cache: the switcher is there on first paint* instead of appearing a request later. Guests skip the request entirely.*/-export function usePortalAccess(): boolean {+export function usePortalAccessState(): PortalAccessState {const { user } = useAuth();const userId = user?.id ?? null;// The query cache is per-tree and per-load, so it can't help a cold start or@@ -42,7 +45,7 @@ export function usePortalAccess(): boolean {// there at first paint. Marked ancient so it still revalidates immediately.const [seed] = useState(readCachedOtherApp);- const { data, isSuccess } = useQuery({+ const { data, isSuccess, isFetched } = useQuery({queryKey: qk.portalAccess(userId),queryFn: fetchPortalAccess,// Signed out: nothing to ask, and any previous answer is void.@@ -60,5 +63,15 @@ export function usePortalAccess(): boolean {if (isSuccess && data !== undefined) writeCachedOtherApp(data);}, [isSuccess, data]);- return data === true;+ // A signed-out user has nothing to look up, so that answer is settled at+ // once. Otherwise the seeded value is a guess until the probe comes back -+ // callers that hide UI on "no access" must not act on the guess.+ return {+ granted: data === true,+ settled: userId === null || isFetched,+ };+}++export function usePortalAccess(): boolean {+ return usePortalAccessState().granted;}diff --git a/frontend/editor/src/saas/portal/usersBackend.ts b/frontend/editor/src/saas/portal/usersBackend.tsindex f71c240ed2..52ab517a75 100644--- a/frontend/editor/src/saas/portal/usersBackend.ts+++ b/frontend/editor/src/saas/portal/usersBackend.ts@@ -111,7 +111,9 @@ function toMember(dto: TeamMemberDTO, team: TeamDetailsDTO): Member {const role: RoleId = isLeader ? "team_owner" : "member";return {id: String(dto.id),- name: dto.username,+ // An invited member may have no username yet; their email is the only name+ // the roster can show.+ name: dto.username ?? dto.email,email: dto.email ?? dto.username,username: dto.username,role,diff --git a/frontend/editor/src/saas/portal/usersCapabilities.ts b/frontend/editor/src/saas/portal/usersCapabilities.tsindex 79d8adec31..e0c6f96d57 100644--- a/frontend/editor/src/saas/portal/usersCapabilities.ts+++ b/frontend/editor/src/saas/portal/usersCapabilities.ts@@ -23,5 +23,6 @@ export const usersCapabilities: UsersCapabilities = {seats: true,manageGrants: false,removeScope: "team",+ removeMember: true,listingRequiresAdmin: false,};diff --git a/frontend/editor/src/saas/routes/Landing.tsx b/frontend/editor/src/saas/routes/Landing.tsxindex 59b72b5e35..b161c0df77 100644--- a/frontend/editor/src/saas/routes/Landing.tsx+++ b/frontend/editor/src/saas/routes/Landing.tsx@@ -3,7 +3,7 @@ import { Navigate, useLocation } from "react-router-dom";import { useAuth } from "@app/auth/UseSession";import { useAutoAnonymousAuth } from "@app/hooks/useAutoAnonymousAuth";import { isHomeRoute, isToolRoute } from "@app/utils/pathUtils";-import HomePage from "@app/pages/HomePage";+import { AppRoot } from "@app/components/layout/AppRoot";import Login from "@app/routes/Login";import GuestUserBanner from "@app/components/auth/GuestUserBanner";import { TeamInvitationBanner } from "@app/components/shared/TeamInvitationBanner";@@ -72,7 +72,7 @@ export default function Landing() {<><GuestUserBanner /><TeamInvitationBanner />- <HomePage />+ <AppRoot /></>);}diff --git a/frontend/editor/src/saas/utils/appSettings.ts b/frontend/editor/src/saas/utils/appSettings.tsindex 989e671a0a..a8505cfd1d 100644--- a/frontend/editor/src/saas/utils/appSettings.ts+++ b/frontend/editor/src/saas/utils/appSettings.ts@@ -1,30 +1,19 @@-// Utility helpers to open the settings/config modal programmatically-// and optionally navigate to a specific section (e.g., 'plan').+// Programmatic entry into the settings page from outside the router (cloud+// modals, onboarding checklists, service callbacks).import type { NavKey } from "@app/components/shared/config/types";--let pendingNavKey: NavKey | null = null;--/** Read and clear the section a caller asked to open the modal on (if any). */-export function consumePendingSettingsNav(): NavKey | null {- const key = pendingNavKey;- pendingNavKey = null;- return key;-}+import { navigateToSettings } from "@app/utils/settingsNavigation";export function openAppSettings(targetKey?: NavKey, notice?: string) {try {- const detail: { key?: NavKey; notice?: string } = {};- if (targetKey) detail.key = targetKey;- if (notice) detail.notice = notice;- // Stash the target so a not-yet-mounted (lazy) modal starts on it.- if (targetKey) pendingNavKey = targetKey;- // Ask the UI to open the App Config modal- window.dispatchEvent(new CustomEvent("appConfig:open", { detail }));- // Navigate there too — handles the case where the modal is already mounted.- if (targetKey) {+ navigateToSettings(targetKey ?? "overview");+ // The Plan section shows why the caller sent the user here (e.g. "Not+ // enough credits"), and only it listens.+ if (notice) {window.dispatchEvent(- new CustomEvent("appConfig:navigate", { detail: { key: targetKey } }),+ new CustomEvent("appConfig:notice", {+ detail: { key: targetKey, notice },+ }),);}} catch (_e) {