#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
Allow first login checks to be called from any page (#8022)
James Bruntonb3427aaf1301
diff --git a/.taskfiles/backend.yml b/.taskfiles/backend.ymlindex 3e43321937..95d8b9b776 100644--- a/.taskfiles/backend.yml+++ b/.taskfiles/backend.yml@@ -299,3 +299,11 @@ tasks:platforms: [windows]- cmd: ./gradlew cleanplatforms: [linux, darwin]++ reset:+ desc: "Reset the local backend database and saved settings"+ cmds:+ - cmd: rm -f app/core/configs/stirling-pdf-DB-*.db app/core/configs/settings.yml app/core/configs/custom_settings.yml app/core/configs/backup/db/backup_*.sql app/core/configs/db/backup/backup_*.sql+ platforms: [linux, darwin]+ - cmd: powershell rm -Force -ErrorAction SilentlyContinue app/core/configs/stirling-pdf-DB-*.db, app/core/configs/settings.yml, app/core/configs/custom_settings.yml, app/core/configs/backup/db/backup_*.sql, app/core/configs/db/backup/backup_*.sql+ platforms: [windows]diff --git a/frontend/editor/src/core/components/AppLayout.tsx b/frontend/editor/src/core/components/AppLayout.tsxindex 48c4cb9149..881285c5a8 100644--- a/frontend/editor/src/core/components/AppLayout.tsx+++ b/frontend/editor/src/core/components/AppLayout.tsx@@ -1,7 +1,6 @@import { ReactNode } from "react";import { useBanner } from "@app/contexts/BannerContext";import NavigationWarningModal from "@app/components/shared/NavigationWarningModal";-import LoginAgreementModal from "@app/components/shared/LoginAgreementModal";interface AppLayoutProps {children: ReactNode;@@ -28,7 +27,6 @@ export function AppLayout({ children }: AppLayoutProps) {<div style={{ flex: 1, minHeight: 0, height: 0 }}>{children}</div></div><NavigationWarningModal />- <LoginAgreementModal /></>);}diff --git a/frontend/editor/src/core/components/AppProviders.tsx b/frontend/editor/src/core/components/AppProviders.tsxindex ed1194eb4b..6a9ae1615c 100644--- a/frontend/editor/src/core/components/AppProviders.tsx+++ b/frontend/editor/src/core/components/AppProviders.tsx@@ -29,8 +29,6 @@ import { AdminTourOrchestrationProvider } from "@app/contexts/AdminTourOrchestraimport { PageEditorProvider } from "@app/contexts/PageEditorContext";import { BannerProvider } from "@app/contexts/BannerContext";import ErrorBoundary from "@app/components/shared/ErrorBoundary";-import { usePosthogTracking } from "@app/hooks/usePosthogTracking";-import { useScarfTracking } from "@app/hooks/useScarfTracking";import { useAppInitialization } from "@app/hooks/useAppInitialization";import { useLogoAssets } from "@app/hooks/useLogoAssets";import AppConfigLoader from "@app/components/shared/AppConfigLoader";@@ -41,17 +39,6 @@ import { FolderFileContextProvider } from "@app/contexts/FolderFileContext";import { FolderProvider } from "@app/contexts/FolderContext";import { WorkbenchSessionPersistence } from "@app/components/session/WorkbenchSessionPersistence";-// Component to initialize scarf tracking (must be inside AppConfigProvider)-function ScarfTrackingInitializer() {- useScarfTracking();- return null;-}--function PosthogTrackingInitializer() {- usePosthogTracking();- return null;-}-// Component to run app-level initialization (must be inside AppProviders for context access)function AppInitializer() {useAppInitialization();@@ -133,8 +120,6 @@ export function AppProviders({retryOptions={appConfigRetryOptions}{...appConfigProviderProps}>- <PosthogTrackingInitializer />- <ScarfTrackingInitializer /><AppConfigLoader /><ServerDefaultsSync />{/* Auto-popup on startup when a newer Stirling-PDF release is available.diff --git a/frontend/editor/src/core/components/layout/AppRoot.tsx b/frontend/editor/src/core/components/layout/AppRoot.tsxindex b39fd349cd..b8f1c1294e 100644--- a/frontend/editor/src/core/components/layout/AppRoot.tsx+++ b/frontend/editor/src/core/components/layout/AppRoot.tsx@@ -4,18 +4,14 @@ 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";+import { StartupPrompts } from "@app/components/startup/StartupPrompts";// 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() {+function AppContent() {const { pathname } = useLocation();const path = stripBasePath(pathname);@@ -37,3 +33,13 @@ export function AppRoot() {return <HomePage />;}++/** The editor's authenticated or login-disabled routes, including catch-all entries. */+export function AppRoot() {+ return (+ <>+ <StartupPrompts />+ <AppContent />+ </>+ );+}diff --git a/frontend/editor/src/core/components/layout/Workbench.tsx b/frontend/editor/src/core/components/layout/Workbench.tsxindex 69ee06d3c4..ba3a06a9d7 100644--- a/frontend/editor/src/core/components/layout/Workbench.tsx+++ b/frontend/editor/src/core/components/layout/Workbench.tsx@@ -12,9 +12,7 @@ import {} from "@app/contexts/NavigationContext";import { isBaseWorkbench } from "@app/types/workbench";import { VIEWER_SUPPORTED_EXTENSIONS } from "@app/utils/fileUtils";-import { useAppConfig } from "@app/contexts/AppConfigContext";import { useSigningOverlay } from "@app/contexts/SigningOverlayContext";-import { useCookieConsent } from "@app/hooks/useCookieConsent";import { useIsPhone } from "@app/hooks/useIsMobile";import styles from "@app/components/layout/Workbench.module.css";@@ -41,15 +39,10 @@ const FileManagerView = lazy(// No props needed - component uses contexts directlyexport default function Workbench() {- const { config } = useAppConfig();// A flow that owns the canvas outright (desktop onboarding's Downloads sweep).// Null in every other case, which is every case in core.const takeover = useWorkbenchTakeover();- // The consent banner used to be initialised by the footer; the legal links- // now live in Settings → Legal, so the workbench owns the banner lifecycle.- useCookieConsent({ analyticsEnabled: config?.enableAnalytics === true });-// Use context-based hooks to eliminate all prop drillingconst { files: activeFiles, fileIds } = useAllFiles();const { workbench: currentView } = useNavigationState();diff --git a/frontend/editor/src/core/components/onboarding/Onboarding.tsx b/frontend/editor/src/core/components/onboarding/Onboarding.tsxindex 3ce2e2701f..8ffde7ccae 100644--- a/frontend/editor/src/core/components/onboarding/Onboarding.tsx+++ b/frontend/editor/src/core/components/onboarding/Onboarding.tsx@@ -3,7 +3,6 @@ import { type StepType } from "@reactour/tour";import { useTranslation } from "react-i18next";import { useNavigate, useLocation } from "react-router-dom";import { isAuthRoute } from "@app/constants/routes";-import { withBasePath } from "@app/constants/app";import { dispatchTourState } from "@app/constants/events";import { useOnboardingOrchestrator } from "@app/components/onboarding/orchestrator/useOnboardingOrchestrator";import { useBypassOnboarding } from "@app/components/onboarding/useBypassOnboarding";@@ -29,11 +28,7 @@ import { getTourSteps } from "@app/components/onboarding/tourRegistry";import { removeAllGlows } from "@app/components/onboarding/tourGlow";import { useFilesModalContext } from "@app/contexts/FilesModalContext";import { useServerExperience } from "@app/hooks/useServerExperience";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import apiClient from "@app/services/apiClient";import "@app/components/onboarding/OnboardingTour.css";-import { useAccountLogout } from "@app/extensions/accountLogout";-import { useAuth } from "@app/auth/UseSession";export default function Onboarding() {const { t } = useTranslation();@@ -57,16 +52,6 @@ export default function Onboarding() {requestedTourType,clearTourRequest,} = useTourRequest();- const { config, refetch: refetchConfig } = useAppConfig();- const [analyticsError, setAnalyticsError] = useState<string | null>(null);- const [analyticsLoading, setAnalyticsLoading] = useState(false);- const [showAnalyticsModal, setShowAnalyticsModal] = useState(false);- const [analyticsModalDismissed, setAnalyticsModalDismissed] = useState(false);- const [firstLoginModalOpen, setFirstLoginModalOpen] = useState(false);- const [mfaModalOpen, setMfaModalOpen] = useState(false);- const accountLogout = useAccountLogout();- const { signOut } = useAuth();-const handleRoleSelect = useCallback((role: "admin" | "user" | null) => {actions.updateRuntimeState({ selectedRole: role });@@ -75,67 +60,6 @@ export default function Onboarding() {[actions, serverExperience],);- const redirectToLogin = useCallback(() => {- window.location.assign(withBasePath("/login"));- }, []);-- const handlePasswordChanged = useCallback(async () => {- actions.updateRuntimeState({ requiresPasswordChange: false });- // delete session and redirect to login page- await accountLogout({ signOut, redirectToLogin });- }, [actions, accountLogout, redirectToLogin, signOut]);-- const handleMfaSetupComplete = useCallback(() => {- actions.updateRuntimeState({ requiresMfaSetup: false });- setMfaModalOpen(false);- actions.complete();- }, [actions]);-- // Check if we should show analytics modal before onboarding- useEffect(() => {- if (- !isLoading &&- !analyticsModalDismissed &&- serverExperience.effectiveIsAdmin &&- config?.enableAnalytics == null- ) {- setShowAnalyticsModal(true);- }- }, [- isLoading,- analyticsModalDismissed,- serverExperience.effectiveIsAdmin,- config?.enableAnalytics,- ]);-- const handleAnalyticsChoice = useCallback(- async (enableAnalytics: boolean) => {- if (analyticsLoading) return;- setAnalyticsLoading(true);- setAnalyticsError(null);-- const formData = new FormData();- formData.append("enabled", enableAnalytics.toString());-- try {- await apiClient.post(- "/api/v1/settings/update-enable-analytics",- formData,- );- await refetchConfig();- setShowAnalyticsModal(false);- setAnalyticsModalDismissed(true);- } catch (error) {- setAnalyticsError(- error instanceof Error ? error.message : "Unknown error",- );- } finally {- setAnalyticsLoading(false);- }- },- [analyticsLoading, refetchConfig],- );-const handleButtonAction = useCallback(async (action: ButtonAction) => {switch (action) {@@ -193,17 +117,10 @@ export default function Onboarding() {actions.complete();navigate("/settings/adminPlan");break;- case "enable-analytics":- await handleAnalyticsChoice(true);- break;- case "disable-analytics":- await handleAnalyticsChoice(false);- break;}},[actions,- handleAnalyticsChoice,handleDownloadSelected,navigate,runtimeState.selectedRole,@@ -255,27 +172,6 @@ export default function Onboarding() {return () => removeAllGlows();}, [isTourOpen]);- // Handle first-login password change modal- useEffect(() => {- if (runtimeState.requiresPasswordChange === true) {- console.log("[Onboarding] User requires password change on first login.");- setFirstLoginModalOpen(true);- } else {- setFirstLoginModalOpen(false);- }- }, [runtimeState.requiresPasswordChange]);-- // Handle MFA setup modal- useEffect(() => {- if (runtimeState.requiresMfaSetup === true) {- console.log("[Onboarding] User requires MFA setup.");- setMfaModalOpen(true);- } else {- console.log("[Onboarding] User does not require MFA setup.");- setMfaModalOpen(false);- }- }, [runtimeState.requiresMfaSetup]);-const finishTour = useCallback(() => {setIsTourOpen(false);if (runtimeState.tourType === "admin") {@@ -336,15 +232,9 @@ export default function Onboarding() {licenseNotice: runtimeState.licenseNotice,loginEnabled: serverExperience.loginEnabled,firstLoginUsername: runtimeState.firstLoginUsername,- onPasswordChanged: handlePasswordChanged,usingDefaultCredentials: runtimeState.usingDefaultCredentials,- analyticsError,- analyticsLoading,- onMfaSetupComplete: handleMfaSetupComplete,});}, [- analyticsError,- analyticsLoading,currentSlideDefinition,osInfo,osOptions,@@ -354,8 +244,6 @@ export default function Onboarding() {serverExperience.loginEnabled,setSelectedDownloadUrl,runtimeState.firstLoginUsername,- handlePasswordChanged,- handleMfaSetupComplete,]);const modalSlideCount = useMemo(() => {@@ -378,70 +266,6 @@ export default function Onboarding() {return null;}- // Interrupt slides shown outside the normal step flow. Precedence is- // preserved by evaluation order: analytics consent → first login → MFA →- // external license notice.- if (showAnalyticsModal) {- return (- <StaticOnboardingSlide- key="analytics-choice"- slideId="analytics-choice"- runtimeState={runtimeState}- params={{ analyticsError, analyticsLoading }}- onSkip={() => {}} // No skip allowed- allowDismiss={false}- onAction={async (action) => {- if (action === "enable-analytics") {- await handleAnalyticsChoice(true);- } else if (action === "disable-analytics") {- await handleAnalyticsChoice(false);- }- }}- />- );- }-- if (firstLoginModalOpen) {- return (- <StaticOnboardingSlide- key="first-login"- slideId="first-login"- runtimeState={runtimeState}- params={{- firstLoginUsername: runtimeState.firstLoginUsername,- onPasswordChanged: handlePasswordChanged,- usingDefaultCredentials: runtimeState.usingDefaultCredentials,- }}- onSkip={() => {}}- allowDismiss={false}- onAction={(action) => {- if (action === "complete-close") {- handlePasswordChanged();- }- }}- />- );- }-- if (mfaModalOpen) {- console.log("[Onboarding] Rendering MFA setup modal slide.");- return (- <StaticOnboardingSlide- key="mfa-setup"- slideId="mfa-setup"- runtimeState={runtimeState}- params={{ onMfaSetupComplete: handleMfaSetupComplete }}- onSkip={() => {}}- allowDismiss={false}- onAction={(action) => {- if (action === "complete-close") {- handleMfaSetupComplete();- }- }}- />- );- }-if (showLicenseSlide) {const effectiveLicenseNotice =externalLicenseNotice || runtimeState.licenseNotice;diff --git a/frontend/editor/src/core/components/onboarding/orchestrator/onboardingConfig.ts b/frontend/editor/src/core/components/onboarding/orchestrator/onboardingConfig.tsindex 9b8ba965c8..2124387151 100644--- a/frontend/editor/src/core/components/onboarding/orchestrator/onboardingConfig.ts+++ b/frontend/editor/src/core/components/onboarding/orchestrator/onboardingConfig.ts@@ -78,12 +78,6 @@ export const DEFAULT_RUNTIME_STATE: OnboardingRuntimeState = {};export const ONBOARDING_STEPS: OnboardingStep[] = [- {- id: "first-login",- type: "modal-slide",- slideId: "first-login",- condition: (ctx) => ctx.requiresPasswordChange,- },{id: "welcome",type: "modal-slide",@@ -124,12 +118,6 @@ export const ONBOARDING_STEPS: OnboardingStep[] = [condition: (ctx) =>ctx.effectiveIsAdmin && ctx.licenseNotice.requiresLicense,},- {- id: "mfa-setup",- type: "modal-slide",- slideId: "mfa-setup",- condition: (ctx) => ctx.requiresMfaSetup,- },];export function getStepById(id: OnboardingStepId): OnboardingStep | undefined {diff --git a/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.ts b/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.tsindex d0ec8a66b5..38432ebcd3 100644--- a/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.ts+++ b/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.ts@@ -16,7 +16,6 @@ import {markOnboardingCompleted,migrateFromLegacyPreferences,} from "@app/components/onboarding/orchestrator/onboardingStorage";-import { accountService } from "@app/services/accountService";import { useBypassOnboarding } from "@app/components/onboarding/useBypassOnboarding";const AUTH_ROUTES = ["/login", "/signup", "/auth", "/invite"];@@ -101,21 +100,6 @@ function clearRuntimeStateSession(): void {}}-function parseMfaRequired(settings: string | null | undefined): boolean {- if (!settings) return false;-- try {- const parsed = JSON.parse(settings) as { mfaRequired?: string };- return parsed.mfaRequired?.toLowerCase() === "true";- } catch (error) {- console.warn(- "[useOnboardingOrchestrator] Failed to parse account settings JSON:",- error,- );- return false;- }-}-export interface OnboardingOrchestratorState {/** Whether onboarding is currently active */isActive: boolean;@@ -219,37 +203,6 @@ export function useOnboardingOrchestrator(serverExperience.userCountResolved,]);- useEffect(() => {- const checkFirstLogin = async () => {- if (config?.enableLogin !== true || !hasAuthToken()) return;-- try {- const [accountData, loginPageData] = await Promise.all([- accountService.getAccountData(),- accountService.getLoginPageData(),- ]);-- setRuntimeState((prev) => ({- ...prev,- requiresPasswordChange: accountData.changeCredsFlag,- firstLoginUsername: accountData.username,- usingDefaultCredentials: loginPageData.showDefaultCredentials,- requiresMfaSetup: parseMfaRequired(accountData.settings),- }));- } catch (error) {- console.log(- "[OnboardingOrchestrator] Failed to fetch account data for onboarding runtime state:",- error,- );- // Account endpoint failed - user not logged in or security disabled- }- };-- if (!configLoading) {- checkFirstLogin();- }- }, [config?.enableLogin, configLoading]);-const isOnAuthRoute = AUTH_ROUTES.some((route) =>location.pathname.startsWith(route),);diff --git a/frontend/editor/src/core/components/onboarding/slides/MFASetupSlide.tsx b/frontend/editor/src/core/components/onboarding/slides/MFASetupSlide.tsxindex 41c8308f2b..13db3b5ba2 100644--- a/frontend/editor/src/core/components/onboarding/slides/MFASetupSlide.tsx+++ b/frontend/editor/src/core/components/onboarding/slides/MFASetupSlide.tsx@@ -113,6 +113,7 @@ function MFASetupContent({ onMfaSetupComplete }: MFASetupSlideProps) {setSubmitting(true);setMfaError("");await accountService.enableMfa(mfaSetupCode.trim());+ setupCompleteRef.current = true;setSetupComplete(true);onMfaSetupComplete?.();} catch (err) {diff --git a/frontend/editor/src/core/components/shared/Footer.tsx b/frontend/editor/src/core/components/shared/Footer.tsxindex 8ae0d3d4c1..1bed7fcd7e 100644--- a/frontend/editor/src/core/components/shared/Footer.tsx+++ b/frontend/editor/src/core/components/shared/Footer.tsx@@ -35,9 +35,7 @@ export default function Footer({const finalCookiePolicy = cookiePolicy ?? footerInfo?.cookiePolicy;const finalImpressum = impressum ?? footerInfo?.impressum;- const { showCookiePreferences } = useCookieConsent({- analyticsEnabled: finalAnalyticsEnabled,- });+ const { showCookiePreferences } = useCookieConsent();// Default URLsconst defaultTermsUrl = "https://www.stirling.com/terms";diff --git a/frontend/editor/src/core/components/shared/LoginAgreementModal.tsx b/frontend/editor/src/core/components/shared/LoginAgreementModal.tsxindex 9329b0d6d8..9096aadbb9 100644--- a/frontend/editor/src/core/components/shared/LoginAgreementModal.tsx+++ b/frontend/editor/src/core/components/shared/LoginAgreementModal.tsx@@ -1,5 +1,4 @@-import { useEffect, useRef, useState } from "react";-import { useLocation } from "react-router-dom";+import { useEffect, useRef, useState, type ReactNode } from "react";import {Box,Divider,@@ -68,22 +67,24 @@ const markdownComponents: Components = {* anonymous mode). Text is fetched live for the user's current language; admins manage it via* customFiles/disclaimer/<locale>.md.*/-export default function LoginAgreementModal() {+export default function LoginAgreementModal({+ children,+}: {+ children?: ReactNode;+}) {const { t, i18n } = useTranslation();const { config } = useAppConfig();const { user, signOut } = useAuth();- const { pathname } = useLocation();const [opened, setOpened] = useState(false);+ const [resolved, setResolved] = useState(false);const [content, setContent] = useState("");const nonceRef = useRef("anon");useEffect(() => {if (!config) return;- // Never gate the login/auth screens themselves. pathname is a dep (not window.location) so- // the gate re-runs when the SPA navigates from /login to / after an interactive login -- // AppLayout stays mounted across that route change, so nothing else would re-trigger it.- if (pathname.startsWith("/login")) return;+ setResolved(false);+ setOpened(false);const loginEnabled = config.enableLogin !== false;let cancelled = false;@@ -119,13 +120,15 @@ export default function LoginAgreementModal() {} catch {// On fetch error (unreachable/unauthorized) fail OPEN: don't block app usage on a// disclaimer we couldn't load.+ } finally {+ if (!cancelled) setResolved(true);}})();return () => {cancelled = true;};- }, [config, i18n.language, user?.id, pathname]);+ }, [config, i18n.language, user?.id]);const handleAccept = () => {try {@@ -139,6 +142,7 @@ export default function LoginAgreementModal() {const handleDecline = async () => {const loginEnabled = config?.enableLogin !== false;if (loginEnabled) {+ setResolved(false);setOpened(false);try {await signOut();@@ -154,7 +158,7 @@ export default function LoginAgreementModal() {}};- if (!opened) return null;+ if (!opened) return resolved ? <>{children}</> : null;return (<Modaldiff --git a/frontend/editor/src/core/components/shared/config/configSections/LegalSection.tsx b/frontend/editor/src/core/components/shared/config/configSections/LegalSection.tsxindex 40945f6fc7..3eb490edf4 100644--- a/frontend/editor/src/core/components/shared/config/configSections/LegalSection.tsx+++ b/frontend/editor/src/core/components/shared/config/configSections/LegalSection.tsx@@ -28,9 +28,7 @@ const LegalSection: React.FC = () => {const cookiePolicy = config?.cookiePolicy ?? footerInfo?.cookiePolicy;const impressum = config?.impressum ?? footerInfo?.impressum;- const { showCookiePreferences } = useCookieConsent({- analyticsEnabled: analyticsEnabled === true,- });+ const { showCookiePreferences } = useCookieConsent();const isValidLink = (link?: string) => link && link.trim().length > 0;diff --git a/frontend/editor/src/core/components/startup/StartupPrompts.test.tsx b/frontend/editor/src/core/components/startup/StartupPrompts.test.tsxnew file mode 100644index 0000000000..a57278e4fe--- /dev/null+++ b/frontend/editor/src/core/components/startup/StartupPrompts.test.tsx@@ -0,0 +1,367 @@+import { type ComponentProps } from "react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MemoryRouter, useNavigate } from "react-router-dom";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MantineProvider } from "@mantine/core";+import {+ AppConfigProvider,+ type AppConfig,+} from "@app/contexts/AppConfigContext";+import { AppLayout } from "@app/components/AppLayout";+import { AppRoot } from "@app/components/layout/AppRoot";+import { BannerProvider } from "@app/contexts/BannerContext";+import type StaticOnboardingSlide from "@app/components/onboarding/StaticOnboardingSlide";+import type { AccountData } from "@app/services/accountService";++const h = vi.hoisted(() => ({+ auth: {+ user: { id: "admin" } as { id: string } | null,+ loading: false,+ isAnonymous: false,+ signOut: vi.fn(),+ },+ get: vi.fn(),+ post: vi.fn(),+ logout: vi.fn(),+ tracking: vi.fn(),+}));+vi.mock("@app/pages/HomePage", () => ({ default: () => null }));+vi.mock("@app/pages/SettingsPage", () => ({ default: () => null }));+vi.mock("@app/components/docs/DocsPage", () => ({ default: () => null }));+vi.mock("@app/components/shared/NavigationWarningModal", () => ({+ default: () => null,+}));+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => h.auth }));+vi.mock("@app/services/apiClient", () => ({+ default: { get: h.get, post: h.post },+}));+vi.mock("@app/extensions/accountLogout", () => ({+ useAccountLogout: () => h.logout,+}));+vi.mock("@app/hooks/useCookieConsentInitialization", () => ({+ useCookieConsentInitialization: () => h.tracking(),+}));+vi.mock("@app/hooks/useScarfTracking", () => ({ useScarfTracking: () => {} }));+vi.mock("@app/hooks/usePosthogTracking", () => ({+ usePosthogTracking: () => {},+}));+vi.mock("@app/components/onboarding/StaticOnboardingSlide", () => ({+ default: ({+ slideId,+ params,+ onAction,+ allowDismiss,+ }: ComponentProps<typeof StaticOnboardingSlide>) => (+ <div role="dialog" aria-label={slideId} data-dismissible={allowDismiss}>+ {params?.firstLoginUsername}+ <span>{params?.analyticsError}</span>+ <button onClick={() => onAction("disable-analytics")}>+ Decline analytics+ </button>+ <button onClick={() => params?.onPasswordChanged?.()}>+ Change password+ </button>+ <button onClick={() => params?.onMfaSetupComplete?.()}>Finish MFA</button>+ </div>+ ),+}));++let config: AppConfig;+let account: AccountData;+let disclaimer: {+ enabled: boolean;+ showInAnonymousMode: boolean;+ content: string;+ format: string;+};+const clients: QueryClient[] = [];++function Navigation() {+ const navigate = useNavigate();+ return (+ <button onClick={() => navigate("/processor/policies")}>+ Go to Processor+ </button>+ );+}++function TestApp({ path, client }: { path: string; client: QueryClient }) {+ return (+ <QueryClientProvider client={client}>+ <MantineProvider>+ <MemoryRouter initialEntries={[path]}>+ <AppConfigProvider>+ <BannerProvider>+ <AppLayout>+ <AppRoot />+ <Navigation />+ </AppLayout>+ </BannerProvider>+ </AppConfigProvider>+ </MemoryRouter>+ </MantineProvider>+ </QueryClientProvider>+ );+}++function renderAt(+ path: string,+ client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ }),+) {+ clients.push(client);+ const view = render(<TestApp path={path} client={client} />);+ return {+ ...view,+ refresh: () => view.rerender(<TestApp path={path} client={client} />),+ client,+ };+}++describe("startup prompts", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.auth.signOut.mockReset();+ localStorage.clear();+ sessionStorage.clear();+ h.auth.user = { id: "admin" };+ h.auth.loading = false;+ h.auth.isAnonymous = false;+ config = { enableLogin: true, isAdmin: true, enableAnalytics: false };+ account = {+ username: "admin",+ role: "ROLE_ADMIN",+ settings: "{}",+ changeCredsFlag: false,+ oAuth2Login: false,+ saml2Login: false,+ };+ disclaimer = {+ enabled: false,+ showInAnonymousMode: false,+ content: "",+ format: "markdown",+ };+ h.get.mockImplementation(async (url: string) => {+ if (url === "/api/v1/config/app-config") return { data: { ...config } };+ if (url === "/api/v1/proprietary/ui-data/account")+ return { data: { ...account } };+ if (url === "/api/v1/proprietary/ui-data/login")+ return { data: { showDefaultCredentials: true } };+ if (url === "/api/v1/config/login-disclaimer")+ return { data: disclaimer };+ throw new Error(`Unexpected request: ${url}`);+ });+ h.post.mockImplementation(async () => {+ config = { ...config, enableAnalytics: false };+ });+ });++ afterEach(() => {+ cleanup();+ clients.splice(0).forEach((client) => client.clear());+ });++ it.each([+ "/editor",+ "/compress",+ "/settings/account",+ "/processor",+ "/processor/policies",+ "/share",+ "/share/",+ "/share/token/extra",+ "/invite",+ "/workflow/sign",+ "/mobile-scanner/extra",+ "/login/extra",+ "/auth",+ "/forgot-password",+ "/reset-password",+ "/oauth/consent",+ "/link",+ ])("requires the password change on direct entry to %s", async (path) => {+ account.changeCredsFlag = true;+ renderAt(path);+ const dialog = await screen.findByRole("dialog", { name: "first-login" });+ expect(dialog).toHaveTextContent("admin");+ expect(dialog).toHaveAttribute("data-dismissible", "false");+ expect(h.tracking).not.toHaveBeenCalled();+ fireEvent.click(screen.getByText("Change password"));+ expect(h.logout).toHaveBeenCalledWith(+ expect.objectContaining({ signOut: h.auth.signOut }),+ );+ });++ it("does not let tour bypass or completed onboarding suppress account setup", async () => {+ sessionStorage.setItem("onboarding::bypass-all", "true");+ localStorage.setItem("onboarding::completed", "true");+ account.changeCredsFlag = true;+ renderAt("/processor?bypassOnboarding=true");+ expect(+ await screen.findByRole("dialog", { name: "first-login" }),+ ).toBeVisible();+ });++ it("checks the account after an interactive login without a reload", async () => {+ h.auth.user = null;+ account.changeCredsFlag = true;+ const view = renderAt("/editor");+ await act(async () => {});+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ h.auth.user = { id: "admin" };+ view.refresh();+ expect(+ await screen.findByRole("dialog", { name: "first-login" }),+ ).toBeVisible();+ });++ it.each(["/processor", "/share"])(+ "sequences analytics, MFA, agreement and cookie consent on %s",+ async (path) => {+ config.enableAnalytics = null;+ account.mfaRequired = true;+ disclaimer = {+ enabled: true,+ showInAnonymousMode: false,+ content: "Company agreement",+ format: "markdown",+ };+ renderAt(path);+ expect(+ await screen.findByRole("dialog", { name: "analytics-choice" }),+ ).toBeVisible();+ expect(screen.queryByText("Company agreement")).not.toBeInTheDocument();+ fireEvent.click(screen.getByText("Decline analytics"));+ expect(+ await screen.findByRole("dialog", { name: "mfa-setup" }),+ ).toBeVisible();+ expect(h.post).toHaveBeenCalledWith(+ "/api/v1/settings/update-enable-analytics",+ expect.any(FormData),+ );+ expect((h.post.mock.calls[0][1] as FormData).get("enabled")).toBe(+ "false",+ );+ fireEvent.click(screen.getByText("Finish MFA"));+ expect(await screen.findByText("Company agreement")).toBeVisible();+ expect(h.tracking).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole("button", { name: "loginAgreementAccept" }),+ );+ await waitFor(() => expect(h.tracking).toHaveBeenCalled());+ },+ );++ it("keeps the analytics prompt open when saving fails", async () => {+ config.enableAnalytics = null;+ h.post.mockRejectedValueOnce(new Error("Could not save"));+ renderAt("/processor");+ await screen.findByRole("dialog", { name: "analytics-choice" });+ fireEvent.click(screen.getByText("Decline analytics"));+ expect(await screen.findByText("Could not save")).toBeVisible();+ expect(h.tracking).not.toHaveBeenCalled();+ });++ it("uses the latest server choice when entering another app with stale config", async () => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ });+ client.setQueryData(["editor", "appConfig"], {+ ...config,+ enableAnalytics: null,+ });+ renderAt("/processor", client);+ await waitFor(() => expect(h.tracking).toHaveBeenCalled());+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("preserves agreement acceptance when changing apps or reloading", async () => {+ disclaimer = {+ enabled: true,+ showInAnonymousMode: false,+ content: "Company agreement",+ format: "markdown",+ };+ const editor = renderAt("/editor");+ await screen.findByText("Company agreement");+ fireEvent.click(+ screen.getByRole("button", { name: "loginAgreementAccept" }),+ );+ await waitFor(() => expect(h.tracking).toHaveBeenCalled());+ editor.unmount();+ h.tracking.mockClear();+ renderAt("/processor");+ await waitFor(() => expect(h.tracking).toHaveBeenCalled());+ expect(screen.queryByText("Company agreement")).not.toBeInTheDocument();+ });++ it("allows login-disabled servers without calling account endpoints", async () => {+ config.enableLogin = false;+ h.auth.user = null;+ renderAt("/editor");+ await waitFor(() => expect(h.tracking).toHaveBeenCalled());+ expect(+ h.get.mock.calls.some(+ ([url]) => url === "/api/v1/proprietary/ui-data/account",+ ),+ ).toBe(false);+ });++ it("does not request MFA setup from an account that has already enabled it", async () => {+ account.mfaRequired = true;+ account.mfaEnabled = true;+ renderAt("/processor");+ await waitFor(() => expect(h.tracking).toHaveBeenCalled());+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("does not initialize consent while declining the login agreement", async () => {+ disclaimer = {+ enabled: true,+ showInAnonymousMode: false,+ content: "Company agreement",+ format: "markdown",+ };+ h.auth.signOut.mockReturnValue(new Promise(() => {}));+ renderAt("/processor");+ await screen.findByText("Company agreement");+ fireEvent.click(+ screen.getByRole("button", { name: "loginAgreementDecline" }),+ );+ await act(async () => {});+ expect(h.auth.signOut).toHaveBeenCalled();+ expect(h.tracking).not.toHaveBeenCalled();+ });++ it("offers a retry when the required account lookup fails", async () => {+ const get = h.get.getMockImplementation()!;+ let failed = true;+ h.get.mockImplementation(async (url: string) => {+ if (url === "/api/v1/proprietary/ui-data/account" && failed) {+ throw new Error("Account lookup unavailable");+ }+ return get(url);+ });+ account.changeCredsFlag = true;+ renderAt("/processor");+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Account lookup unavailable",+ );+ expect(h.tracking).not.toHaveBeenCalled();+ failed = false;+ fireEvent.click(screen.getByRole("button", { name: "common.retry" }));+ expect(+ await screen.findByRole("dialog", { name: "first-login" }),+ ).toBeVisible();+ });+});diff --git a/frontend/editor/src/core/components/startup/StartupPrompts.tsx b/frontend/editor/src/core/components/startup/StartupPrompts.tsxnew file mode 100644index 0000000000..8e3d06b011--- /dev/null+++ b/frontend/editor/src/core/components/startup/StartupPrompts.tsx@@ -0,0 +1,32 @@+import { useAuth } from "@app/auth/UseSession";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { StartupSetup } from "@app/components/startup/StartupSetup";+import LoginAgreementModal from "@app/components/shared/LoginAgreementModal";+import { useCookieConsentInitialization } from "@app/hooks/useCookieConsentInitialization";+import { usePosthogTracking } from "@app/hooks/usePosthogTracking";+import { useScarfTracking } from "@app/hooks/useScarfTracking";++function StartupTracking() {+ useCookieConsentInitialization();+ usePosthogTracking();+ useScarfTracking();+ return null;+}++/** Mount once in each app's main routes, below its auth, config and theme providers. */+export function StartupPrompts() {+ const { config } = useAppConfig();+ const { user, loading } = useAuth();++ if (!config || loading || (config.enableLogin !== false && !user)) {+ return null;+ }++ return (+ <StartupSetup key={user?.id ?? "anonymous"}>+ <LoginAgreementModal>+ <StartupTracking />+ </LoginAgreementModal>+ </StartupSetup>+ );+}diff --git a/frontend/editor/src/core/components/startup/StartupSetup.tsx b/frontend/editor/src/core/components/startup/StartupSetup.tsxnew file mode 100644index 0000000000..00db251d3f--- /dev/null+++ b/frontend/editor/src/core/components/startup/StartupSetup.tsx@@ -0,0 +1,180 @@+import { useState, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { Modal, Stack, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { useAuth } from "@app/auth/UseSession";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { useServerExperience } from "@app/hooks/useServerExperience";+import { useAccountLogout } from "@app/extensions/accountLogout";+import { accountService, type AccountData } from "@app/services/accountService";+import apiClient from "@app/services/apiClient";+import { withBasePath } from "@app/constants/app";+import { DEFAULT_RUNTIME_STATE } from "@app/components/onboarding/orchestrator/onboardingConfig";+import StaticOnboardingSlide from "@app/components/onboarding/StaticOnboardingSlide";+import { Button } from "@app/ui/Button";+import { Z_INDEX_ONBOARDING_CARD } from "@app/styles/zIndex";++function requiresMfaSetup(account: AccountData): boolean {+ if (account.mfaEnabled) return false;+ if (account.mfaRequired !== undefined) return account.mfaRequired;+ try {+ const settings: unknown = JSON.parse(account.settings);+ return (+ typeof settings === "object" &&+ settings !== null &&+ "mfaRequired" in settings &&+ String(settings.mfaRequired).toLowerCase() === "true"+ );+ } catch {+ return false;+ }+}++/** Rechecks setup on app entry; deferred backends can supply config without another fetch. */+export function StartupSetup({+ children,+ refreshConfigOnMount = true,+}: {+ children: ReactNode;+ refreshConfigOnMount?: boolean;+}) {+ const { t } = useTranslation();+ const { config, refetch } = useAppConfig();+ const { user, signOut, isAnonymous } = useAuth();+ const { effectiveIsAdmin } = useServerExperience();+ const accountLogout = useAccountLogout();+ const [analyticsError, setAnalyticsError] = useState<string | null>(null);+ const [analyticsLoading, setAnalyticsLoading] = useState(false);+ const [analyticsConfigured, setAnalyticsConfigured] = useState(false);+ const [mfaCompleted, setMfaCompleted] = useState(false);+ const loginEnabled = config?.enableLogin === true;++ const requirements = useQuery({+ queryKey: ["startup", "requirements", user?.id, loginEnabled],+ queryFn: async () => {+ // Editor and Processor have separate query caches. Re-read server settings+ // on entry so an analytics choice made in the other app is respected.+ if (refreshConfigOnMount) await refetch();+ if (!loginEnabled || !user || isAnonymous) return null;+ const [account, login] = await Promise.all([+ accountService.getAccountData(),+ accountService.getLoginPageData(),+ ]);+ return { account, login };+ },+ staleTime: 0,+ refetchOnMount: "always",+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ retry: false,+ });++ const handleAnalyticsChoice = async (enabled: boolean) => {+ if (analyticsLoading) return;+ setAnalyticsLoading(true);+ setAnalyticsError(null);+ const formData = new FormData();+ formData.append("enabled", String(enabled));+ try {+ await apiClient.post(+ "/api/v1/settings/update-enable-analytics",+ formData,+ );+ await refetch();+ setAnalyticsConfigured(true);+ } catch (error) {+ setAnalyticsError(error instanceof Error ? error.message : String(error));+ } finally {+ setAnalyticsLoading(false);+ }+ };++ const handlePasswordChanged = async () => {+ await accountLogout({+ signOut,+ redirectToLogin: () => window.location.assign(withBasePath("/login")),+ });+ };++ if (requirements.isPending || requirements.isFetching) return null;++ if (requirements.isError) {+ return (+ <Modal+ opened+ onClose={() => {}}+ withCloseButton={false}+ closeOnEscape={false}+ closeOnClickOutside={false}+ title={t("common.error", "Error")}+ zIndex={Z_INDEX_ONBOARDING_CARD}+ centered+ >+ <Stack>+ <Text role="alert">{requirements.error.message}</Text>+ <Button onClick={() => void requirements.refetch()}>+ {t("common.retry", "Retry")}+ </Button>+ </Stack>+ </Modal>+ );+ }++ const runtimeState = DEFAULT_RUNTIME_STATE;+ if (+ !analyticsConfigured &&+ effectiveIsAdmin &&+ config?.enableAnalytics == null+ ) {+ return (+ <StaticOnboardingSlide+ key="analytics-choice"+ slideId="analytics-choice"+ runtimeState={runtimeState}+ params={{ analyticsError, analyticsLoading }}+ onSkip={() => {}}+ allowDismiss={false}+ onAction={(action) => {+ if (action === "enable-analytics" || action === "disable-analytics") {+ void handleAnalyticsChoice(action === "enable-analytics");+ }+ }}+ />+ );+ }++ const { account, login } = requirements.data ?? {};+ if (account?.changeCredsFlag) {+ return (+ <StaticOnboardingSlide+ key="first-login"+ slideId="first-login"+ runtimeState={runtimeState}+ params={{+ firstLoginUsername: account.username,+ onPasswordChanged: handlePasswordChanged,+ usingDefaultCredentials: login?.showDefaultCredentials,+ }}+ onSkip={() => {}}+ allowDismiss={false}+ onAction={() => {}}+ />+ );+ }++ if (account && requiresMfaSetup(account) && !mfaCompleted) {+ return (+ <StaticOnboardingSlide+ key="mfa-setup"+ slideId="mfa-setup"+ runtimeState={runtimeState}+ params={{ onMfaSetupComplete: () => setMfaCompleted(true) }}+ onSkip={() => {}}+ allowDismiss={false}+ onAction={() => {}}+ />+ );+ }++ return <>{children}</>;+}diff --git a/frontend/editor/src/core/hooks/useCookieConsent.ts b/frontend/editor/src/core/hooks/useCookieConsent.tsindex 95e66b9bf1..f7aaf4b036 100644--- a/frontend/editor/src/core/hooks/useCookieConsent.ts+++ b/frontend/editor/src/core/hooks/useCookieConsent.ts@@ -1,14 +1,4 @@-import { useEffect, useState, useCallback } from "react";-import { useTranslation } from "react-i18next";-import { BASE_PATH } from "@app/constants/app";-import { getSystemTheme } from "@app/constants/theme";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import {- Z_INDEX_COOKIE_CONSENT_BANNER,- Z_INDEX_COOKIE_PREFERENCES_MODAL,-} from "@app/styles/zIndex";-import { TOUR_STATE_EVENT, type TourStatePayload } from "@app/constants/events";-import { getCookieConsentOverrides } from "@app/extensions/cookieConsentConfig";+import { useCallback } from "react";declare global {interface Window {@@ -25,376 +15,22 @@ declare global {}}-interface CookieConsentConfig {- analyticsEnabled?: boolean;-}--export const useCookieConsent = ({- analyticsEnabled = false,-}: CookieConsentConfig = {}) => {- const { t } = useTranslation();- const { config } = useAppConfig();- const [isInitialized, setIsInitialized] = useState(false);-- useEffect(() => {- if (!analyticsEnabled) return;-- // Bridge the layering constants to the static cookie-consent stylesheets- document.documentElement.style.setProperty(- "--z-index-cookie-consent",- String(Z_INDEX_COOKIE_CONSENT_BANNER),- );- document.documentElement.style.setProperty(- "--z-index-cookie-preferences",- String(Z_INDEX_COOKIE_PREFERENCES_MODAL),- );-- const mainCSS = document.createElement("link");- mainCSS.rel = "stylesheet";- mainCSS.href = `${BASE_PATH}/css/cookieconsent.css`;- if (!document.querySelector(`link[href="${mainCSS.href}"]`)) {- document.head.appendChild(mainCSS);- }-- const customCSS = document.createElement("link");- customCSS.rel = "stylesheet";- customCSS.href = `${BASE_PATH}/css/cookieconsentCustomisation.css`;- if (!document.querySelector(`link[href="${customCSS.href}"]`)) {- document.head.appendChild(customCSS);- }-- if (window.CookieConsent) {- setIsInitialized(true);- return;- }-- const script = document.createElement("script");- script.src = `${BASE_PATH}/js/thirdParty/cookieconsent.umd.js`;- script.onload = () => {- setTimeout(() => {- const detectTheme = () => {- const mantineScheme = document.documentElement.getAttribute(- "data-mantine-color-scheme",- );- const hasLightClass =- document.documentElement.classList.contains("light");- const hasDarkClass =- document.documentElement.classList.contains("dark");- const systemPrefersDark = getSystemTheme() === "dark";-- let isDarkMode: boolean;- if (mantineScheme) {- isDarkMode = mantineScheme === "dark";- } else if (hasLightClass) {- isDarkMode = false;- } else if (hasDarkClass) {- isDarkMode = true;- } else {- isDarkMode = systemPrefersDark;- }-- document.documentElement.classList.toggle("cc--darkmode", isDarkMode);- return isDarkMode;- };-- setTimeout(() => detectTheme(), 50);-- if (!window.CookieConsent) {- console.error("CookieConsent is not available on window object");- return;- }-- const themeObserver = new MutationObserver((mutations) => {- mutations.forEach((mutation) => {- if (- mutation.type === "attributes" &&- (mutation.attributeName === "data-mantine-color-scheme" ||- mutation.attributeName === "class")- ) {- detectTheme();- }- });- });-- themeObserver.observe(document.documentElement, {- attributes: true,- attributeFilter: ["data-mantine-color-scheme", "class"],- });-- try {- const overrides = getCookieConsentOverrides();- window.CookieConsent.run({- autoShow: true,- hideFromBots: false,- ...overrides,- guiOptions: {- consentModal: {- layout: "bar",- position: "bottom",- equalWeightButtons: true,- flipButtons: true,- },- preferencesModal: {- layout: "box",- position: "right",- equalWeightButtons: true,- flipButtons: true,- },- },- categories: {- necessary: {- readOnly: true,- },- analytics: {- services: {- ...(config?.enablePosthog !== false && {- posthog: {- label: t(- "cookieBanner.services.posthog",- "PostHog Analytics",- ),- },- }),- ...(config?.enableScarf !== false && {- scarf: {- label: t("cookieBanner.services.scarf", "Scarf Pixel"),- },- }),- },- },- },- language: {- default: "en",- translations: {- en: {- consentModal: {- title: t("cookieBanner.popUp.title", "How we use Cookies"),- description:- t(- "cookieBanner.popUp.description.1",- "We use cookies and other technologies to make Stirling PDF work better for you—helping us improve our tools and keep building features you'll love.",- ) +- "<br>" +- t(- "cookieBanner.popUp.description.2",- "If you'd rather not, clicking 'No Thanks' will only enable the essential cookies needed to keep things running smoothly.",- ),- acceptAllBtn: t("cookieBanner.popUp.acceptAllBtn", "Okay"),- acceptNecessaryBtn: t(- "cookieBanner.popUp.acceptNecessaryBtn",- "No Thanks",- ),- showPreferencesBtn: t(- "cookieBanner.popUp.showPreferencesBtn",- "Manage preferences",- ),- },- preferencesModal: {- title: t(- "cookieBanner.preferencesModal.title",- "Consent Preferences Center",- ),- acceptAllBtn: t(- "cookieBanner.preferencesModal.acceptAllBtn",- "Accept all",- ),- acceptNecessaryBtn: t(- "cookieBanner.preferencesModal.acceptNecessaryBtn",- "Reject all",- ),- savePreferencesBtn: t(- "cookieBanner.preferencesModal.savePreferencesBtn",- "Save preferences",- ),- closeIconLabel: t(- "cookieBanner.preferencesModal.closeIconLabel",- "Close modal",- ),- serviceCounterLabel: t(- "cookieBanner.preferencesModal.serviceCounterLabel",- "Service|Services",- ),- sections: [- {- title: t(- "cookieBanner.preferencesModal.subtitle",- "Cookie Usage",- ),- description:- t(- "cookieBanner.preferencesModal.description.1",- "Stirling PDF uses cookies and similar technologies to enhance your experience and understand how our tools are used. This helps us improve performance, develop the features you care about, and provide ongoing support to our users.",- ) +- "<br><br>" +- t(- "cookieBanner.preferencesModal.description.2",- "Stirling PDF cannot—and will never—track or access the content of the documents you use.",- ) +- "<b> " +- t(- "cookieBanner.preferencesModal.description.3",- "Your privacy and trust are at the core of what we do.",- ) +- "</b>",- },- {- title:- t(- "cookieBanner.preferencesModal.necessary.title.1",- "Strictly Necessary Cookies",- ) +- '<span class="pm__badge">' +- t(- "cookieBanner.preferencesModal.necessary.title.2",- "Always Enabled",- ) +- "</span>",- description: t(- "cookieBanner.preferencesModal.necessary.description",- "These cookies are essential for the website to function properly. They enable core features like setting your privacy preferences, logging in, and filling out forms—which is why they can't be turned off.",- ),- linkedCategory: "necessary",- },- {- title: t(- "cookieBanner.preferencesModal.analytics.title",- "Analytics",- ),- description: t(- "cookieBanner.preferencesModal.analytics.description",- "These cookies help us understand how our tools are being used, so we can focus on building the features our community values most. Rest assured—Stirling PDF cannot and will never track the content of the documents you work with.",- ),- linkedCategory: "analytics",- },- ],- },- },- },- },- });- } catch (error) {- console.error("Error initializing CookieConsent:", error);- }- setIsInitialized(true);- }, 100);- };-- script.onerror = () => {- console.error("Failed to load cookie consent library");- };-- document.head.appendChild(script);-- return () => {- if (document.head.contains(script)) {- document.head.removeChild(script);- }- if (document.head.contains(mainCSS)) {- document.head.removeChild(mainCSS);- }- if (document.head.contains(customCSS)) {- document.head.removeChild(customCSS);- }- };- }, [analyticsEnabled, config?.enablePosthog, config?.enableScarf, t]);-- useEffect(() => {- if (!isInitialized) return;-- const detectTheme = () => {- const mantineScheme = document.documentElement.getAttribute(- "data-mantine-color-scheme",- );- const hasLightClass =- document.documentElement.classList.contains("light");- const hasDarkClass = document.documentElement.classList.contains("dark");- const systemPrefersDark = getSystemTheme() === "dark";-- let isDarkMode: boolean;- if (mantineScheme) {- isDarkMode = mantineScheme === "dark";- } else if (hasLightClass) {- isDarkMode = false;- } else if (hasDarkClass) {- isDarkMode = true;- } else {- isDarkMode = systemPrefersDark;- }-- document.documentElement.classList.toggle("cc--darkmode", isDarkMode);- return isDarkMode;- };-- detectTheme();-- const themeObserver = new MutationObserver((mutations) => {- mutations.forEach((mutation) => {- if (- mutation.type === "attributes" &&- (mutation.attributeName === "data-mantine-color-scheme" ||- mutation.attributeName === "class")- ) {- detectTheme();- }- });- });-- themeObserver.observe(document.documentElement, {- attributes: true,- attributeFilter: ["data-mantine-color-scheme", "class"],- });-- return () => themeObserver.disconnect();- }, [isInitialized]);-- useEffect(() => {- if (!isInitialized || !window.CookieConsent) return;-- const handleTourState = (event: Event) => {- const { detail } = event as CustomEvent<TourStatePayload>;- if (detail?.isOpen) {- window.CookieConsent?.hide();- } else {- const consentCookie = window.CookieConsent?.getCookie?.();- const hasConsented =- consentCookie && Object.keys(consentCookie).length > 0;- if (!hasConsented) window.CookieConsent?.show();- }- };-- window.addEventListener(TOUR_STATE_EVENT, handleTourState);- return () => window.removeEventListener(TOUR_STATE_EVENT, handleTourState);- }, [isInitialized]);-+/** Reads consent and opens preferences; StartupPrompts owns library initialization. */+export function useCookieConsent() {const showCookieConsent = useCallback(() => {- if (isInitialized && window.CookieConsent) {- window.CookieConsent?.show();- }- }, [isInitialized]);+ window.CookieConsent?.show();+ }, []);const showCookiePreferences = useCallback(() => {- if (isInitialized && window.CookieConsent) {- // Open the detailed preferences dialog directly (not the consent- // banner) — it gets the `.show--preferences` class, which the CSS- // raises above the settings modal.- window.CookieConsent?.showPreferences();- }- }, [isInitialized]);+ window.CookieConsent?.showPreferences();+ }, []);const isServiceAccepted = useCallback((service: string, category: string): boolean => {- if (typeof window === "undefined" || !window.CookieConsent) {- return false;- }- return window.CookieConsent.acceptedService(service, category);+ return window.CookieConsent?.acceptedService(service, category) ?? false;},[],);- return {- showCookieConsent,- showCookiePreferences,- isServiceAccepted,- isInitialized,- };-};+ return { showCookieConsent, showCookiePreferences, isServiceAccepted };+}diff --git a/frontend/editor/src/core/hooks/useCookieConsentInitialization.test.tsx b/frontend/editor/src/core/hooks/useCookieConsentInitialization.test.tsxnew file mode 100644index 0000000000..7fab99278d--- /dev/null+++ b/frontend/editor/src/core/hooks/useCookieConsentInitialization.test.tsx@@ -0,0 +1,110 @@+import { StrictMode, type ReactNode } from "react";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useCookieConsentInitialization } from "@app/hooks/useCookieConsentInitialization";+import { useCookieConsent } from "@app/hooks/useCookieConsent";+import { TOUR_STATE_EVENT } from "@app/constants/events";++const h = vi.hoisted(() => ({+ config: { enableAnalytics: false, enablePosthog: true, enableScarf: true },+ translate: (key: string) => key,+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: h.config }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: h.translate }),+}));++const scripts = () =>+ document.querySelectorAll('script[src$="cookieconsent.umd.js"]');++describe("cookie consent lifecycle", () => {+ afterEach(cleanup);++ it("does not initialize from preference readers or when analytics is disabled", () => {+ renderHook(() => useCookieConsent());+ renderHook(() => useCookieConsentInitialization());+ expect(scripts()).toHaveLength(0);+ });++ it("shares loading across apps, preserves consent, and hides on leaving the app", async () => {+ h.config.enableAnalytics = true;+ const editor = renderHook(() => useCookieConsentInitialization(), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <StrictMode>{children}</StrictMode>+ ),+ });+ expect(scripts()).toHaveLength(1);+ editor.unmount();+ const processor = renderHook(() => useCookieConsentInitialization());+ expect(scripts()).toHaveLength(1);++ const consent = {+ run: vi.fn(),+ show: vi.fn(),+ hide: vi.fn(),+ showPreferences: vi.fn(),+ hidePreferences: vi.fn(),+ getCookie: vi.fn<() => unknown>(() => ({})),+ acceptedCategory: vi.fn(() => false),+ acceptedService: vi.fn(() => false),+ };+ window.CookieConsent = consent;+ await act(async () => {+ scripts()[0].dispatchEvent(new Event("load"));+ });+ await waitFor(() => expect(consent.show).toHaveBeenCalledTimes(1));+ expect(consent.run).toHaveBeenCalledTimes(1);+ expect(consent.run).toHaveBeenCalledWith(+ expect.objectContaining({ autoShow: false }),+ );+ expect(document.querySelectorAll("link[data-cookie-consent]")).toHaveLength(+ 2,+ );++ const reader = renderHook(() => useCookieConsent());+ act(() => reader.result.current.showCookiePreferences());+ expect(consent.showPreferences).toHaveBeenCalledTimes(1);++ act(() =>+ window.dispatchEvent(+ new CustomEvent(TOUR_STATE_EVENT, { detail: { isOpen: true } }),+ ),+ );+ expect(consent.hide).toHaveBeenCalled();+ consent.show.mockClear();+ act(() =>+ window.dispatchEvent(+ new CustomEvent(TOUR_STATE_EVENT, { detail: { isOpen: false } }),+ ),+ );+ expect(consent.show).toHaveBeenCalledTimes(1);++ consent.getCookie.mockReturnValue({ categories: ["necessary"] });+ processor.unmount();+ consent.show.mockClear();+ consent.hide.mockClear();+ const nextEntry = renderHook(() => useCookieConsentInitialization());+ await act(async () => {});+ expect(consent.run).toHaveBeenCalledTimes(1);+ expect(consent.show).not.toHaveBeenCalled();++ act(() =>+ document.documentElement.setAttribute(+ "data-mantine-color-scheme",+ "dark",+ ),+ );+ await waitFor(() =>+ expect(document.documentElement).toHaveClass("cc--darkmode"),+ );+ h.config.enableAnalytics = false;+ nextEntry.rerender();+ expect(consent.hide).toHaveBeenCalled();+ expect(consent.hidePreferences).toHaveBeenCalled();+ consent.hide.mockClear();+ nextEntry.unmount();+ expect(consent.hide).toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/hooks/useCookieConsentInitialization.ts b/frontend/editor/src/core/hooks/useCookieConsentInitialization.tsnew file mode 100644index 0000000000..ba480ba840--- /dev/null+++ b/frontend/editor/src/core/hooks/useCookieConsentInitialization.ts@@ -0,0 +1,283 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import type { TFunction } from "i18next";+import { BASE_PATH } from "@app/constants/app";+import { getSystemTheme } from "@app/constants/theme";+import { useAppConfig, type AppConfig } from "@app/contexts/AppConfigContext";+import {+ Z_INDEX_COOKIE_CONSENT_BANNER,+ Z_INDEX_COOKIE_PREFERENCES_MODAL,+} from "@app/styles/zIndex";+import { TOUR_STATE_EVENT, type TourStatePayload } from "@app/constants/events";+import { getCookieConsentOverrides } from "@app/extensions/cookieConsentConfig";++// The library owns document-level DOM. Its promise and assets must outlive either+// app's provider stack, including a navigation while the script is still loading.+let initialization: Promise<void> | null = null;++function initializeCookieConsent(+ config: Record<string, unknown>,+): Promise<void> {+ if (initialization) return initialization;+ initialization = (async () => {+ for (const name of [+ "cookieconsent.css",+ "cookieconsentCustomisation.css",+ ]) {+ const href = `${BASE_PATH}/css/${name}`;+ if (!document.querySelector(`link[data-cookie-consent="${name}"]`)) {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.href = href;+ link.dataset.cookieConsent = name;+ document.head.appendChild(link);+ }+ }+ if (!window.CookieConsent) {+ await new Promise<void>((resolve, reject) => {+ const script = document.createElement("script");+ script.src = `${BASE_PATH}/js/thirdParty/cookieconsent.umd.js`;+ script.onload = () => resolve();+ script.onerror = () => {+ script.remove();+ reject(new Error("Failed to load cookie consent library"));+ };+ document.head.appendChild(script);+ });+ }+ if (!window.CookieConsent) throw new Error("CookieConsent is unavailable");+ await window.CookieConsent.run(config);+ })().catch((error: unknown) => {+ initialization = null;+ throw error;+ });+ return initialization;+}++function createCookieConsentConfig(+ config: AppConfig | null,+ t: TFunction,+): Record<string, unknown> {+ const overrides = getCookieConsentOverrides();+ return {+ autoShow: false,+ hideFromBots: false,+ ...overrides,+ guiOptions: {+ consentModal: {+ layout: "bar",+ position: "bottom",+ equalWeightButtons: true,+ flipButtons: true,+ },+ preferencesModal: {+ layout: "box",+ position: "right",+ equalWeightButtons: true,+ flipButtons: true,+ },+ },+ categories: {+ necessary: {+ readOnly: true,+ },+ analytics: {+ services: {+ ...(config?.enablePosthog !== false && {+ posthog: {+ label: t("cookieBanner.services.posthog", "PostHog Analytics"),+ },+ }),+ ...(config?.enableScarf !== false && {+ scarf: {+ label: t("cookieBanner.services.scarf", "Scarf Pixel"),+ },+ }),+ },+ },+ },+ language: {+ default: "en",+ translations: {+ en: {+ consentModal: {+ title: t("cookieBanner.popUp.title", "How we use Cookies"),+ description:+ t(+ "cookieBanner.popUp.description.1",+ "We use cookies and other technologies to make Stirling PDF work better for you—helping us improve our tools and keep building features you'll love.",+ ) ++ "<br>" ++ t(+ "cookieBanner.popUp.description.2",+ "If you'd rather not, clicking 'No Thanks' will only enable the essential cookies needed to keep things running smoothly.",+ ),+ acceptAllBtn: t("cookieBanner.popUp.acceptAllBtn", "Okay"),+ acceptNecessaryBtn: t(+ "cookieBanner.popUp.acceptNecessaryBtn",+ "No Thanks",+ ),+ showPreferencesBtn: t(+ "cookieBanner.popUp.showPreferencesBtn",+ "Manage preferences",+ ),+ },+ preferencesModal: {+ title: t(+ "cookieBanner.preferencesModal.title",+ "Consent Preferences Center",+ ),+ acceptAllBtn: t(+ "cookieBanner.preferencesModal.acceptAllBtn",+ "Accept all",+ ),+ acceptNecessaryBtn: t(+ "cookieBanner.preferencesModal.acceptNecessaryBtn",+ "Reject all",+ ),+ savePreferencesBtn: t(+ "cookieBanner.preferencesModal.savePreferencesBtn",+ "Save preferences",+ ),+ closeIconLabel: t(+ "cookieBanner.preferencesModal.closeIconLabel",+ "Close modal",+ ),+ serviceCounterLabel: t(+ "cookieBanner.preferencesModal.serviceCounterLabel",+ "Service|Services",+ ),+ sections: [+ {+ title: t(+ "cookieBanner.preferencesModal.subtitle",+ "Cookie Usage",+ ),+ description:+ t(+ "cookieBanner.preferencesModal.description.1",+ "Stirling PDF uses cookies and similar technologies to enhance your experience and understand how our tools are used. This helps us improve performance, develop the features you care about, and provide ongoing support to our users.",+ ) ++ "<br><br>" ++ t(+ "cookieBanner.preferencesModal.description.2",+ "Stirling PDF cannot—and will never—track or access the content of the documents you use.",+ ) ++ "<b> " ++ t(+ "cookieBanner.preferencesModal.description.3",+ "Your privacy and trust are at the core of what we do.",+ ) ++ "</b>",+ },+ {+ title:+ t(+ "cookieBanner.preferencesModal.necessary.title.1",+ "Strictly Necessary Cookies",+ ) ++ '<span class="pm__badge">' ++ t(+ "cookieBanner.preferencesModal.necessary.title.2",+ "Always Enabled",+ ) ++ "</span>",+ description: t(+ "cookieBanner.preferencesModal.necessary.description",+ "These cookies are essential for the website to function properly. They enable core features like setting your privacy preferences, logging in, and filling out forms—which is why they can't be turned off.",+ ),+ linkedCategory: "necessary",+ },+ {+ title: t(+ "cookieBanner.preferencesModal.analytics.title",+ "Analytics",+ ),+ description: t(+ "cookieBanner.preferencesModal.analytics.description",+ "These cookies help us understand how our tools are being used, so we can focus on building the features our community values most. Rest assured—Stirling PDF cannot and will never track the content of the documents you work with.",+ ),+ linkedCategory: "analytics",+ },+ ],+ },+ },+ },+ },+ };+}++/** Initializes consent once per document and limits its UI to the active app entry. */+export function useCookieConsentInitialization() {+ const { config } = useAppConfig();+ const { t } = useTranslation();+ const analyticsEnabled = config?.enableAnalytics === true;+ const [initialized, setInitialized] = useState(false);+ const [tourOpen, setTourOpen] = useState(false);++ useEffect(() => {+ if (!analyticsEnabled) return;+ let active = true;+ document.documentElement.style.setProperty(+ "--z-index-cookie-consent",+ String(Z_INDEX_COOKIE_CONSENT_BANNER),+ );+ document.documentElement.style.setProperty(+ "--z-index-cookie-preferences",+ String(Z_INDEX_COOKIE_PREFERENCES_MODAL),+ );+ void initializeCookieConsent(createCookieConsentConfig(config, t))+ .then(() => {+ if (active) setInitialized(true);+ })+ .catch((error: unknown) => {+ console.error("Error initializing CookieConsent:", error);+ });+ return () => {+ active = false;+ };+ }, [analyticsEnabled, config?.enablePosthog, config?.enableScarf, t]);++ useEffect(() => {+ const onTourState = (event: Event) => {+ setTourOpen(+ Boolean((event as CustomEvent<TourStatePayload>).detail?.isOpen),+ );+ };+ window.addEventListener(TOUR_STATE_EVENT, onTourState);+ return () => window.removeEventListener(TOUR_STATE_EVENT, onTourState);+ }, []);++ useEffect(() => {+ if (!analyticsEnabled || tourOpen) {+ window.CookieConsent?.hide();+ window.CookieConsent?.hidePreferences();+ } else if (initialized) {+ const cookie = window.CookieConsent?.getCookie();+ if (!cookie || Object.keys(cookie).length === 0)+ window.CookieConsent?.show();+ }+ return () => {+ window.CookieConsent?.hide();+ window.CookieConsent?.hidePreferences();+ };+ }, [analyticsEnabled, initialized, tourOpen]);++ useEffect(() => {+ if (!initialized) return;+ const detectTheme = () => {+ const scheme = document.documentElement.getAttribute(+ "data-mantine-color-scheme",+ );+ const dark = scheme ? scheme === "dark" : getSystemTheme() === "dark";+ document.documentElement.classList.toggle("cc--darkmode", dark);+ };+ detectTheme();+ const observer = new MutationObserver(detectTheme);+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["data-mantine-color-scheme"],+ });+ return () => observer.disconnect();+ }, [initialized]);+}diff --git a/frontend/editor/src/core/hooks/useScarfTracking.ts b/frontend/editor/src/core/hooks/useScarfTracking.tsindex 7c98e80c68..f91dd2a851 100644--- a/frontend/editor/src/core/hooks/useScarfTracking.ts+++ b/frontend/editor/src/core/hooks/useScarfTracking.ts@@ -15,9 +15,7 @@ import { setScarfConfig, firePixel } from "@app/utils/scarfTracking";*/export function useScarfTracking() {const { config } = useAppConfig();- const { isServiceAccepted } = useCookieConsent({- analyticsEnabled: config?.enableAnalytics === true,- });+ const { isServiceAccepted } = useCookieConsent();// Update scarf config whenever config or consent changesuseEffect(() => {diff --git a/frontend/editor/src/core/services/accountService.ts b/frontend/editor/src/core/services/accountService.tsindex bc43cdd2d0..f2607ab8bd 100644--- a/frontend/editor/src/core/services/accountService.ts+++ b/frontend/editor/src/core/services/accountService.ts@@ -9,6 +9,7 @@ export interface AccountData {oAuth2Login: boolean;saml2Login: boolean;mfaEnabled?: boolean;+ mfaRequired?: boolean;}export interface LoginPageData {diff --git a/frontend/editor/src/core/tests/helpers/api-stubs.ts b/frontend/editor/src/core/tests/helpers/api-stubs.tsindex 944c6119da..5627ac19cc 100644--- a/frontend/editor/src/core/tests/helpers/api-stubs.ts+++ b/frontend/editor/src/core/tests/helpers/api-stubs.ts@@ -120,6 +120,8 @@ export interface MockAppApiOptions {enableLogin?: boolean;/** Override `isAdmin` in app-config. Default `false`. */isAdmin?: boolean;+ /** Null leaves the server analytics choice unconfigured. */+ enableAnalytics?: boolean | null;/** Override the logged-in user returned by `/auth/me`. */user?: {id?: number;@@ -152,6 +154,7 @@ export async function mockAppApis(const {enableLogin = false,isAdmin = false,+ enableAnalytics = false,user = {id: 1,username: "testuser",@@ -175,6 +178,7 @@ export async function mockAppApis(json: {enableLogin,isAdmin,+ enableAnalytics,languages,defaultLocale,},diff --git a/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.ts b/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.tsindex a613493b97..ccc07494ae 100644--- a/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/cookie-preferences.spec.ts@@ -5,6 +5,7 @@ import {} from "@app/tests/helpers/ui-helpers";test.describe("18. Cookie Preferences", () => {+ test.use({ stubOptions: { enableAnalytics: true } });test.describe("18.1 Cookie Banner", () => {test("should open and configure cookie preferences from Settings → Legal", async ({page,@@ -26,7 +27,6 @@ test.describe("18. Cookie Preferences", () => {const cookieButton = page.locator("#cookieBanner").first();await expect(cookieButton).toBeVisible({ timeout: 10000 });- // The consent library lazy-loads when the Legal section mountsawait page.waitForFunction(() => (window as unknown as { CookieConsent?: unknown }).CookieConsent,{ timeout: 10000 },diff --git a/frontend/editor/src/core/tests/stubbed/startup-anonymous.spec.ts b/frontend/editor/src/core/tests/stubbed/startup-anonymous.spec.tsnew file mode 100644index 0000000000..183a237899--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/startup-anonymous.spec.ts@@ -0,0 +1,59 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({+ autoGoto: false,+ stubOptions: { enableLogin: false, user: null },+});++test.describe("login-disabled startup", () => {+ for (const path of ["/editor", "/share"]) {+ for (const enableAnalytics of [false, true]) {+ test(`loads ${path} without repeated config requests (analytics=${enableAnalytics})`, async ({+ page,+ context,+ }) => {+ await context.clearCookies();+ let configRequests = 0;+ let accountRequests = 0;+ await page.route("**/api/v1/proprietary/ui-data/account", (route) => {+ accountRequests++;+ return route.fulfill({ json: {} });+ });+ await page.route("**/api/v1/config/app-config", async (route) => {+ configRequests++;+ // Keep the refresh in flight long enough for React to render its loading state.+ await new Promise((resolve) => setTimeout(resolve, 100));+ await route.fulfill({+ json: {+ enableLogin: false,+ isAdmin: false,+ enableAnalytics,+ enablePosthog: false,+ enableScarf: false,+ languages: ["en-US"],+ defaultLocale: "en-US",+ },+ });+ });++ await page.goto(path, { waitUntil: "domcontentloaded" });+ const editor = page.locator(".workspace-frame");+ await expect(editor).toBeVisible();+ const consent = page.locator("#cc-main .cm");+ if (enableAnalytics) {+ await expect(consent).toBeVisible();+ await consent+ .getByRole("button", { name: "No Thanks", exact: true })+ .click();+ }++ // A briefly visible editor can still be remounting in a refetch loop.+ await page.waitForTimeout(1000);+ await expect(editor).toBeVisible();+ await expect(consent).toBeHidden();+ expect(configRequests).toBeLessThanOrEqual(3);+ expect(accountRequests).toBe(0);+ });+ }+ }+});diff --git a/frontend/editor/src/core/tests/stubbed/startup-login.spec.ts b/frontend/editor/src/core/tests/stubbed/startup-login.spec.tsnew file mode 100644index 0000000000..395d9f7c8b--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/startup-login.spec.ts@@ -0,0 +1,87 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++const admin = {+ id: 1,+ username: "admin",+ role: "ROLE_ADMIN",+ portalAccess: true,+};++test.use({+ autoGoto: false,+ stubOptions: { enableLogin: true, isAdmin: true, user: admin },+});++test.beforeEach(async ({ page, context }) => {+ let signedIn = false;+ await context.route("**/api/v1/**", (route) => route.fulfill({ json: {} }));+ await page.route("**/api/v1/auth/me", (route) =>+ route.fulfill({ json: { user: signedIn ? admin : null } }),+ );+ await page.route("**/api/v1/proprietary/ui-data/login", (route) =>+ route.fulfill({+ json: {+ enableLogin: true,+ loginMethod: "normal",+ firstTimeSetup: true,+ showDefaultCredentials: true,+ },+ }),+ );+ await page.route("**/api/v1/proprietary/ui-data/account", (route) =>+ route.fulfill({+ json: { ...admin, settings: "{}", changeCredsFlag: true },+ }),+ );+ await page.route("**/api/v1/auth/login", (route) => {+ signedIn = true;+ return route.fulfill({+ json: {+ user: admin,+ session: {+ access_token: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.signature",+ expires_in: 3600,+ },+ },+ });+ });+});++for (const path of [+ "/",+ "/editor?view=all#latest",+ "/processor",+ "/processor/policies?view=all#latest",+]) {+ for (const reload of [false, true]) {+ test(`uses the shared first-startup login when opening ${path}${reload ? " after reloading login" : ""}`, async ({+ page,+ }) => {+ await page.goto(path, { waitUntil: "domcontentloaded" });+ await expect(page).toHaveURL(+ (url) =>+ url.pathname === "/login" &&+ (path === "/" || url.searchParams.get("from") === path),+ );+ await expect(+ page.getByText("Default Login Credentials", { exact: true }),+ ).toBeVisible();++ if (reload) await page.reload({ waitUntil: "domcontentloaded" });+ await page.locator("#email").fill("admin");+ await page.locator("#password").fill("stirling");+ await page.getByRole("button", { name: "Login", exact: true }).click();++ if (path !== "/") {+ await expect(page).toHaveURL(+ (url) => url.pathname + url.search + url.hash === path,+ );+ }+ await expect(+ page+ .getByRole("dialog", { name: "Onboarding", exact: true })+ .getByRole("textbox", { name: "New Password", exact: true }),+ ).toBeVisible();+ });+ }+}diff --git a/frontend/editor/src/core/tests/stubbed/startup-prompts.spec.ts b/frontend/editor/src/core/tests/stubbed/startup-prompts.spec.tsnew file mode 100644index 0000000000..9f6e1cdcc9--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/startup-prompts.spec.ts@@ -0,0 +1,145 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({+ autoGoto: false,+ seedJwt: true,+ stubOptions: {+ enableLogin: true,+ isAdmin: true,+ user: { id: 1, username: "admin", role: "ROLE_ADMIN", portalAccess: true },+ },+});++test.beforeEach(async ({ context }) => {+ // Page stubs take precedence; unrelated Processor queries must not reach a+ // live backend and turn a missing fixture into an expired-session redirect.+ await context.route("**/api/v1/**", (route) => route.fulfill({ json: {} }));+});++for (const path of [+ "/editor",+ "/settings/account",+ "/processor/policies",+ "/share",+ "/share/",+ "/share/token/extra",+ "/login/extra",+ "/signup/extra",+ "/auth",+ "/auth/unknown",+ "/invite",+ "/forgot-password",+ "/reset-password",+ "/oauth/consent",+ "/workflow/sign",+ "/workflow/sign/token/extra",+ "/mobile-scanner/extra",+ "/mobile-sign/extra",+ "/account-link/callback/extra",+ "/link",+]) {+ test(`requires a password change when opening ${path} first`, async ({+ page,+ }) => {+ await page.route("**/api/v1/proprietary/ui-data/account", (route) =>+ route.fulfill({+ json: {+ username: "admin",+ role: "ROLE_ADMIN",+ settings: "{}",+ changeCredsFlag: true,+ },+ }),+ );+ await page.route("**/api/v1/proprietary/ui-data/login", (route) =>+ route.fulfill({+ json: { showDefaultCredentials: true, enableLogin: true },+ }),+ );+ await page.goto(path, { waitUntil: "domcontentloaded" });+ const dialog = page.getByRole("dialog", {+ name: "Onboarding",+ exact: true,+ });+ await expect(+ dialog.getByRole("textbox", { name: "New Password", exact: true }),+ ).toBeVisible();+ await page.keyboard.press("Escape");+ await expect(dialog).toBeVisible();+ });+}++test("keeps a genuine share page free of startup prompts, then requires setup on entering Editor", async ({+ page,+ context,+}) => {+ await context.clearCookies();+ const accountRequests: string[] = [];+ await page.route("**/api/v1/proprietary/ui-data/account", (route) => {+ accountRequests.push(route.request().url());+ return route.fulfill({+ json: {+ username: "admin",+ role: "ROLE_ADMIN",+ settings: "{}",+ changeCredsFlag: true,+ },+ });+ });+ await page.route("**/api/v1/storage/share-links/token/metadata", (route) =>+ route.fulfill({+ json: { fileName: "Shared report.pdf", accessRole: "viewer" },+ }),+ );+ await page.goto("/share/token", { waitUntil: "domcontentloaded" });+ await expect(+ page.getByText("Shared report.pdf", { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("dialog", { name: "Onboarding", exact: true }),+ ).toBeHidden();+ await expect(page.locator("#cc-main .cm")).toBeHidden();+ expect(accountRequests).toEqual([]);++ await page.goto("/share", { waitUntil: "domcontentloaded" });+ await expect(+ page+ .getByRole("dialog", { name: "Onboarding", exact: true })+ .getByRole("textbox", { name: "New Password", exact: true }),+ ).toBeVisible();+});++for (const path of ["/processor/policies", "/share", "/auth"]) {+ test(`shows cookie consent on a cold ${path} entry and remembers the choice in Editor`, async ({+ page,+ context,+ }) => {+ await context.clearCookies();+ await page.route("**/api/v1/config/app-config", (route) =>+ route.fulfill({+ json: {+ enableLogin: true,+ isAdmin: true,+ enableAnalytics: true,+ enablePosthog: false,+ enableScarf: false,+ languages: ["en-US"],+ defaultLocale: "en-US",+ },+ }),+ );+ await page.goto(path, { waitUntil: "domcontentloaded" });+ const banner = page.locator("#cc-main .cm");+ await expect(banner).toBeVisible();+ await banner+ .getByRole("button", { name: "No Thanks", exact: true })+ .click();+ await expect(banner).toBeHidden();+ await page.goto("/editor", { waitUntil: "domcontentloaded" });+ await page.waitForFunction(() => Boolean(window.CookieConsent));+ await expect(banner).toBeHidden();+ expect(+ (await context.cookies()).some((cookie) => cookie.name === "cc_cookie"),+ ).toBe(true);+ });+}diff --git a/frontend/editor/src/desktop/components/startup/StartupSetup.test.tsx b/frontend/editor/src/desktop/components/startup/StartupSetup.test.tsxnew file mode 100644index 0000000000..99c275d196--- /dev/null+++ b/frontend/editor/src/desktop/components/startup/StartupSetup.test.tsx@@ -0,0 +1,45 @@+import type { ReactNode } from "react";+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { StartupSetup } from "@app/components/startup/StartupSetup";++const h = vi.hoisted(() => ({+ saas: false,+ appVersion: undefined as string | undefined,+ setup: vi.fn(),+}));+vi.mock("@app/hooks/useSaaSMode", () => ({ useSaaSMode: () => h.saas }));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: { appVersion: h.appVersion } }),+}));+vi.mock("@core/components/startup/StartupSetup", () => ({+ StartupSetup: (props: {+ children: ReactNode;+ refreshConfigOnMount: boolean;+ }) => {+ h.setup(props.refreshConfigOnMount);+ return <>{props.children}</>;+ },+}));+beforeEach(() => {+ h.saas = false;+ h.appVersion = undefined;+ h.setup.mockClear();+});+afterEach(cleanup);++it("waits for desktop config readiness without fetching the bundled backend", () => {+ const view = render(<StartupSetup>Consent</StartupSetup>);+ expect(h.setup).not.toHaveBeenCalled();+ h.appVersion = "1.0";+ view.rerender(<StartupSetup>Consent</StartupSetup>);+ expect(h.setup).toHaveBeenCalledWith(false);+});++it("leaves hosted account setup to the identity provider", () => {+ h.saas = true;+ h.appVersion = "1.0";+ render(<StartupSetup>Consent</StartupSetup>);+ expect(screen.getByText("Consent")).toBeVisible();+ expect(h.setup).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/desktop/components/startup/StartupSetup.tsx b/frontend/editor/src/desktop/components/startup/StartupSetup.tsxnew file mode 100644index 0000000000..4a4508cf4e--- /dev/null+++ b/frontend/editor/src/desktop/components/startup/StartupSetup.tsx@@ -0,0 +1,14 @@+import type { ReactNode } from "react";+import { StartupSetup as CoreStartupSetup } from "@core/components/startup/StartupSetup";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { useSaaSMode } from "@app/hooks/useSaaSMode";++/** DesktopConfigSync owns backend readiness; hosted accounts have no Spring setup. */+export function StartupSetup({ children }: { children: ReactNode }) {+ const isSaaSMode = useSaaSMode();+ const { config } = useAppConfig();+ if (isSaaSMode || !config?.appVersion) return <>{children}</>;+ return (+ <CoreStartupSetup refreshConfigOnMount={false}>{children}</CoreStartupSetup>+ );+}diff --git a/frontend/editor/src/portal-saas/PortalProviders.tsx b/frontend/editor/src/portal-saas/PortalProviders.tsxindex 8c806422f0..98a2dffed9 100644--- a/frontend/editor/src/portal-saas/PortalProviders.tsx+++ b/frontend/editor/src/portal-saas/PortalProviders.tsx@@ -2,6 +2,8 @@ import { TierProvider } from "@portal/contexts/TierContext";import { UIProvider } from "@portal/contexts/UIContext";import { PortalChrome } from "@portal/components/PortalChrome";import { LicenseProvider } from "@app/contexts/LicenseContext";+import { StartupPrompts } from "@app/components/startup/StartupPrompts";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";import { CheckoutProvider } from "@app/contexts/CheckoutContext";/**@@ -19,11 +21,14 @@ export function PortalProviders() {return (<TierProvider><UIProvider>- <LicenseProvider>- <CheckoutProvider>- <PortalChrome />- </CheckoutProvider>- </LicenseProvider>+ <AppConfigProvider>+ <LicenseProvider>+ <CheckoutProvider>+ <StartupPrompts />+ <PortalChrome />+ </CheckoutProvider>+ </LicenseProvider>+ </AppConfigProvider></UIProvider></TierProvider>);diff --git a/frontend/editor/src/portal/PortalProviders.startup.test.tsx b/frontend/editor/src/portal/PortalProviders.startup.test.tsxnew file mode 100644index 0000000000..c1b6d7a773--- /dev/null+++ b/frontend/editor/src/portal/PortalProviders.startup.test.tsx@@ -0,0 +1,108 @@+import type { ReactNode } from "react";+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router-dom";+import { MantineProvider } from "@mantine/core";+import { PortalProviders } from "@portal/PortalProviders";++const h = vi.hoisted(() => ({+ get: vi.fn(),+ auth: {+ user: { id: "admin" },+ loading: false,+ isAnonymous: false,+ signOut: vi.fn(),+ },+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { language: "en-US" },+ }),+}));+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => h.auth }));+vi.mock("@app/services/apiClient", () => ({ default: { get: h.get } }));+vi.mock("@app/extensions/accountLogout", () => ({+ useAccountLogout: () => vi.fn(),+}));+vi.mock("@app/contexts/LicenseContext", () => ({+ LicenseProvider: ({ children }: { children: ReactNode }) => children,+ useLicense: () => ({ licenseInfo: null, loading: false }),+}));+vi.mock("@app/contexts/CheckoutContext", () => ({+ CheckoutProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@portal/contexts/TierContext", () => ({+ TierProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@portal/contexts/LinkContext", () => ({+ LinkProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@portal/contexts/AccountLinkContext", () => ({+ AccountLinkProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@portal/contexts/UIContext", () => ({+ UIProvider: ({ children }: { children: ReactNode }) => children,+ useUI: () => ({ linkModalOpen: false }),+}));+vi.mock("@portal/components/account-link/LinkAccountModal", () => ({+ LinkAccountModal: () => null,+}));+vi.mock("@portal/components/account-link/ConnectCallbackHost", () => ({+ ConnectCallbackHost: () => null,+}));+vi.mock("@portal/hooks/useFreeTierExhaustedPrompt", () => ({+ useFreeTierExhaustedPrompt: () => {},+}));+vi.mock("@portal/components/PortalChrome", () => ({+ PortalChrome: () => <div>Processor</div>,+}));+vi.mock("@app/components/onboarding/StaticOnboardingSlide", () => ({+ default: ({ slideId }: { slideId: string }) => (+ <div role="dialog" aria-label={slideId} />+ ),+}));+vi.mock("@app/hooks/useCookieConsentInitialization", () => ({+ useCookieConsentInitialization: () => {},+}));+vi.mock("@app/hooks/usePosthogTracking", () => ({+ usePosthogTracking: () => {},+}));+vi.mock("@app/hooks/useScarfTracking", () => ({ useScarfTracking: () => {} }));++afterEach(cleanup);++it("mounts mandatory setup on a cold Processor entry without editor providers", async () => {+ h.get.mockImplementation(async (url: string) => {+ if (url === "/api/v1/config/app-config")+ return {+ data: { enableLogin: true, isAdmin: true, enableAnalytics: false },+ };+ if (url === "/api/v1/proprietary/ui-data/account")+ return {+ data: { username: "admin", changeCredsFlag: true, settings: "{}" },+ };+ if (url === "/api/v1/proprietary/ui-data/login")+ return { data: { showDefaultCredentials: true } };+ throw new Error(`Unexpected request: ${url}`);+ });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ });+ const view = render(+ <MemoryRouter initialEntries={["/processor/policies"]}>+ <QueryClientProvider client={client}>+ <MantineProvider>+ <PortalProviders />+ </MantineProvider>+ </QueryClientProvider>+ </MemoryRouter>,+ );+ expect(+ await screen.findByRole("dialog", { name: "first-login" }),+ ).toBeVisible();+ expect(screen.getByText("Processor")).toBeVisible();+ view.unmount();+ client.clear();+});diff --git a/frontend/editor/src/portal/PortalProviders.tsx b/frontend/editor/src/portal/PortalProviders.tsxindex 325e1cec22..5ad70afbea 100644--- a/frontend/editor/src/portal/PortalProviders.tsx+++ b/frontend/editor/src/portal/PortalProviders.tsx@@ -8,6 +8,8 @@ import { PortalChrome } from "@portal/components/PortalChrome";import { useFreeTierExhaustedPrompt } from "@portal/hooks/useFreeTierExhaustedPrompt";import { LicenseProvider } from "@app/contexts/LicenseContext";import { AppConfigProvider } from "@app/contexts/AppConfigContext";+import { StartupPrompts } from "@app/components/startup/StartupPrompts";+import { ServerExperienceProvider } from "@app/contexts/ServerExperienceContext";import { CheckoutProvider } from "@app/contexts/CheckoutContext";/** The one and only account-link modal, whichever step it is on. */@@ -46,7 +48,10 @@ export function PortalProviders() {<AppConfigProvider><LicenseProvider><CheckoutProvider>- <PortalChrome />+ <ServerExperienceProvider>+ <StartupPrompts />+ <PortalChrome />+ </ServerExperienceProvider><LinkModalHost /><ConnectCallbackHost /></CheckoutProvider>diff --git a/frontend/editor/src/portal/auth/PortalAuthBoundary.tsx b/frontend/editor/src/portal/auth/PortalAuthBoundary.tsxindex df24718eda..afb9ea2964 100644--- a/frontend/editor/src/portal/auth/PortalAuthBoundary.tsx+++ b/frontend/editor/src/portal/auth/PortalAuthBoundary.tsx@@ -3,12 +3,8 @@ import { AuthProvider } from "@app/auth";import { AuthGate } from "@portal/components/AuthGate";/**- * Portal auth wiring — the seam the SaaS build overrides.- *- * <p>Self-hosted (this base): the portal is its own standalone app, so it owns a- * Spring {@link AuthProvider} and a Spring login gate ({@link AuthGate}). The SaaS- * build shadows this file to authenticate against the SaaS Supabase project (the- * same session the editor uses) with no Spring login and no account-link step.+ * The self-hosted Processor owns its Spring session provider and uses the shared+ * /login route. SaaS overrides this boundary to use the editor's Supabase session.*/export function PortalAuthBoundary({ children }: { children: ReactNode }) {return (diff --git a/frontend/editor/src/portal/components/AuthGate.tsx b/frontend/editor/src/portal/components/AuthGate.tsxindex 0af62ee53b..205987079d 100644--- a/frontend/editor/src/portal/components/AuthGate.tsx+++ b/frontend/editor/src/portal/components/AuthGate.tsx@@ -1,8 +1,8 @@import { type ReactNode } from "react";+import { Navigate, useLocation } from "react-router-dom";import { useTranslation } from "react-i18next";import { RequirePortalAccess } from "@app/auth";import { Spinner } from "@app/ui";-import { LoginScreen } from "@portal/components/LoginScreen";import { EDITOR_URL } from "@portal/auth/editorUrl";// Stable module-level ref; RequirePortalAccess calls it from an effect.@@ -30,9 +30,13 @@ function FullScreenMessage({ children }: { children: ReactNode }) {/** Gates the portal: login when signed out, redirect to the editor without portal access. */export function AuthGate({ children }: { children: ReactNode }) {const { t } = useTranslation();+ const location = useLocation();+ const returnTo = encodeURIComponent(+ location.pathname + location.search + location.hash,+ );return (<RequirePortalAccess- fallback={<LoginScreen />}+ fallback={<Navigate to={`/login?from=${returnTo}`} replace />}onForbidden={redirectToEditor}loading={<FullScreenMessage>diff --git a/frontend/editor/src/portal/components/LoginScreen.stories.tsx b/frontend/editor/src/portal/components/LoginScreen.stories.tsxdeleted file mode 100644index 63db811b71..0000000000--- a/frontend/editor/src/portal/components/LoginScreen.stories.tsx+++ /dev/null@@ -1,12 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { LoginScreen } from "@portal/components/LoginScreen";--const meta: Meta<typeof LoginScreen> = {- title: "Portal/LoginScreen",- component: LoginScreen,- parameters: { layout: "fullscreen" },-};-export default meta;-type Story = StoryObj<typeof LoginScreen>;--export const Default: Story = {};diff --git a/frontend/editor/src/portal/components/LoginScreen.tsx b/frontend/editor/src/portal/components/LoginScreen.tsxdeleted file mode 100644index ac69040c19..0000000000--- a/frontend/editor/src/portal/components/LoginScreen.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { AuthShell } from "@app/auth/ui/AuthShell";-import SpringLoginForm from "@app/auth/ui/SpringLoginForm";-import { useSpringLogin } from "@app/auth/ui/useSpringLogin";-import { withBasePath } from "@app/constants/app";-import "@app/auth/ui/auth-theme.css";-import "@app/auth/ui/auth.css";-import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg";--/**- * Full-screen login shown by the portal's auth gate. Renders the shared- * AuthShell with the Spring form/auth wiring from @app/auth/ui.- *- * It follows the user's light/dark theme (AuthShell is theme-aware — the same- * screen the editor login uses; passing both logo variants keeps the header- * readable in either mode). The gate handles "already logged in", so this only- * needs to collect credentials.- */-export function LoginScreen() {- const login = useSpringLogin();-- return (- <AuthShell>- <SpringLoginForm- state={login}- logoSrc={loginHeader}- logoDarkSrc={withBasePath("/modern-logo/LoginDarkModeHeader.svg")}- />- </AuthShell>- );-}diff --git a/frontend/editor/src/proprietary/routes/Landing.tsx b/frontend/editor/src/proprietary/routes/Landing.tsxindex df65aa9597..8107ad26f1 100644--- a/frontend/editor/src/proprietary/routes/Landing.tsx+++ b/frontend/editor/src/proprietary/routes/Landing.tsx@@ -26,7 +26,8 @@ export default function Landing() {const navigate = useNavigate();const { t } = useTranslation();- const loading = authLoading || configLoading || backendProbe.loading;+ const loading =+ authLoading || (configLoading && !config) || backendProbe.loading;// The backend-down screen is not the app. Loading is: it resolves in a moment.useSuppressQuickNavRail(!session && backendProbe.status !== "up");@@ -182,7 +183,9 @@ export default function Landing() {// authenticated, and carries where we came from so signing in returns there// (going to /editor and logging in lands back on /editor, not the role// router). Also passed as router state; the query is what survives a reload.- const returnTo = encodeURIComponent(location.pathname + location.search);+ const returnTo = encodeURIComponent(+ location.pathname + location.search + location.hash,+ );return config?.enableLogin === true && !backendProbe.loginDisabled ? (<Navigateto={`/login?from=${returnTo}`}diff --git a/frontend/editor/src/proprietary/routes/Login.tsx b/frontend/editor/src/proprietary/routes/Login.tsxindex 5be2f1970d..853a75a39b 100644--- a/frontend/editor/src/proprietary/routes/Login.tsx+++ b/frontend/editor/src/proprietary/routes/Login.tsx@@ -1,5 +1,6 @@import { useEffect, useMemo, useRef, useState } from "react";import {+ type Location,Navigate,useLocation,useNavigate,@@ -43,10 +44,13 @@ export default function Login() {// a reload of /login. Null means "no specific destination" and the caller// falls back to the default landing.const resolveReturnPath = (): string | null => {- const fromState = (- location.state as { from?: { pathname?: string } } | null- )?.from?.pathname;- if (fromState) return safePath(fromState);+ const fromState = (location.state as { from?: Partial<Location> } | null)+ ?.from;+ if (fromState?.pathname) {+ return safePath(+ fromState.pathname + (fromState.search ?? "") + (fromState.hash ?? ""),+ );+ }const fromQuery = searchParams.get("from");if (!fromQuery) return null;try {diff --git a/frontend/editor/src/saas/components/startup/StartupPrompts.test.tsx b/frontend/editor/src/saas/components/startup/StartupPrompts.test.tsxnew file mode 100644index 0000000000..8488f4a02e--- /dev/null+++ b/frontend/editor/src/saas/components/startup/StartupPrompts.test.tsx@@ -0,0 +1,66 @@+import { cleanup, render, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router-dom";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";+import { StartupPrompts } from "@app/components/startup/StartupPrompts";++const h = vi.hoisted(() => ({+ anonymous: false,+ get: vi.fn(),+ consent: vi.fn(),+}));+vi.mock("@app/services/apiClient", () => ({ default: { get: h.get } }));+vi.mock("@app/auth/UseSession", () => ({+ useAuth: () => ({+ user: { id: "cloud-user" },+ isAnonymous: h.anonymous,+ loading: false,+ signOut: vi.fn(),+ }),+}));+vi.mock("@app/hooks/useCookieConsentInitialization", () => ({+ useCookieConsentInitialization: () => h.consent(),+}));+vi.mock("@app/hooks/usePosthogTracking", () => ({+ usePosthogTracking: () => {},+}));+vi.mock("@app/hooks/useScarfTracking", () => ({ useScarfTracking: () => {} }));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it.each([false, true])(+ "shows consent for a hosted account (guest=%s) without Spring account APIs",+ async (anonymous) => {+ h.anonymous = anonymous;+ h.get.mockImplementation(async (url: string) => {+ if (url === "/api/v1/config/app-config")+ return { data: { enableLogin: true, enableAnalytics: true } };+ if (url === "/api/v1/config/login-disclaimer")+ return { data: { enabled: false } };+ throw new Error(`Unexpected request: ${url}`);+ });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ });+ const view = render(+ <MemoryRouter initialEntries={["/processor"]}>+ <QueryClientProvider client={client}>+ <AppConfigProvider>+ <StartupPrompts />+ </AppConfigProvider>+ </QueryClientProvider>+ </MemoryRouter>,+ );+ await waitFor(() => expect(h.consent).toHaveBeenCalled());+ expect(h.get.mock.calls.map(([url]) => url)).toEqual([+ "/api/v1/config/app-config",+ "/api/v1/config/login-disclaimer",+ ]);+ view.unmount();+ client.clear();+ },+);diff --git a/frontend/editor/src/saas/components/startup/StartupSetup.tsx b/frontend/editor/src/saas/components/startup/StartupSetup.tsxnew file mode 100644index 0000000000..e7888bffad--- /dev/null+++ b/frontend/editor/src/saas/components/startup/StartupSetup.tsx@@ -0,0 +1,6 @@+import type { ReactNode } from "react";++/** Hosted accounts use their identity provider's setup; there is no local server to configure. */+export function StartupSetup({ children }: { children: ReactNode }) {+ return <>{children}</>;+}