Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

fix: persist Default tool picker mode and Default view on launch settings (#6827)

Matt Van Horn932031354e34
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index 7365e0c759..a64c5334ee 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -1628,6 +1628,10 @@ public class ApplicationProperties {
public static class Ui {
private String appNameNavbar;
private List<String> languages;
+ // Options: "sidebar" (default) or "fullscreen"
+ private String defaultToolPanelMode = "sidebar";
+ // Options: "tools" (default), "read", or "automate"
+ private String defaultStartupView = "tools";
private boolean defaultHideUnavailableTools = false;
private boolean defaultHideUnavailableConversions = false;
private HideDisabledTools hideDisabledTools = new HideDisabledTools();
@@ -1636,6 +1640,23 @@ public class ApplicationProperties {
return appNameNavbar != null && !appNameNavbar.trim().isEmpty() ? appNameNavbar : null;
}
+ public String getDefaultToolPanelMode() {
+ if ("fullscreen".equalsIgnoreCase(defaultToolPanelMode)) {
+ return "fullscreen";
+ }
+ return "sidebar";
+ }
+
+ public String getDefaultStartupView() {
+ if ("read".equalsIgnoreCase(defaultStartupView)) {
+ return "read";
+ }
+ if ("automate".equalsIgnoreCase(defaultStartupView)) {
+ return "automate";
+ }
+ return "tools";
+ }
+
@Data
public static class HideDisabledTools {
private boolean googleDrive = false;
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
index 22312af85f..c143ca5b1a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
@@ -219,6 +219,11 @@ public class ConfigController {
configData.put("defaultLocale", applicationProperties.getSystem().getDefaultLocale());
// User preference defaults
+ configData.put(
+ "defaultToolPanelMode",
+ applicationProperties.getUi().getDefaultToolPanelMode());
+ configData.put(
+ "defaultStartupView", applicationProperties.getUi().getDefaultStartupView());
configData.put(
"defaultHideUnavailableTools",
applicationProperties.getUi().isDefaultHideUnavailableTools());
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index b4c7ebc0c1..267e4d07d2 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -318,6 +318,8 @@ autoPipeline:
ui:
appNameNavbar: "" # custom app/brand name. NOTE: no longer shown in the navbar (the navbar renders the logo). It IS used as the browser tab title and as the TOTP/2FA issuer label in authenticator apps. Empty falls back to "Stirling PDF"
languages: [] # If empty, all languages are enabled. To restrict to specific languages, use a whitelist like ["de_DE", "pl_PL", "sv_SE"]. Empty list or not restricting any languages will enable all available languages.
+ defaultToolPanelMode: sidebar # Default user preference: open the tool picker in 'sidebar' or 'fullscreen' mode
+ defaultStartupView: tools # Default user preference: first view on launch. Options: 'tools', 'read', or 'automate'
defaultHideUnavailableTools: false # Default user preference: hide disabled tools instead of greying them out
defaultHideUnavailableConversions: false # Default user preference: hide disabled conversion options instead of greying them out
hideDisabledTools:
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerTest.java
index faf5c70985..df0f5e76ee 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerTest.java
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationContext;
+import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -20,6 +21,7 @@ import jakarta.servlet.http.HttpServletRequest;
import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.config.EndpointConfiguration.DisableReason;
import stirling.software.SPDF.config.EndpointConfiguration.EndpointAvailability;
+import stirling.software.SPDF.config.ExternalAppDepConfig;
import stirling.software.common.configuration.AppConfig;
import stirling.software.common.configuration.interfaces.ShowAdminInterface;
import stirling.software.common.model.ApplicationProperties;
@@ -55,6 +57,60 @@ class ConfigControllerTest {
mock(stirling.software.SPDF.config.ExternalAppDepConfig.class));
}
+ @Test
+ void getAppConfig_includesConfiguredDefaultLayoutSettings() {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getUi().setDefaultToolPanelMode("fullscreen");
+ properties.getUi().setDefaultStartupView("read");
+
+ ResponseEntity<Map<String, Object>> response =
+ createConfigController(properties).getAppConfig(mock(HttpServletRequest.class));
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ Map<String, Object> body = response.getBody();
+ assertNotNull(body);
+ assertFalse(body.containsKey("error"));
+ assertEquals("fullscreen", body.get("defaultToolPanelMode"));
+ assertEquals("read", body.get("defaultStartupView"));
+ assertEquals(false, body.get("defaultHideUnavailableTools"));
+ assertEquals(false, body.get("defaultHideUnavailableConversions"));
+ }
+
+ @Test
+ void getAppConfig_includesDefaultLayoutFallbacks() {
+ ResponseEntity<Map<String, Object>> response =
+ createConfigController(new ApplicationProperties())
+ .getAppConfig(mock(HttpServletRequest.class));
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ Map<String, Object> body = response.getBody();
+ assertNotNull(body);
+ assertFalse(body.containsKey("error"));
+ assertEquals("sidebar", body.get("defaultToolPanelMode"));
+ assertEquals("tools", body.get("defaultStartupView"));
+ }
+
+ private ConfigController createConfigController(ApplicationProperties properties) {
+ ApplicationContext context = mock(ApplicationContext.class);
+ ExternalAppDepConfig externalAppDepConfig = mock(ExternalAppDepConfig.class);
+ Environment environment = mock(Environment.class);
+ AppConfig appConfig = new AppConfig(environment, properties);
+
+ when(context.getBean(AppConfig.class)).thenReturn(appConfig);
+ when(context.getEnvironment()).thenReturn(environment);
+ when(externalAppDepConfig.isDependenciesChecked()).thenReturn(true);
+
+ return new ConfigController(
+ properties,
+ context,
+ endpointConfiguration,
+ serverCertificateService,
+ userService,
+ showAdmin,
+ licenseService,
+ externalAppDepConfig);
+ }
+
@Test
void isEndpointEnabled_returnsTrue() {
when(endpointConfiguration.isEndpointEnabled("flatten")).thenReturn(true);
diff --git a/frontend/editor/src/core/components/AppProviders.tsx b/frontend/editor/src/core/components/AppProviders.tsx
index 1242cc0039..e27fb679b6 100644
--- a/frontend/editor/src/core/components/AppProviders.tsx
+++ b/frontend/editor/src/core/components/AppProviders.tsx
@@ -37,6 +37,7 @@ import { FormFillProvider } from "@app/tools/formFill/FormFillContext";
import { FolderProvider } from "@app/contexts/FolderContext";
import { WorkbenchSessionPersistence } from "@app/components/session/WorkbenchSessionPersistence";
import { retireLegacyFolderWorker } from "@app/services/retireLegacyFolderWorker";
+import type { UserPreferences } from "@app/services/preferencesService";
// Component to run app-level initialization (must be inside AppProviders for context access)
function AppInitializer() {
@@ -85,19 +86,37 @@ export interface AppProvidersProps {
// Component to sync server defaults to preferences when AppConfig loads
function ServerDefaultsSync() {
- const { config } = useAppConfig();
+ const { config, configFromServer } = useAppConfig();
const { updateServerDefaults } = usePreferences();
useEffect(() => {
- if (config) {
- const serverDefaults = {
+ // A stand-in (401 default, auth-page fallback, desktop startup config)
+ // must not count as the server's answer. Installing it marks defaults as
+ // loaded and the launch then locks in "tools".
+ if (config && configFromServer) {
+ // Only known values. An absent or unexpected field must not clobber the
+ // hardcoded default via an explicit `undefined` in the merge.
+ const serverDefaults: Partial<UserPreferences> = {
hideUnavailableTools: config.defaultHideUnavailableTools ?? false,
hideUnavailableConversions:
config.defaultHideUnavailableConversions ?? false,
};
+ if (
+ config.defaultToolPanelMode === "sidebar" ||
+ config.defaultToolPanelMode === "fullscreen"
+ ) {
+ serverDefaults.defaultToolPanelMode = config.defaultToolPanelMode;
+ }
+ if (
+ config.defaultStartupView === "tools" ||
+ config.defaultStartupView === "read" ||
+ config.defaultStartupView === "automate"
+ ) {
+ serverDefaults.defaultStartupView = config.defaultStartupView;
+ }
updateServerDefaults(serverDefaults);
}
- }, [config, updateServerDefaults]);
+ }, [config, configFromServer, updateServerDefaults]);
return null;
}
diff --git a/frontend/editor/src/core/contexts/AppConfigContext.tsx b/frontend/editor/src/core/contexts/AppConfigContext.tsx
index 2926c00345..c9c5a514a5 100644
--- a/frontend/editor/src/core/contexts/AppConfigContext.tsx
+++ b/frontend/editor/src/core/contexts/AppConfigContext.tsx
@@ -24,6 +24,13 @@ export type { AppConfig, AppConfigBootstrapMode };
interface AppConfigContextValue {
config: AppConfig | null;
+ /**
+ * True only for a real /app-config payload, or a caller-supplied seed with
+ * fetching disabled. The 401 stand-in (the DEFAULT_APP_CONFIG singleton) and
+ * the auth-page fallback are not the server's answer; the desktop hook also
+ * clears this for its startup placeholder.
+ */
+ configFromServer: boolean;
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
@@ -31,6 +38,7 @@ interface AppConfigContextValue {
const AppConfigContext = createContext<AppConfigContextValue | undefined>({
config: null,
+ configFromServer: false,
loading: true,
error: null,
refetch: async () => {},
@@ -116,12 +124,19 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
if (data) onConfigLoadedRef.current?.(data);
}, [data]);
- const value = useMemo<AppConfigContextValue>(
- () => ({
+ const value = useMemo<AppConfigContextValue>(() => {
+ // fetchAppConfig turns a 401 into the DEFAULT_APP_CONFIG singleton instead
+ // of failing the query, so a resolved `data` can still be a stand-in.
+ // Identity is what separates that cached default from a server payload.
+ const configFromServer =
+ (data != null && data !== DEFAULT_APP_CONFIG) ||
+ (data == null && !autoFetch && initialConfig != null);
+ return {
config:
data ??
initialConfig ??
(isAuthPage || error ? DEFAULT_APP_CONFIG : null),
+ configFromServer,
// "Config not settled yet": in flight, or never going to be fetched at
// all. isFetching rather than isPending because a pre-login 401 resolves
// to the default config, so isPending is already false by the time the
@@ -135,19 +150,18 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
: false,
error: error ? errorMessage(error) : null,
refetch,
- }),
- [
- data,
- error,
- isFetching,
- initialConfig,
- isAuthPage,
- seeded,
- autoFetch,
- fetching,
- refetch,
- ],
- );
+ };
+ }, [
+ data,
+ error,
+ isFetching,
+ initialConfig,
+ isAuthPage,
+ seeded,
+ autoFetch,
+ fetching,
+ refetch,
+ ]);
return (
<AppConfigContext.Provider value={value}>
diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.startupView.test.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.startupView.test.tsx
new file mode 100644
index 0000000000..0287db037a
--- /dev/null
+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.startupView.test.tsx
@@ -0,0 +1,249 @@
+import "fake-indexeddb/auto";
+import type { ReactNode } from "react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter, useLocation, useNavigate } from "react-router-dom";
+import { AppProviders } from "@app/components/AppProviders";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { usePreferences } from "@app/contexts/PreferencesContext";
+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
+import { preferencesService } from "@app/services/preferencesService";
+import apiClient from "@app/services/apiClient";
+import type { AppConfig } from "@app/types/appConfig";
+
+const STORAGE_KEY = "stirlingpdf_preferences";
+const originalGet = apiClient.get.bind(apiClient);
+
+function LaunchProbe() {
+ const workflow = useToolWorkflow();
+ const { preferences } = usePreferences();
+ const { configFromServer, loading } = useAppConfig();
+ const { pathname } = useLocation();
+ return (
+ <div
+ data-testid="launch"
+ data-reader={String(workflow.readerMode)}
+ data-tool={workflow.selectedToolKey ?? ""}
+ data-panel={workflow.toolPanelMode}
+ data-startup={preferences.defaultStartupView}
+ data-mode={preferences.defaultToolPanelMode}
+ data-from-server={String(configFromServer)}
+ data-loading={String(loading)}
+ data-path={pathname}
+ />
+ );
+}
+
+function GoHome() {
+ const navigate = useNavigate();
+ return (
+ <>
+ <button type="button" onClick={() => navigate("/")}>
+ home
+ </button>
+ <LaunchProbe />
+ </>
+ );
+}
+
+function renderLaunch(
+ ui: ReactNode,
+ options: {
+ config?: AppConfig | null;
+ path?: string;
+ autoFetch?: boolean;
+ } = {},
+) {
+ const { config = null, path = "/", autoFetch = false } = options;
+ render(
+ <MemoryRouter initialEntries={[path]}>
+ <AppProviders
+ appConfigProviderProps={{
+ initialConfig: config,
+ bootstrapMode: "non-blocking",
+ autoFetch,
+ }}
+ >
+ {ui}
+ </AppProviders>
+ </MemoryRouter>,
+ );
+ return screen.getByTestId("launch");
+}
+
+function renderWithConfig(config: AppConfig) {
+ return renderLaunch(<LaunchProbe />, { config });
+}
+
+describe("server default reaches the launch view", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ preferencesService.clearServerDefaults();
+ });
+
+ it("opens reading from the server default when nothing is stored", async () => {
+ const launch = renderWithConfig({
+ defaultStartupView: "read",
+ defaultToolPanelMode: "fullscreen",
+ });
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-reader", "true");
+ expect(launch).toHaveAttribute("data-startup", "read");
+ expect(launch).toHaveAttribute("data-panel", "fullscreen");
+ expect(launch).toHaveAttribute("data-mode", "fullscreen");
+ });
+ // The server choice stays a default: it must not be written as the user's.
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+ });
+
+ it("keeps a stored launch view ahead of the server default", async () => {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({
+ defaultStartupView: "automate",
+ defaultToolPanelMode: "sidebar",
+ }),
+ );
+ const launch = renderWithConfig({
+ defaultStartupView: "read",
+ defaultToolPanelMode: "fullscreen",
+ });
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-tool", "automate");
+ expect(launch).toHaveAttribute("data-reader", "false");
+ expect(launch).toHaveAttribute("data-startup", "automate");
+ expect(launch).toHaveAttribute("data-panel", "sidebar");
+ expect(launch).toHaveAttribute("data-mode", "sidebar");
+ });
+ expect(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}")).toMatchObject(
+ {
+ defaultStartupView: "automate",
+ defaultToolPanelMode: "sidebar",
+ },
+ );
+ });
+
+ it("applies a server default that arrives after mount", async () => {
+ let resolveConfig: (value: unknown) => void = () => {};
+ const pending = new Promise((resolve) => {
+ resolveConfig = resolve;
+ });
+ const get = vi.spyOn(apiClient, "get").mockImplementation((url, config) => {
+ if (String(url).includes("app-config")) return pending;
+ return originalGet(url, config);
+ });
+ try {
+ const launch = renderLaunch(<LaunchProbe />, { autoFetch: true });
+ expect(launch).toHaveAttribute("data-reader", "false");
+ expect(launch).toHaveAttribute("data-tool", "");
+ expect(launch).toHaveAttribute("data-from-server", "false");
+
+ await act(async () => {
+ resolveConfig({
+ status: 200,
+ data: { defaultStartupView: "automate" },
+ });
+ });
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-tool", "automate");
+ expect(launch).toHaveAttribute("data-reader", "false");
+ expect(launch).toHaveAttribute("data-startup", "automate");
+ expect(launch).toHaveAttribute("data-from-server", "true");
+ });
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+ } finally {
+ get.mockRestore();
+ }
+ });
+
+ it("ignores a 401 stand-in and applies the real server default", async () => {
+ let appConfigCalls = 0;
+ const get = vi.spyOn(apiClient, "get").mockImplementation((url, config) => {
+ if (String(url).includes("app-config")) {
+ appConfigCalls += 1;
+ if (appConfigCalls === 1) {
+ return Promise.reject(
+ Object.assign(new Error("Unauthorized"), {
+ response: { status: 401, data: {} },
+ }),
+ );
+ }
+ return Promise.resolve({
+ status: 200,
+ data: { enableLogin: true, defaultStartupView: "read" },
+ });
+ }
+ return originalGet(url, config);
+ });
+ try {
+ const launch = renderLaunch(<LaunchProbe />, { autoFetch: true });
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-loading", "false");
+ });
+ // The cached login default must not spend the launch on "tools".
+ expect(launch).toHaveAttribute("data-from-server", "false");
+ expect(launch).toHaveAttribute("data-reader", "false");
+ expect(launch).toHaveAttribute("data-startup", "tools");
+
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent("jwt-available"));
+ });
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-reader", "true");
+ expect(launch).toHaveAttribute("data-startup", "read");
+ expect(launch).toHaveAttribute("data-from-server", "true");
+ });
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+ } finally {
+ get.mockRestore();
+ }
+ });
+
+ it("applies the server default after signing in from /login", async () => {
+ const launch = renderLaunch(<GoHome />, {
+ config: { defaultStartupView: "read" },
+ path: "/login",
+ });
+
+ expect(launch).toHaveAttribute("data-from-server", "true");
+ expect(launch).toHaveAttribute("data-reader", "false");
+ expect(launch).toHaveAttribute("data-startup", "read");
+
+ fireEvent.click(screen.getByRole("button", { name: "home" }));
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-reader", "true");
+ });
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+ });
+
+ it("does not replace a deep link when the editor home is opened later", async () => {
+ const launch = renderLaunch(<GoHome />, {
+ config: { defaultStartupView: "read" },
+ path: "/compress",
+ });
+
+ expect(launch).toHaveAttribute("data-reader", "false");
+
+ fireEvent.click(screen.getByRole("button", { name: "home" }));
+
+ await waitFor(() => {
+ expect(launch).toHaveAttribute("data-path", "/");
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(launch).toHaveAttribute("data-reader", "false");
+ });
+});
diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
index b1ef312d05..f2365b5ac7 100644
--- a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
@@ -12,6 +12,7 @@ import React, {
useEffect,
useRef,
} from "react";
+import { useLocation } from "react-router-dom";
import {
useToolManagement,
type ToolAvailabilityMap,
@@ -28,7 +29,7 @@ import {
isBaseWorkbench,
} from "@app/types/workbench";
import { useNavigationUrlSync } from "@app/hooks/useUrlSync";
-import { stripBasePath } from "@app/constants/app";
+import { isAuthRoute } from "@app/constants/routes";
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
import { filterToolRegistryByQuery } from "@app/utils/toolSearch";
import { useToolHistory } from "@app/hooks/tools/useUserToolActivity";
@@ -39,7 +40,9 @@ import {
toolWorkflowReducer,
} from "@app/contexts/toolWorkflow/toolWorkflowState";
import type { ToolPanelMode } from "@app/constants/toolPanel";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
import { usePreferences } from "@app/contexts/PreferencesContext";
+import { preferencesService } from "@app/services/preferencesService";
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
import { ToolFileEligibilityProvider } from "@app/contexts/ToolFileEligibilityContext";
@@ -175,6 +178,28 @@ const ToolWorkflowDataContext = createContext<
ToolWorkflowDataValue | undefined
>(undefined);
+// Login, signup, invite, share, and the account-link page all sit inside these
+// providers and then navigate into the editor without remounting. Spending the
+// launch there would drop the admin default. A tool URL is not one of these:
+// that address wins.
+function defersStartupView(pathname: string): boolean {
+ if (isAuthRoute(pathname)) return true;
+ return (
+ pathname === "/link" ||
+ pathname.startsWith("/link/") ||
+ pathname === "/share" ||
+ pathname.startsWith("/share/")
+ );
+}
+
+function isEditorHome(pathname: string): boolean {
+ const path =
+ pathname.length > 1 && pathname.endsWith("/")
+ ? pathname.slice(0, -1)
+ : pathname;
+ return path === "/" || path === EDITOR_BASENAME;
+}
+
// Provider component
interface ToolWorkflowProviderProps {
children: React.ReactNode;
@@ -187,6 +212,8 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
createInitialState,
);
const { preferences, updatePreference } = usePreferences();
+ const { pathname } = useLocation();
+ const { configFromServer } = useAppConfig();
// Store reset functions for tools
const [toolResetFunctions, setToolResetFunctions] = React.useState<
@@ -382,31 +409,46 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
}
}, [preferences.defaultToolPanelMode, state.toolPanelMode]);
- // Apply default startup view preference on initial load.
- // This runs once to navigate to the user's preferred tab (read/automate)
- // instead of always starting on the tools tab.
+ // One launch decision. A stored choice wins without waiting. Otherwise wait
+ // for a real /app-config: a stand-in looks loaded and would lock this in as
+ // "tools". Auth routes must not spend the launch, because sign-in navigates
+ // here without remounting; a deep link does, because the URL wins. A reload
+ // keeps the open view, unless that reload was the login page.
const hasAppliedStartupView = React.useRef(false);
+ // True once an auth route was showing, so its document reload does not count
+ // as the launch after sign-in moves to the editor.
+ const deferredStartupForAuth = React.useRef(false);
// Set when the startup view picks the tool, so the URL sync knows this
// selection came from a preference and must not be written to the address.
const startupSelectedToolRef = React.useRef<ToolId | null>(null);
useEffect(() => {
if (hasAppliedStartupView.current) return;
- // The URL wins: the startup view decides what you see when you arrive at the
- // editor's home, never what a deep link to a tool shows. Without this, a
- // "Reader" preference rewrote every /<tool> link to /read.
- const path = stripBasePath(window.location.pathname);
- // A reload is not a launch: it keeps whichever view the user had open.
+ if (defersStartupView(pathname)) {
+ deferredStartupForAuth.current = true;
+ return;
+ }
const navigation = performance.getEntriesByType?.("navigation")[0] as
| PerformanceNavigationTiming
| undefined;
+ const reloaded =
+ !deferredStartupForAuth.current && navigation?.type === "reload";
+ if (reloaded || !isEditorHome(pathname)) {
+ hasAppliedStartupView.current = true;
+ return;
+ }
if (
- navigation?.type === "reload" ||
- (path !== "/" && path !== EDITOR_BASENAME)
+ !preferencesService.hasStoredPreference("defaultStartupView") &&
+ (!configFromServer || !preferencesService.hasServerDefaults())
) {
- hasAppliedStartupView.current = true;
return;
}
- const startupView = preferences.defaultStartupView;
+ // The service, not this render's snapshot: defaults can be installed in the
+ // same commit, before PreferencesProvider re-renders with the merge.
+ const startupView = preferencesService.hasStoredPreference(
+ "defaultStartupView",
+ )
+ ? preferences.defaultStartupView
+ : preferencesService.getPreference("defaultStartupView");
if (startupView === "read") {
// Reading is a surface, not a tool: selecting the Read tool as well would
// disagree with the reader's address, and the URL sync would close both.
@@ -424,7 +466,9 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
hasAppliedStartupView.current = true;
}
}, [
- preferences.defaultStartupView,
+ pathname,
+ preferences,
+ configFromServer,
actions,
setReaderMode,
setLeftPanelView,
diff --git a/frontend/editor/src/core/services/preferencesService.ts b/frontend/editor/src/core/services/preferencesService.ts
index b68cf3a645..0bcc3dd14a 100644
--- a/frontend/editor/src/core/services/preferencesService.ts
+++ b/frontend/editor/src/core/services/preferencesService.ts
@@ -59,9 +59,36 @@ const STORAGE_KEY = "stirlingpdf_preferences";
class PreferencesService {
private serverDefaults: Partial<UserPreferences> = {};
+ // False until a real /app-config has been applied, so a launch can tell "not
+ // loaded yet" apart from "loaded, and the server's choice is the hardcoded
+ // one". Callers must not set this for a stand-in config: the launch treats
+ // the flag as "the server has answered" and would lock in "tools".
+ private serverDefaultsInstalled = false;
setServerDefaults(defaults: Partial<UserPreferences>): void {
this.serverDefaults = defaults;
+ this.serverDefaultsInstalled = true;
+ }
+
+ hasServerDefaults(): boolean {
+ return this.serverDefaultsInstalled;
+ }
+
+ clearServerDefaults(): void {
+ this.serverDefaults = {};
+ this.serverDefaultsInstalled = false;
+ }
+
+ // A missing key is not a choice: it falls through to the server default.
+ hasStoredPreference<K extends keyof UserPreferences>(key: K): boolean {
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ if (!stored) return false;
+ const preferences = JSON.parse(stored) as Partial<UserPreferences>;
+ return key in preferences && preferences[key] !== undefined;
+ } catch {
+ return false;
+ }
}
getPreference<K extends keyof UserPreferences>(key: K): UserPreferences[K] {
diff --git a/frontend/editor/src/core/types/appConfig.ts b/frontend/editor/src/core/types/appConfig.ts
index 2dec90ca65..4e783ce15f 100644
--- a/frontend/editor/src/core/types/appConfig.ts
+++ b/frontend/editor/src/core/types/appConfig.ts
@@ -55,6 +55,10 @@ export interface AppConfig {
error?: string;
isNewServer?: boolean;
isNewUser?: boolean;
+ /** Server tool-panel default; a stored user preference takes precedence. */
+ defaultToolPanelMode?: "sidebar" | "fullscreen";
+ /** Server startup-view default; a stored user preference takes precedence. */
+ defaultStartupView?: "tools" | "read" | "automate";
defaultHideUnavailableTools?: boolean;
defaultHideUnavailableConversions?: boolean;
storageEnabled?: boolean;
diff --git a/frontend/editor/src/desktop/config/defaultAppConfig.ts b/frontend/editor/src/desktop/config/defaultAppConfig.ts
index 58290870ae..6920947a94 100644
--- a/frontend/editor/src/desktop/config/defaultAppConfig.ts
+++ b/frontend/editor/src/desktop/config/defaultAppConfig.ts
@@ -1,4 +1,4 @@
-import { AppConfig } from "@app/contexts/AppConfigContext";
+import type { AppConfig } from "@app/types/appConfig";
/**
* Default configuration used while the bundled backend starts up.
diff --git a/frontend/editor/src/desktop/contexts/AppConfigContext.tsx b/frontend/editor/src/desktop/contexts/AppConfigContext.tsx
index 3372b3bd2f..f9eef6f655 100644
--- a/frontend/editor/src/desktop/contexts/AppConfigContext.tsx
+++ b/frontend/editor/src/desktop/contexts/AppConfigContext.tsx
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import { useAppConfig as useCoreAppConfig } from "@core/contexts/AppConfigContext";
import { useLocalProcessingOnly } from "@app/hooks/useLocalProcessingOnly";
+import { DESKTOP_DEFAULT_APP_CONFIG } from "@app/config/defaultAppConfig";
export { AppConfigProvider } from "@core/contexts/AppConfigContext";
export type {
@@ -14,24 +15,30 @@ export type {
export function useAppConfig() {
const context = useCoreAppConfig();
const localOnly = useLocalProcessingOnly();
- return useMemo(
- () =>
- !localOnly || !context.config
+ return useMemo(() => {
+ // Core treats a non-fetching seed as the server's answer. The desktop shell
+ // seeds DESKTOP_DEFAULT_APP_CONFIG until the bundled backend responds; that
+ // object is not the server's answer.
+ const configFromServer =
+ context.configFromServer && context.config !== DESKTOP_DEFAULT_APP_CONFIG;
+ const withSource =
+ configFromServer === context.configFromServer
? context
- : {
- ...context,
- config: {
- ...context.config,
- storageEnabled: false,
- storageSharingEnabled: false,
- storageShareLinksEnabled: false,
- storageShareEmailEnabled: false,
- storageGroupSigningEnabled: false,
- aiEngineEnabled: false,
- enableMobileScanner: false,
- enableMobileSignature: false,
- },
- },
- [context, localOnly],
- );
+ : { ...context, configFromServer };
+ if (!localOnly || !withSource.config) return withSource;
+ return {
+ ...withSource,
+ config: {
+ ...withSource.config,
+ storageEnabled: false,
+ storageSharingEnabled: false,
+ storageShareLinksEnabled: false,
+ storageShareEmailEnabled: false,
+ storageGroupSigningEnabled: false,
+ aiEngineEnabled: false,
+ enableMobileScanner: false,
+ enableMobileSignature: false,
+ },
+ };
+ }, [context, localOnly]);
}
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.test.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.test.tsx
new file mode 100644
index 0000000000..6b2397715b
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.test.tsx
@@ -0,0 +1,44 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { MantineProvider } from "@mantine/core";
+import { UserDefaultsCard } from "@app/components/shared/config/configSections/server/UserDefaultsCard";
+import type { UiDefaultsSettingsData } from "@app/components/shared/config/configSections/server/serverSettings";
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({
+ t: (_key: string, fallback?: string) => fallback ?? _key,
+ i18n: { changeLanguage: vi.fn() },
+ }),
+}));
+
+const settings: UiDefaultsSettingsData = {
+ defaultHideUnavailableTools: false,
+ defaultHideUnavailableConversions: false,
+ defaultToolPanelMode: "sidebar",
+ defaultStartupView: "tools",
+};
+
+describe("UserDefaultsCard", () => {
+ it("names the new controls and keeps their labels out of a paragraph", () => {
+ const { container } = render(
+ <MantineProvider>
+ <UserDefaultsCard
+ settings={settings}
+ setSettings={vi.fn()}
+ isFieldPending={() => false}
+ loginEnabled
+ />
+ </MantineProvider>,
+ );
+
+ expect(
+ screen.getByRole("radiogroup", { name: "Default tool picker mode" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("radiogroup", { name: "Default view on launch" }),
+ ).toBeInTheDocument();
+ // Text renders a <p>; a Group inside it is the div-in-p warning.
+ expect(container.querySelector("p div, p > div")).toBeNull();
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsx
index 5537ff6fd1..937cfff695 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/UserDefaultsCard.tsx
@@ -1,10 +1,16 @@
import { useTranslation } from "react-i18next";
import { Stack, Paper } from "@mantine/core";
+import { SegmentedControl } from "@app/ui/SegmentedControl";
+import { InfoTooltip } from "@app/ui/InfoTooltip";
import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";
+import PendingBadge from "@app/components/shared/config/PendingBadge";
+import "@app/components/shared/config/SettingsToggleRow.css";
import type { UiDefaultsCardProps } from "@app/components/shared/config/configSections/server/serverCardProps";
+import type { ToolPanelMode } from "@app/constants/toolPanel";
+import type { StartupView } from "@app/services/preferencesService";
/**
- * Starting values for two per-user preferences. Its own `ui` draft, kept apart
+ * Starting values for four per-user preferences. Its own `ui` draft, kept apart
* from the System card's ui.* keys so each save still sends only what changed.
*/
export function UserDefaultsCard({
@@ -15,6 +21,23 @@ export function UserDefaultsCard({
}: UiDefaultsCardProps) {
const { t } = useTranslation();
+ const toolPanelModeValue: ToolPanelMode =
+ settings.defaultToolPanelMode === "fullscreen" ? "fullscreen" : "sidebar";
+ const startupViewValue: StartupView =
+ settings.defaultStartupView === "read" ||
+ settings.defaultStartupView === "automate"
+ ? settings.defaultStartupView
+ : "tools";
+
+ const toolPanelLabel = t(
+ "settings.general.defaultToolPickerMode",
+ "Default tool picker mode",
+ );
+ const startupViewLabel = t(
+ "settings.general.defaultStartupView",
+ "Default view on launch",
+ );
+
return (
<Paper withBorder p="md" radius="md">
<Stack gap="md">
@@ -59,6 +82,80 @@ export function UserDefaultsCard({
}}
disabled={!loginEnabled}
/>
+
+ <div className="settings-toggle">
+ <div className="settings-toggle__row">
+ <span className="settings-toggle__label">
+ <span className="settings-toggle__title">{toolPanelLabel}</span>
+ <PendingBadge show={isFieldPending("defaultToolPanelMode")} />
+ <InfoTooltip
+ label={t(
+ "settings.general.defaultToolPickerModeDescription",
+ "Choose whether the tool picker opens in fullscreen or sidebar by default",
+ )}
+ />
+ </span>
+ <SegmentedControl<ToolPanelMode>
+ className="settings-toggle__control"
+ ariaLabel={toolPanelLabel}
+ value={toolPanelModeValue}
+ onChange={(value) => {
+ if (!loginEnabled) return;
+ setSettings({ ...settings, defaultToolPanelMode: value });
+ }}
+ options={[
+ {
+ label: t("settings.general.mode.sidebar", "Sidebar"),
+ value: "sidebar",
+ },
+ {
+ label: t("settings.general.mode.fullscreen", "Fullscreen"),
+ value: "fullscreen",
+ },
+ ]}
+ disabled={!loginEnabled}
+ />
+ </div>
+ </div>
+
+ <div className="settings-toggle">
+ <div className="settings-toggle__row">
+ <span className="settings-toggle__label">
+ <span className="settings-toggle__title">{startupViewLabel}</span>
+ <PendingBadge show={isFieldPending("defaultStartupView")} />
+ <InfoTooltip
+ label={t(
+ "settings.general.defaultStartupViewDescription",
+ "Choose which view is active when the app starts",
+ )}
+ />
+ </span>
+ <SegmentedControl<StartupView>
+ className="settings-toggle__control"
+ ariaLabel={startupViewLabel}
+ value={startupViewValue}
+ onChange={(value) => {
+ if (!loginEnabled) return;
+ setSettings({ ...settings, defaultStartupView: value });
+ }}
+ options={[
+ {
+ label: t("settings.general.startupView.tools", "Tools"),
+ value: "tools",
+ },
+ {
+ label: t("settings.general.startupView.read", "Read"),
+ value: "read",
+ },
+ {
+ label: t("settings.general.startupView.automate", "Automate"),
+ value: "automate",
+ },
+ ]}
+ disabled={!loginEnabled}
+ />
+ </div>
+ </div>
</Stack>
</Paper>
);
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.ts
index 5e55707e6a..4452391df1 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.ts
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/serverSettings.ts
@@ -7,6 +7,9 @@
* the general draft as `serverCertificate` - one hook and one GET fewer.
*/
+import type { ToolPanelMode } from "@app/constants/toolPanel";
+import type { StartupView } from "@app/services/preferencesService";
+
export interface GeneralSettingsData {
ui: {
appNameNavbar?: string;
@@ -54,6 +57,8 @@ export interface GeneralSettingsData {
export interface UiDefaultsSettingsData {
defaultHideUnavailableTools?: boolean;
defaultHideUnavailableConversions?: boolean;
+ defaultToolPanelMode?: ToolPanelMode;
+ defaultStartupView?: StartupView;
}
export interface EndpointsSettingsData {