Skip to content

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

Ask signed-out desktop users to sign in for tools that need an account (#8952)

Anthony Stirlingf0fec0c87c3f
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 6f7461d927..e4b1791860 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -4403,6 +4403,7 @@ pdfUaTitle = "Document title"
pdfUaTitleHelp = "Shown by a reader instead of the filename. Left blank, the first heading is used."
selectSourceFormatFirst = "Choose a source format first"
settings = "Settings"
+signInToUse = "Sign in to use"
single = "Single"
sourceFormatPlaceholder = "Source format"
stirlingOfficeConvert = "Use Stirling Office Convert (beta)"
@@ -14267,7 +14268,6 @@ toggleDetails = "Toggle details"
[tool]
endpointUnavailable = "This tool is unavailable on your server."
-endpointUnavailableClickable = "Not available in this mode. Click to sign in."
filesLoading = "Files are still loading, please wait."
filesLoadingProgress = "{{loaded}} / {{total}} files loading..."
invalidParams = "Fill in the required settings."
@@ -14275,6 +14275,8 @@ noFiles = "Add a file to get started."
scopeFiles = "files"
scopeThisFile = "this file"
selectFilesHint = "Select files in Active Files to run this tool"
+signInRequired = "This needs a Stirling account. Sign in to continue."
+signInToUse = "Sign in to use"
singleFileScope = "Only applying to: {{fileName}}"
viewerMode = "Switch to the file editor to add multiple files."
diff --git a/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx b/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx
index 919db13443..e2a8a77560 100644
--- a/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx
+++ b/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx
@@ -14,6 +14,7 @@ import {
} from "@editor/utils/convertUtils";
import { getConversionEndpoints } from "@editor/data/toolsTaxonomy";
import { usePreferences } from "@editor/contexts/PreferencesContext";
+import { useToolActions } from "@editor/contexts/ToolActionsContext";
import { useConversionCloudStatus } from "@editor/hooks/useConversionCloudStatus";
import { useLocalProcessingOnly } from "@editor/hooks/useLocalProcessingOnly";
import GroupedFormatDropdown from "@editor/components/tools/convert/GroupedFormatDropdown";
@@ -87,7 +88,19 @@ const ConvertSettings = ({
return endpoints;
}, []);
- const { endpointStatus } = useMultipleEndpointsEnabled(allEndpoints);
+ const { endpointStatus, endpointDetails } =
+ useMultipleEndpointsEnabled(allEndpoints);
+ const { onEndpointUnavailableClick } = useToolActions();
+
+ const unlockedBySignIn = (fromExt: string, toExt: string): boolean => {
+ const endpointKey = getEndpointName(fromExt, toExt);
+ return (
+ !localProcessingOnly &&
+ !!onEndpointUnavailableClick &&
+ !!endpointKey &&
+ endpointDetails?.[endpointKey]?.reason === "NOT_SUPPORTED_LOCALLY"
+ );
+ };
// Get comprehensive conversion status (availability + cloud routing)
const conversionStatus = useConversionCloudStatus();
@@ -121,10 +134,16 @@ const ConvertSettings = ({
(targetOption) =>
isConversionAvailable(option.value, targetOption.value),
);
+ const needsSignIn =
+ !hasAvailableConversions &&
+ availableConversions.some((targetOption) =>
+ unlockedBySignIn(option.value, targetOption.value),
+ );
return {
...option,
- enabled: hasAvailableConversions,
+ enabled: hasAvailableConversions || needsSignIn,
+ needsSignIn,
};
});
@@ -154,6 +173,8 @@ const ConvertSettings = ({
}, [
parameters.fromExtension,
endpointStatus,
+ endpointDetails,
+ onEndpointUnavailableClick,
hideUnavailableConversions,
conversionStatus,
]);
@@ -169,14 +190,16 @@ const ConvertSettings = ({
parameters.fromExtension,
option.value,
);
- const usesCloud = doesConversionUseCloud(
- parameters.fromExtension,
- option.value,
- );
+ const needsSignIn =
+ !enabled && unlockedBySignIn(parameters.fromExtension, option.value);
+ const usesCloud =
+ !needsSignIn &&
+ doesConversionUseCloud(parameters.fromExtension, option.value);
return {
...option,
- enabled,
+ enabled: enabled || needsSignIn,
usesCloud,
+ needsSignIn,
};
});
@@ -188,6 +211,8 @@ const ConvertSettings = ({
}, [
parameters.fromExtension,
endpointStatus,
+ endpointDetails,
+ onEndpointUnavailableClick,
hideUnavailableConversions,
conversionStatus,
]);
diff --git a/frontend/src/editor/core/components/tools/convert/GroupedFormatDropdown.tsx b/frontend/src/editor/core/components/tools/convert/GroupedFormatDropdown.tsx
index 1e2dcf1d43..139e7380d7 100644
--- a/frontend/src/editor/core/components/tools/convert/GroupedFormatDropdown.tsx
+++ b/frontend/src/editor/core/components/tools/convert/GroupedFormatDropdown.tsx
@@ -20,6 +20,7 @@ interface FormatOption {
group: string;
enabled?: boolean;
usesCloud?: boolean;
+ needsSignIn?: boolean;
}
interface GroupedFormatDropdownProps {
@@ -165,8 +166,19 @@ const GroupedFormatDropdown = ({
size="sm"
onClick={() => handleOptionSelect(option.value)}
disabled={option.enabled === false}
+ title={
+ option.needsSignIn
+ ? t("convert.signInToUse", "Sign in to use")
+ : undefined
+ }
rightSection={
- option.usesCloud ? (
+ option.needsSignIn ? (
+ <Icon
+ name="lock"
+ size={"0.625rem"}
+ style={{ marginLeft: "0.25rem", opacity: 0.7 }}
+ />
+ ) : option.usesCloud ? (
<Icon
name="cloud"
size={"0.625rem"}
diff --git a/frontend/src/editor/core/components/tools/shared/OperationButton.test.tsx b/frontend/src/editor/core/components/tools/shared/OperationButton.test.tsx
new file mode 100644
index 0000000000..596fdbe3fe
--- /dev/null
+++ b/frontend/src/editor/core/components/tools/shared/OperationButton.test.tsx
@@ -0,0 +1,110 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import OperationButton from "@editor/components/tools/shared/OperationButton";
+import { ToolActionsContext } from "@editor/contexts/ToolActionsContext";
+
+const health = vi.hoisted(() => ({ isOnline: true }));
+vi.mock("@editor/hooks/useBackendHealth", () => ({
+ useBackendHealth: () => ({ isOnline: health.isOnline }),
+}));
+vi.mock("@editor/ui/Icon", () => ({ Icon: () => null }));
+
+function renderButton(onEndpointUnavailableClick?: () => void) {
+ const run = vi.fn();
+ render(
+ <MantineProvider>
+ <ToolActionsContext.Provider value={{ onEndpointUnavailableClick }}>
+ <OperationButton
+ onClick={run}
+ disabledReason="endpointUnavailable"
+ submitText="Convert"
+ data-testid="run"
+ />
+ </ToolActionsContext.Provider>
+ </MantineProvider>,
+ );
+ return run;
+}
+
+describe("OperationButton", () => {
+ beforeEach(() => {
+ health.isOnline = true;
+ });
+
+ it("turns into a sign-in prompt when signing in would unlock the tool", () => {
+ const signIn = vi.fn();
+ const run = renderButton(signIn);
+
+ expect(screen.queryByText("tool.signInRequired")).toBeNull();
+ const button = screen.getByTestId("run");
+ expect(button).toBeEnabled();
+ expect(button).toHaveTextContent("tool.signInToUse");
+ fireEvent.click(button);
+ expect(signIn).toHaveBeenCalledOnce();
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it("becomes the run button once the tool is available", () => {
+ const signIn = vi.fn();
+ const run = vi.fn();
+ const ui = (disabledReason?: "endpointUnavailable") => (
+ <MantineProvider>
+ <ToolActionsContext.Provider
+ value={{ onEndpointUnavailableClick: signIn }}
+ >
+ <OperationButton
+ onClick={run}
+ disabledReason={disabledReason}
+ submitText="Convert"
+ data-testid="run"
+ />
+ </ToolActionsContext.Provider>
+ </MantineProvider>
+ );
+ const { rerender } = render(ui("endpointUnavailable"));
+ expect(screen.getByTestId("run")).toHaveTextContent("tool.signInToUse");
+
+ rerender(ui());
+
+ expect(screen.queryByTestId("sign-in-required")).toBeNull();
+ const button = screen.getByTestId("run");
+ expect(button).toHaveTextContent("Convert");
+ fireEvent.click(button);
+ expect(run).toHaveBeenCalledOnce();
+ expect(signIn).not.toHaveBeenCalled();
+ });
+
+ it("stays disabled when no sign-in can unlock the tool", () => {
+ renderButton();
+
+ expect(screen.queryByTestId("sign-in-required")).toBeNull();
+ expect(screen.getByTestId("run")).toBeDisabled();
+ });
+
+ it("keeps the sign-in prompt while the backend is offline", () => {
+ health.isOnline = false;
+ const signIn = vi.fn();
+ renderButton(signIn);
+
+ const button = screen.getByTestId("run");
+ expect(button).toBeEnabled();
+ fireEvent.click(button);
+ expect(signIn).toHaveBeenCalledOnce();
+ });
+
+ it("blocks running the tool while the backend is offline", () => {
+ health.isOnline = false;
+ render(
+ <MantineProvider>
+ <OperationButton
+ onClick={vi.fn()}
+ submitText="Convert"
+ data-testid="run"
+ />
+ </MantineProvider>,
+ );
+
+ expect(screen.getByTestId("run")).toBeDisabled();
+ });
+});
diff --git a/frontend/src/editor/core/components/tools/shared/OperationButton.tsx b/frontend/src/editor/core/components/tools/shared/OperationButton.tsx
index 9fc46a1ebb..69735e4aed 100644
--- a/frontend/src/editor/core/components/tools/shared/OperationButton.tsx
+++ b/frontend/src/editor/core/components/tools/shared/OperationButton.tsx
@@ -6,6 +6,7 @@ import {
type ButtonAccent,
} from "@editor/ui/Button";
import { Tooltip } from "@editor/components/shared/Tooltip";
+import { Icon } from "@editor/ui/Icon";
import { useBackendHealth } from "@editor/hooks/useBackendHealth";
import { CloudBadge } from "@editor/components/shared/CloudBadge";
import type { ExecuteDisabledReason } from "@editor/hooks/tools/shared/toolOperationTypes";
@@ -74,15 +75,10 @@ const OperationButton = ({
const combinedDisabled = effectiveDisabled || blockedByBackend;
const reasonTooltip: Record<NonNullable<ExecuteDisabledReason>, string> = {
- endpointUnavailable: onEndpointUnavailableClick
- ? t(
- "tool.endpointUnavailableClickable",
- "Not available in this mode. Click to sign in.",
- )
- : t(
- "tool.endpointUnavailable",
- "This tool is unavailable on your server.",
- ),
+ endpointUnavailable: t(
+ "tool.endpointUnavailable",
+ "This tool is unavailable on your server.",
+ ),
filesLoading: t(
"tool.filesLoading",
"Files are still loading, please wait.",
@@ -102,6 +98,34 @@ const OperationButton = ({
? (reasonTooltip[disabledReason] ?? null)
: null;
+ if (disabledReason === "endpointUnavailable" && onEndpointUnavailableClick) {
+ return (
+ <Tooltip
+ content={t(
+ "tool.signInRequired",
+ "This needs a Stirling account. Sign in to continue.",
+ )}
+ position="top"
+ arrow
+ >
+ <Box mx="md" mt={mt} data-testid="sign-in-required">
+ <Button
+ type="button"
+ fullWidth
+ variant="primary"
+ leftSection={<Icon name="log-in" size="1rem" />}
+ onClick={onEndpointUnavailableClick}
+ data-testid={dataTestId}
+ data-tour={dataTour}
+ style={{ minHeight: "2.5rem", height: "auto" }}
+ >
+ {t("tool.signInToUse", "Sign in to use")}
+ </Button>
+ </Box>
+ </Tooltip>
+ );
+ }
+
const sharedVariant: ButtonVariant =
operationButtonVariantMap[variant] ?? "primary";
const sharedAccent: ButtonAccent =
@@ -141,24 +165,9 @@ const OperationButton = ({
if (tooltipLabel) {
// Disabled buttons suppress pointer events at the browser level, so the Tooltip's
// cloneElement handlers would never fire. Wrap in a Box to capture them instead.
- // When endpointUnavailable and a click handler is provided (desktop), the Box
- // also acts as the click target to open the sign-in / connect modal.
- const boxClickHandler =
- disabledReason === "endpointUnavailable"
- ? onEndpointUnavailableClick
- : undefined;
return (
<Tooltip content={tooltipLabel} position="top" arrow>
- <Box
- mr="md"
- ml="md"
- mt={mt}
- style={{
- display: "block",
- cursor: boxClickHandler ? "pointer" : undefined,
- }}
- onClick={boxClickHandler}
- >
+ <Box mr="md" ml="md" mt={mt} style={{ display: "block" }}>
{button}
</Box>
</Tooltip>
diff --git a/frontend/src/editor/core/contexts/ToolActionsContext.tsx b/frontend/src/editor/core/contexts/ToolActionsContext.tsx
index 8a2e6e5356..e0e085ca30 100644
--- a/frontend/src/editor/core/contexts/ToolActionsContext.tsx
+++ b/frontend/src/editor/core/contexts/ToolActionsContext.tsx
@@ -2,9 +2,9 @@ import { createContext, useContext } from "react";
interface ToolActionsContextValue {
/**
- * Called when the user clicks the disabled execute button while the reason
- * is 'endpointUnavailable'. Desktop provides a sign-in modal dispatch;
- * web builds leave this undefined (button stays disabled with tooltip only).
+ * Set only where signing in would unlock unavailable tools (desktop while
+ * signed out). When set, an 'endpointUnavailable' execute button becomes a
+ * sign-in prompt that calls this; otherwise it stays disabled.
*/
onEndpointUnavailableClick?: () => void;
}
diff --git a/frontend/src/editor/desktop/api/endpointAvailability.ts b/frontend/src/editor/desktop/api/endpointAvailability.ts
index 910546a328..aacdb9716d 100644
--- a/frontend/src/editor/desktop/api/endpointAvailability.ts
+++ b/frontend/src/editor/desktop/api/endpointAvailability.ts
@@ -8,6 +8,7 @@ import { tauriBackendService } from "@editor/services/tauriBackendService";
import { selfHostedServerMonitor } from "@editor/services/selfHostedServerMonitor";
import { endpointAvailabilityService } from "@editor/services/endpointAvailabilityService";
import { connectionModeService } from "@editor/services/connectionModeService";
+import { requiresSignIn } from "@editor/services/signInRequiredEndpoints";
import {
createBackendNotReadyError,
isBackendNotReadyError,
@@ -129,6 +130,18 @@ async function resolveOffline(
*/
export async function resolveEndpointsAvailability(
endpoints: string[],
+): Promise<EndpointAvailabilityMap> {
+ const map = await resolveForEnvironment(endpoints);
+ if ((await connectionModeService.getCurrentMode()) !== "local") return map;
+ for (const endpoint of endpoints) {
+ if (requiresSignIn(endpoint))
+ map[endpoint] = { enabled: false, reason: "NOT_SUPPORTED_LOCALLY" };
+ }
+ return map;
+}
+
+async function resolveForEnvironment(
+ endpoints: string[],
): Promise<EndpointAvailabilityMap> {
if (await isLocalProcessingOnly()) {
const map = await resolveOffline(endpoints);
@@ -164,6 +177,11 @@ export async function resolveEndpointsAvailability(
export async function resolveEndpointEnabled(
endpoint: string,
): Promise<boolean> {
+ if (
+ requiresSignIn(endpoint) &&
+ (await connectionModeService.getCurrentMode()) === "local"
+ )
+ return false;
if (await isLocalProcessingOnly())
return (await resolveEndpointsAvailability([endpoint]))[endpoint].enabled;
if (isSelfHostedOffline()) {
diff --git a/frontend/src/editor/desktop/components/AppProviders.test.tsx b/frontend/src/editor/desktop/components/AppProviders.test.tsx
index fd0b89b703..5fab8a2844 100644
--- a/frontend/src/editor/desktop/components/AppProviders.test.tsx
+++ b/frontend/src/editor/desktop/components/AppProviders.test.tsx
@@ -44,7 +44,7 @@ vi.mock("@editor/services/selfHostedServerMonitor", () => ({
selfHostedServerMonitor: { stop: vi.fn() },
}));
vi.mock("@editor/services/endpointAvailabilityService", () => ({
- endpointAvailabilityService: { preloadEndpoints: state.preload },
+ endpointAvailabilityService: { preloadLocalCapabilities: state.preload },
}));
vi.mock("@editor/hooks/useFirstLaunchCheck", () => ({
useFirstLaunchCheck: () => state.launch,
@@ -133,10 +133,7 @@ it("initializes backend monitoring and endpoint preload after a gate retry recov
fireEvent.click(screen.getByRole("button", { name: "common.retry" }));
await screen.findByText("Required sign-in");
await waitFor(() => expect(state.monitor).toHaveBeenCalledWith(true));
- expect(state.preload).toHaveBeenCalledWith(
- expect.any(Array),
- "http://localhost:8080",
- );
+ expect(state.preload).toHaveBeenCalledWith("http://localhost:8080");
expect(screen.queryByText("Workbench")).toBeNull();
});
diff --git a/frontend/src/editor/desktop/components/AppProviders.tsx b/frontend/src/editor/desktop/components/AppProviders.tsx
index d941a54e57..e868b0d250 100644
--- a/frontend/src/editor/desktop/components/AppProviders.tsx
+++ b/frontend/src/editor/desktop/components/AppProviders.tsx
@@ -33,25 +33,17 @@ import UpdateModal from "@editor-core/components/shared/UpdateModal";
import { useDesktopUpdatePopup } from "@editor/hooks/useDesktopUpdatePopup";
import { useLocalProcessingOnly } from "@editor/hooks/useLocalProcessingOnly";
-// Common tool endpoints to preload for faster first-use
-const COMMON_TOOL_ENDPOINTS = [
- "/api/v1/misc/compress-pdf",
- "/api/v1/general/merge-pdfs",
- "/api/v1/general/split-pages",
- "/api/v1/convert/pdf/img",
- "/api/v1/convert/img/pdf",
- "/api/v1/general/rotate-pdf",
- "/api/v1/misc/add-watermark",
- "/api/v1/security/add-password",
- "/api/v1/security/remove-password",
- "/api/v1/general/extract-pages",
-];
-
/**
* Desktop application providers
* Wraps proprietary providers and adds desktop-specific configuration
* - Shows setup wizard on first launch
*/
+const signInActions = {
+ onEndpointUnavailableClick: () =>
+ window.dispatchEvent(new CustomEvent(OPEN_SIGN_IN_EVENT)),
+};
+const NO_TOOL_ACTIONS = {};
+
export function AppProviders({ children }: { children: ReactNode }) {
const localOnly = useLocalProcessingOnly();
const { isFirstLaunch, setupComplete } = useFirstLaunchCheck();
@@ -260,13 +252,8 @@ export function AppProviders({ children }: { children: ReactNode }) {
// tauriBackendService.isOnline now always reflects the local backend.
// Wait for it to be healthy before preloading in both modes.
if (!tauriBackendService.isOnline) return;
- console.debug(
- "[AppProviders] Preloading common tool endpoints for local backend",
- );
- void endpointAvailabilityService.preloadEndpoints(
- COMMON_TOOL_ENDPOINTS,
- backendUrl,
- );
+ console.debug("[AppProviders] Preloading local backend capabilities");
+ endpointAvailabilityService.preloadLocalCapabilities(backendUrl);
};
const unsubscribe = tauriBackendService.subscribeToStatus(() =>
@@ -356,10 +343,7 @@ export function AppProviders({ children }: { children: ReactNode }) {
return (
<ProprietaryAppProviders>
<ToolActionsContext.Provider
- value={{
- onEndpointUnavailableClick: () =>
- window.dispatchEvent(new CustomEvent(OPEN_SIGN_IN_EVENT)),
- }}
+ value={connectionMode === "local" ? signInActions : NO_TOOL_ACTIONS}
>
<DesktopQueryCacheReset />
<DesktopAccessGate onConfigLoaded={initializeConnectionMode}>
diff --git a/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx b/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx
index 5c6d52eb2a..f867d799fd 100644
--- a/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx
+++ b/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx
@@ -3,8 +3,13 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { MantineProvider } from "@mantine/core";
import ConvertSettings from "@editor/components/tools/convert/ConvertSettings";
import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";
+import { ToolActionsContext } from "@editor/contexts/ToolActionsContext";
-const state = vi.hoisted(() => ({ localOnly: true }));
+const state = vi.hoisted(() => ({
+ localOnly: true,
+ signedOut: false,
+ signInEndpoints: ["pdf-to-word"],
+}));
vi.mock("@editor/hooks/useOfficeConversionDefault", () => ({
useOfficeConversionDefault: () => false,
}));
@@ -23,6 +28,14 @@ vi.mock("@editor/hooks/useEndpointConfig", () => ({
"pdf-to-word": false,
"file-to-pdf": false,
},
+ endpointDetails: state.signedOut
+ ? Object.fromEntries(
+ state.signInEndpoints.map((endpoint) => [
+ endpoint,
+ { enabled: false, reason: "NOT_SUPPORTED_LOCALLY" },
+ ]),
+ )
+ : {},
}),
}));
vi.mock("@editor/hooks/useConversionCloudStatus", () => ({
@@ -36,15 +49,22 @@ vi.mock("@editor/ui/Icon", () => ({ Icon: () => null }));
beforeEach(() => {
state.localOnly = true;
+ state.signedOut = false;
+ state.signInEndpoints = ["pdf-to-word"];
});
-function renderSettings() {
+function renderSettings(
+ onEndpointUnavailableClick?: () => void,
+ fromExtension = "pdf",
+) {
return render(
<MantineProvider>
- <ConvertSettings
- parameters={{ ...defaultParameters, fromExtension: "pdf" }}
- onParameterChange={vi.fn()}
- />
+ <ToolActionsContext.Provider value={{ onEndpointUnavailableClick }}>
+ <ConvertSettings
+ parameters={{ ...defaultParameters, fromExtension }}
+ onParameterChange={vi.fn()}
+ />
+ </ToolActionsContext.Provider>
</MantineProvider>,
);
}
@@ -71,3 +91,46 @@ it("keeps disabled formats visible when privacy and the hiding preference are of
expect(await screen.findByTestId("format-option-docx")).toBeDisabled();
expect(screen.getByTestId("format-option-png")).toBeEnabled();
});
+
+it("offers formats that need sign-in instead of greying them out", async () => {
+ state.localOnly = false;
+ state.signedOut = true;
+ renderSettings(vi.fn());
+ fireEvent.click(screen.getByTestId("convert-to-dropdown"));
+ const word = await screen.findByTestId("format-option-docx");
+ expect(word).toBeEnabled();
+ expect(word).toHaveAttribute("title", "convert.signInToUse");
+});
+
+it("keeps sign-in formats unavailable under privacy", async () => {
+ state.signedOut = true;
+ renderSettings(vi.fn());
+ fireEvent.click(screen.getByTestId("convert-to-dropdown"));
+ await screen.findByTestId("format-option-png");
+ expect(screen.queryByTestId("format-option-docx")).toBeNull();
+});
+
+it("offers PDF for a dynamic file source that needs sign-in", async () => {
+ state.localOnly = false;
+ state.signedOut = true;
+ state.signInEndpoints = ["file-to-pdf"];
+ renderSettings(vi.fn(), "file-docm");
+ fireEvent.click(screen.getByTestId("convert-to-dropdown"));
+ const pdf = await screen.findByTestId("format-option-pdf");
+ expect(pdf).toBeEnabled();
+ expect(pdf).toHaveAttribute("title", "convert.signInToUse");
+});
+
+it("locks source formats reachable only by signing in", async () => {
+ state.localOnly = false;
+ state.signedOut = true;
+ state.signInEndpoints = ["file-to-pdf"];
+ renderSettings(vi.fn());
+ fireEvent.click(screen.getByTestId("convert-from-dropdown"));
+ const docx = await screen.findByTestId("format-option-docx");
+ expect(docx).toBeEnabled();
+ expect(docx).toHaveAttribute("title", "convert.signInToUse");
+ const pdf = screen.getByTestId("format-option-pdf");
+ expect(pdf).toBeEnabled();
+ expect(pdf).not.toHaveAttribute("title");
+});
diff --git a/frontend/src/editor/desktop/hooks/useConversionCloudStatus.test.ts b/frontend/src/editor/desktop/hooks/useConversionCloudStatus.test.ts
new file mode 100644
index 0000000000..557295b281
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useConversionCloudStatus.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { useConversionCloudStatus } from "@editor/hooks/useConversionCloudStatus";
+
+const probe = vi.hoisted(() => ({ hang: false }));
+const mode = vi.hoisted(() => ({
+ current: "local" as "local" | "saas" | "selfhosted",
+ listeners: new Set<() => void>(),
+}));
+
+vi.mock("@editor/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCurrentMode: async () => mode.current,
+ subscribeToModeChanges: (listener: () => void) => {
+ mode.listeners.add(listener);
+ return () => mode.listeners.delete(listener);
+ },
+ },
+}));
+vi.mock("@editor/services/endpointAvailabilityService", () => ({
+ endpointAvailabilityService: {
+ isEndpointSupportedLocally: (endpoint: string) =>
+ probe.hang
+ ? new Promise<boolean>(() => {})
+ : Promise.resolve(endpoint !== "pdf-to-word"),
+ },
+}));
+vi.mock("@editor/services/tauriBackendService", () => ({
+ tauriBackendService: {
+ isOnline: true,
+ getBackendUrl: () => "http://localhost:8080",
+ subscribeToStatus: () => () => {},
+ },
+}));
+vi.mock("@editor/services/selfHostedServerMonitor", () => ({
+ selfHostedServerMonitor: {
+ getSnapshot: () => ({ status: "idle" }),
+ subscribe: () => () => {},
+ },
+}));
+vi.mock("@editor/hooks/useLocalProcessingOnly", () => ({
+ useLocalProcessingOnly: () => false,
+}));
+vi.mock("@editor/hooks/useEndpointConfig", () => ({
+ useMultipleEndpointsEnabled: () => ({ endpointStatus: {} }),
+}));
+
+describe("useConversionCloudStatus", () => {
+ it("re-checks conversions when signing in switches the connection mode", async () => {
+ probe.hang = false;
+ mode.current = "local";
+ const { result } = renderHook(() => useConversionCloudStatus());
+
+ await waitFor(() => expect(result.current.availability).toEqual({}));
+
+ mode.current = "saas";
+ act(() => mode.listeners.forEach((listener) => listener()));
+
+ await waitFor(() =>
+ expect(result.current.cloudStatus["pdf-docx"]).toBe(true),
+ );
+ expect(result.current.availability["pdf-docx"]).toBe(true);
+ });
+
+ it("reports SaaS conversions as available before the local probes answer", async () => {
+ probe.hang = true;
+ mode.current = "saas";
+ const { result } = renderHook(() => useConversionCloudStatus());
+
+ await waitFor(() =>
+ expect(result.current.availability["pdf-docx"]).toBe(true),
+ );
+ expect(Object.values(result.current.availability).every(Boolean)).toBe(
+ true,
+ );
+ });
+});
diff --git a/frontend/src/editor/desktop/hooks/useConversionCloudStatus.ts b/frontend/src/editor/desktop/hooks/useConversionCloudStatus.ts
index a51e242a3b..b8ebafaf16 100644
--- a/frontend/src/editor/desktop/hooks/useConversionCloudStatus.ts
+++ b/frontend/src/editor/desktop/hooks/useConversionCloudStatus.ts
@@ -53,7 +53,7 @@ export function useConversionCloudStatus(): ConversionStatus {
}
return { availability, cloudStatus, localOnly };
}, [endpointStatus, localProcessingOnly]);
- const [status, setStatus] = useState<ConversionStatus>({
+ const [status, setLatestStatus] = useState<ConversionStatus>({
availability: Object.fromEntries(
Object.entries(EXTENSION_TO_ENDPOINT).flatMap(([from, targets]) =>
Object.keys(targets).map((to) => [`${from}-${to}`, false]),
@@ -65,7 +65,12 @@ export function useConversionCloudStatus(): ConversionStatus {
useEffect(() => {
if (localProcessingOnly) return;
+ let latestCheck = 0;
const checkConversions = async () => {
+ const check = ++latestCheck;
+ const setStatus = (next: ConversionStatus) => {
+ if (check === latestCheck) setLatestStatus(next);
+ };
const mode = await connectionModeService.getCurrentMode();
// Self-hosted offline path: server is down but local backend is available.
@@ -139,6 +144,14 @@ export function useConversionCloudStatus(): ConversionStatus {
}
}
+ setStatus({
+ availability: Object.fromEntries(
+ pairs.map(([fromExt, toExt]) => [`${fromExt}-${toExt}`, true]),
+ ),
+ cloudStatus: {},
+ localOnly: {},
+ });
+
const results = await Promise.all(
pairs.map(async ([fromExt, toExt, endpointName]) => {
const key = `${fromExt}-${toExt}`;
@@ -212,9 +225,15 @@ export function useConversionCloudStatus(): ConversionStatus {
void checkConversions();
});
+ const unsubMode = connectionModeService.subscribeToModeChanges(() => {
+ void checkConversions();
+ });
+
return () => {
+ latestCheck = -1;
unsubLocal();
unsubServer();
+ unsubMode();
};
}, [localProcessingOnly]);
diff --git a/frontend/src/editor/desktop/hooks/useEndpointConfig.test.tsx b/frontend/src/editor/desktop/hooks/useEndpointConfig.test.tsx
index 0c7a1c394a..f81377f613 100644
--- a/frontend/src/editor/desktop/hooks/useEndpointConfig.test.tsx
+++ b/frontend/src/editor/desktop/hooks/useEndpointConfig.test.tsx
@@ -253,6 +253,37 @@ describe("desktop useMultipleEndpointsEnabled", () => {
expect(result.current.endpointStatus.ocr).toBe(true);
});
+ it.each(["local", "saas"] as const)(
+ "gates Office Convert endpoints on sign-in in %s mode",
+ async (current) => {
+ mode = current;
+ mockGet.mockImplementation((url: string) => {
+ if (url.includes("app-config")) return Promise.resolve(appConfig(true));
+ return Promise.resolve(
+ availability({
+ "file-to-pdf": { enabled: true },
+ "pdf-to-word": { enabled: true },
+ merge: { enabled: true },
+ }),
+ );
+ });
+
+ const { result } = renderHook(
+ () =>
+ useMultipleEndpointsEnabled(["file-to-pdf", "pdf-to-word", "merge"]),
+ { wrapper: TestQueryProvider },
+ );
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ const signedIn = current !== "local";
+ expect(result.current.endpointStatus).toEqual({
+ "file-to-pdf": signedIn,
+ "pdf-to-word": signedIn,
+ merge: true,
+ });
+ },
+ );
+
it("fails closed for un-fetchable endpoints outside SaaS mode", async () => {
mode = "local";
mockGet.mockImplementation((url: string) => {
diff --git a/frontend/src/editor/desktop/hooks/useToolCloudStatus.ts b/frontend/src/editor/desktop/hooks/useToolCloudStatus.ts
index 2bb78cf302..cd87bc0931 100644
--- a/frontend/src/editor/desktop/hooks/useToolCloudStatus.ts
+++ b/frontend/src/editor/desktop/hooks/useToolCloudStatus.ts
@@ -35,25 +35,11 @@ export function useToolCloudStatus(endpointName?: string): boolean {
return;
}
- // Check if supported on SaaS first (if not, no point showing cloud badge)
- const supportedOnSaaS =
- await endpointAvailabilityService.isEndpointSupportedOnSaaS(
- endpointName,
- );
-
- if (!supportedOnSaaS) {
- // Not available on SaaS, don't show cloud badge
- setUsesCloud(false);
- return;
- }
-
- // Available on SaaS, check if also available locally
const supportedLocally =
await endpointAvailabilityService.isEndpointSupportedLocally(
endpointName,
tauriBackendService.getBackendUrl(),
);
- // Show cloud badge only if SaaS supports it but local doesn't
setUsesCloud(!supportedLocally);
} catch {
setUsesCloud(false);
diff --git a/frontend/src/editor/desktop/services/connectionModeService.test.ts b/frontend/src/editor/desktop/services/connectionModeService.test.ts
index f54f00d00a..49f1442059 100644
--- a/frontend/src/editor/desktop/services/connectionModeService.test.ts
+++ b/frontend/src/editor/desktop/services/connectionModeService.test.ts
@@ -7,9 +7,6 @@ import {
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/core", () => ({ invoke, isTauri: () => true }));
vi.mock("@tauri-apps/plugin-http", () => ({ fetch: vi.fn() }));
-vi.mock("@editor/services/endpointAvailabilityService", () => ({
- endpointAvailabilityService: { clearCache: vi.fn() },
-}));
vi.mock("@editor/services/selfHostedServerMonitor", () => ({
selfHostedServerMonitor: { start: vi.fn() },
}));
diff --git a/frontend/src/editor/desktop/services/connectionModeService.ts b/frontend/src/editor/desktop/services/connectionModeService.ts
index 5ca3b651e0..5b7109d9de 100644
--- a/frontend/src/editor/desktop/services/connectionModeService.ts
+++ b/frontend/src/editor/desktop/services/connectionModeService.ts
@@ -1,7 +1,6 @@
import { invoke, isTauri } from "@tauri-apps/api/core";
import i18n from "i18next";
import { fetch } from "@tauri-apps/plugin-http";
-import { endpointAvailabilityService } from "@editor/services/endpointAvailabilityService";
import { selfHostedServerMonitor } from "@editor/services/selfHostedServerMonitor";
export type ConnectionMode = "saas" | "selfhosted" | "local";
@@ -183,12 +182,6 @@ export class ConnectionModeService {
lock_connection_mode: this.currentConfig?.lock_connection_mode ?? false,
};
- // Clear endpoint availability cache when mode changes
- endpointAvailabilityService.clearCache();
- console.log(
- "Cleared endpoint availability cache due to connection mode change",
- );
-
this.notifyListeners();
// Re-dispatch `jwt-available` so the proprietary AuthProvider re-runs
@@ -246,9 +239,6 @@ export class ConnectionModeService {
lock_connection_mode: isLocked,
};
- // Clear endpoint availability cache when mode changes
- endpointAvailabilityService.clearCache();
-
this.notifyListeners();
}
@@ -274,12 +264,6 @@ export class ConnectionModeService {
lock_connection_mode: this.currentConfig?.lock_connection_mode ?? false,
};
- // Clear endpoint availability cache when mode changes
- endpointAvailabilityService.clearCache();
- console.log(
- "Cleared endpoint availability cache due to connection mode change",
- );
-
// Single authoritative calling point for health monitoring — every path that
// switches to self-hosted mode funnels through here.
selfHostedServerMonitor.start(serverConfig.url);
diff --git a/frontend/src/editor/desktop/services/endpointAvailabilityService.test.ts b/frontend/src/editor/desktop/services/endpointAvailabilityService.test.ts
new file mode 100644
index 0000000000..20d501d1f1
--- /dev/null
+++ b/frontend/src/editor/desktop/services/endpointAvailabilityService.test.ts
@@ -0,0 +1,128 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fetch } from "@tauri-apps/plugin-http";
+import { EndpointAvailabilityService } from "@editor/services/endpointAvailabilityService";
+import { expectConsole } from "@editor/tests/failOnConsole";
+
+const backend = vi.hoisted(() => ({ isOnline: true }));
+
+vi.mock("@tauri-apps/plugin-http", () => ({ fetch: vi.fn() }));
+vi.mock("@editor/services/tauriBackendService", () => ({
+ tauriBackendService: backend,
+}));
+
+const capabilities = {
+ "file-to-pdf": { enabled: true, reason: null },
+ "pdf-to-word": { enabled: false, reason: "MISSING_DEPENDENCY" },
+};
+
+function respondWith(body: unknown, ok = true) {
+ vi.mocked(fetch).mockResolvedValue({
+ ok,
+ status: ok ? 200 : 503,
+ json: async () => body,
+ } as Response);
+}
+
+describe("EndpointAvailabilityService", () => {
+ beforeEach(() => {
+ vi.mocked(fetch).mockReset();
+ backend.isOnline = true;
+ });
+
+ it("answers every concurrent check from one request", async () => {
+ respondWith(capabilities);
+ const service = new EndpointAvailabilityService();
+
+ const answers = await Promise.all([
+ service.isEndpointSupportedLocally("file-to-pdf", "http://127.0.0.1:1"),
+ service.isEndpointSupportedLocally("file-to-pdf", "http://127.0.0.1:1"),
+ service.isEndpointSupportedLocally("pdf-to-word", "http://127.0.0.1:1"),
+ service.isEndpointSupportedLocally("unknown", "http://127.0.0.1:1"),
+ ]);
+
+ expect(answers).toEqual([true, true, false, false]);
+ expect(fetch).toHaveBeenCalledOnce();
+ expect(vi.mocked(fetch).mock.calls[0][0]).toBe(
+ "http://127.0.0.1:1/api/v1/config/endpoints-availability",
+ );
+ });
+
+ it("reuses the map for later checks against the same backend", async () => {
+ respondWith(capabilities);
+ const service = new EndpointAvailabilityService();
+
+ await service.isEndpointSupportedLocally(
+ "file-to-pdf",
+ "http://127.0.0.1:1",
+ );
+ await service.isEndpointSupportedLocally(
+ "pdf-to-word",
+ "http://127.0.0.1:1",
+ );
+
+ expect(fetch).toHaveBeenCalledOnce();
+ });
+
+ it("fetches again for a restarted backend on a new port", async () => {
+ respondWith(capabilities);
+ const service = new EndpointAvailabilityService();
+
+ await service.isEndpointSupportedLocally(
+ "file-to-pdf",
+ "http://127.0.0.1:1",
+ );
+ await service.isEndpointSupportedLocally(
+ "file-to-pdf",
+ "http://127.0.0.1:2",
+ );
+
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not keep a failed check", async () => {
+ expectConsole.error(/Local capability check failed: 503/);
+ respondWith({}, false);
+ const service = new EndpointAvailabilityService();
+
+ await expect(
+ service.isEndpointSupportedLocally("file-to-pdf", "http://127.0.0.1:1"),
+ ).resolves.toBe(false);
+
+ respondWith(capabilities);
+ await expect(
+ service.isEndpointSupportedLocally("file-to-pdf", "http://127.0.0.1:1"),
+ ).resolves.toBe(true);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("reports nothing local before the backend has a URL", async () => {
+ const service = new EndpointAvailabilityService();
+
+ await expect(
+ service.isEndpointSupportedLocally("file-to-pdf", null),
+ ).resolves.toBe(false);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("does not keep a map read before the backend's dependencies are ready", async () => {
+ backend.isOnline = false;
+ respondWith(capabilities);
+ const service = new EndpointAvailabilityService();
+
+ await service.isEndpointSupportedLocally(
+ "file-to-pdf",
+ "http://127.0.0.1:1",
+ );
+ backend.isOnline = true;
+ await service.isEndpointSupportedLocally(
+ "file-to-pdf",
+ "http://127.0.0.1:1",
+ );
+ await service.isEndpointSupportedLocally(
+ "file-to-pdf",
+ "http://127.0.0.1:1",
+ );
+
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/src/editor/desktop/services/endpointAvailabilityService.ts b/frontend/src/editor/desktop/services/endpointAvailabilityService.ts
index 386704aba8..08340ab123 100644
--- a/frontend/src/editor/desktop/services/endpointAvailabilityService.ts
+++ b/frontend/src/editor/desktop/services/endpointAvailabilityService.ts
@@ -1,320 +1,86 @@
import { fetch } from "@tauri-apps/plugin-http";
-import { STIRLING_SAAS_BACKEND_API_URL } from "@editor/constants/connection";
+import { tauriBackendService } from "@editor/services/tauriBackendService";
-/**
- * Service for checking endpoint availability on the local bundled backend.
- * Used by operation router to determine if a tool should be routed to SaaS backend.
- *
- * Caches results to avoid repeated checks for the same endpoint.
- */
-export class EndpointAvailabilityService {
- private localCache: Map<string, boolean> = new Map();
- private localCacheExpiry: Map<string, number> = new Map();
- private saasCache: Map<string, boolean> = new Map();
- private saasCacheExpiry: Map<string, number> = new Map();
- private readonly CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
-
- /**
- * Check if local backend supports an endpoint
- * Returns cached result if available, otherwise fetches from backend
- *
- * @param endpoint - The endpoint path to check (e.g., "/api/v1/misc/compress-pdf")
- * @param backendUrl - The URL for the backend
- * @returns Promise<boolean> - true if supported locally, false otherwise
- */
- async isEndpointSupportedLocally(
- endpoint: string,
- backendUrl: string | null,
- ): Promise<boolean> {
- // Check cache first
- const cached = this.localCache.get(endpoint);
- const expiry = this.localCacheExpiry.get(endpoint);
-
- if (cached !== undefined && expiry && Date.now() < expiry) {
- return cached;
- }
+type CapabilityMap = Record<string, boolean>;
- // Fetch from backend
- try {
- if (!backendUrl) {
- // Backend not started yet - assume not supported (will route to SaaS)
- return false;
- }
-
- const url = `${backendUrl}/api/v1/config/endpoints-availability?endpoints=${encodeURIComponent(endpoint)}`;
-
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Cache-Control": "no-store",
- },
- });
-
- if (!response.ok) {
- console.warn(
- `[endpointAvailabilityService] Failed to check local endpoint availability: ${response.status}`,
- );
- return false;
- }
-
- const data = await response.json();
- const available = data[endpoint]?.enabled ?? false;
-
- // Cache the result
- this.localCache.set(endpoint, available);
- this.localCacheExpiry.set(endpoint, Date.now() + this.CACHE_DURATION);
+interface CapabilityEntry {
+ backendUrl: string;
+ expiresAt: number;
+ capabilities: Promise<CapabilityMap>;
+}
- return available;
- } catch (error) {
- console.error(
- `[endpointAvailabilityService] Error checking local endpoint availability:`,
- error,
- );
- return false; // Assume not supported on error
- }
+async function fetchLocalCapabilities(
+ backendUrl: string,
+): Promise<CapabilityMap> {
+ const response = await fetch(
+ `${backendUrl.replace(/\/$/, "")}/api/v1/config/endpoints-availability`,
+ { method: "GET", headers: { "Cache-Control": "no-store" } },
+ );
+ if (!response.ok) {
+ throw new Error(`Local capability check failed: ${response.status}`);
}
-
- /**
- * Check if SaaS backend supports an endpoint
- * Returns cached result if available, otherwise fetches from SaaS backend
- *
- * @param endpoint - The endpoint path to check (e.g., "/api/v1/misc/compress-pdf")
- * @returns Promise<boolean> - true if supported on SaaS, false otherwise
- */
- async isEndpointSupportedOnSaaS(endpoint: string): Promise<boolean> {
- // Check cache first
- const cached = this.saasCache.get(endpoint);
- const expiry = this.saasCacheExpiry.get(endpoint);
-
- if (cached !== undefined && expiry && Date.now() < expiry) {
- return cached;
- }
-
- // Fetch from SaaS backend
- try {
- if (!STIRLING_SAAS_BACKEND_API_URL) {
- return false;
- }
-
- const saasUrl = STIRLING_SAAS_BACKEND_API_URL.replace(/\/$/, "");
- const url = `${saasUrl}/api/v1/config/endpoints-availability?endpoints=${encodeURIComponent(endpoint)}`;
-
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Cache-Control": "no-store",
- },
- });
-
- if (!response.ok) {
- console.warn(
- `[endpointAvailabilityService] Failed to check SaaS endpoint availability: ${response.status}`,
- );
- return false;
- }
-
- const data = await response.json();
- const available = data[endpoint]?.enabled ?? false;
-
- // Cache the result
- this.saasCache.set(endpoint, available);
- this.saasCacheExpiry.set(endpoint, Date.now() + this.CACHE_DURATION);
-
- return available;
- } catch (error) {
- console.error(
- `[endpointAvailabilityService] Error checking SaaS endpoint availability:`,
- error,
- );
- return false; // Assume not supported on error
- }
- }
-
- /**
- * Clear cache (useful when backend restarts or connection mode changes)
- */
- clearCache() {
- this.localCache.clear();
- this.localCacheExpiry.clear();
- this.saasCache.clear();
- this.saasCacheExpiry.clear();
+ const data = (await response.json()) as Record<
+ string,
+ { enabled?: boolean } | null
+ >;
+ const capabilities: CapabilityMap = {};
+ for (const [endpoint, details] of Object.entries(data)) {
+ capabilities[endpoint] = details?.enabled ?? false;
}
+ return capabilities;
+}
- /**
- * Debug: Log all cached endpoint availability
- * Call from console: window.endpointAvailabilityService.debugCache()
- */
- debugCache() {
- console.group("[endpointAvailabilityService] Cache Debug");
-
- console.group("Local Cache");
- this.localCache.forEach((available, endpoint) => {
- const expiry = this.localCacheExpiry.get(endpoint);
- const expiresIn = expiry ? Math.max(0, expiry - Date.now()) : 0;
- console.log(
- `${endpoint}: ${available} (expires in ${Math.round(expiresIn / 1000)}s)`,
- );
- });
- console.groupEnd();
+export class EndpointAvailabilityService {
+ private local: CapabilityEntry | null = null;
+ private readonly CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
- console.group("SaaS Cache");
- this.saasCache.forEach((available, endpoint) => {
- const expiry = this.saasCacheExpiry.get(endpoint);
- const expiresIn = expiry ? Math.max(0, expiry - Date.now()) : 0;
- console.log(
- `${endpoint}: ${available} (expires in ${Math.round(expiresIn / 1000)}s)`,
- );
+ private localCapabilities(backendUrl: string): Promise<CapabilityMap> {
+ const now = Date.now();
+ if (
+ this.local &&
+ this.local.backendUrl === backendUrl &&
+ now < this.local.expiresAt
+ ) {
+ return this.local.capabilities;
+ }
+ const capabilities = fetchLocalCapabilities(backendUrl);
+ if (!tauriBackendService.isOnline) return capabilities;
+ const entry: CapabilityEntry = {
+ backendUrl,
+ expiresAt: now + this.CACHE_DURATION,
+ capabilities,
+ };
+ this.local = entry;
+ entry.capabilities.catch(() => {
+ if (this.local === entry) this.local = null;
});
- console.groupEnd();
-
- console.groupEnd();
+ return entry.capabilities;
}
- /**
- * Preload availability for multiple endpoints
- * Optimizes batch checking for tool initialization
- *
- * @param endpoints - Array of endpoint paths to check
- * @param backendUrl - The URL of the backend
- */
- async preloadEndpoints(
- endpoints: string[],
+ async isEndpointSupportedLocally(
+ endpoint: string,
backendUrl: string | null,
- ): Promise<void> {
- if (!backendUrl || endpoints.length === 0) {
- return;
- }
-
+ ): Promise<boolean> {
+ if (!backendUrl) return false;
try {
- const endpointsParam = endpoints.join(",");
- const url = `${backendUrl}/api/v1/config/endpoints-availability?endpoints=${encodeURIComponent(endpointsParam)}`;
-
- const response = await fetch(url, {
- method: "GET",
- headers: {
- "Cache-Control": "no-store",
- },
- });
-
- if (response.ok) {
- const data = await response.json();
- const now = Date.now();
-
- Object.entries(data).forEach(
- ([endpoint, details]: [string, unknown]) => {
- const available =
- (details as { enabled?: boolean })?.enabled ?? false;
- this.localCache.set(endpoint, available);
- this.localCacheExpiry.set(endpoint, now + this.CACHE_DURATION);
- },
- );
- } else {
- console.warn(
- `[endpointAvailabilityService] Failed to preload endpoints: ${response.status}`,
- );
- }
+ return (await this.localCapabilities(backendUrl))[endpoint] ?? false;
} catch (error) {
console.error(
- "[endpointAvailabilityService] Error preloading endpoints:",
+ "[endpointAvailabilityService] Error checking local endpoint availability:",
error,
);
+ return false;
}
}
- /**
- * Check endpoint availability across both local and SaaS backends
- * Returns comprehensive status for decision making
- *
- * @param endpoint - The endpoint path to check
- * @returns Promise with availability details
- */
- async checkEndpointCombined(
- endpoint: string,
- backendUrl: string | null,
- ): Promise<{
- availableLocally: boolean;
- availableOnSaaS: boolean;
- isAvailable: boolean; // local || saas
- willUseCloud: boolean; // saas && !local
- localOnly: boolean; // local && !saas
- }> {
- // Check both backends in parallel for efficiency
- const [availableLocally, availableOnSaaS] = await Promise.all([
- this.isEndpointSupportedLocally(endpoint, backendUrl),
- this.isEndpointSupportedOnSaaS(endpoint),
- ]);
-
- return {
- availableLocally,
- availableOnSaaS,
- isAvailable: availableLocally || availableOnSaaS,
- willUseCloud: availableOnSaaS && !availableLocally,
- localOnly: availableLocally && !availableOnSaaS,
- };
- }
-
- /**
- * Get cache statistics (useful for debugging)
- */
- getCacheStats(): {
- local: {
- size: number;
- entries: Array<{
- endpoint: string;
- available: boolean;
- expiresIn: number;
- }>;
- };
- saas: {
- size: number;
- entries: Array<{
- endpoint: string;
- available: boolean;
- expiresIn: number;
- }>;
- };
- } {
- const now = Date.now();
-
- const localEntries = Array.from(this.localCache.entries()).map(
- ([endpoint, available]) => {
- const expiry = this.localCacheExpiry.get(endpoint) ?? 0;
- return {
- endpoint,
- available,
- expiresIn: Math.max(0, expiry - now),
- };
- },
- );
-
- const saasEntries = Array.from(this.saasCache.entries()).map(
- ([endpoint, available]) => {
- const expiry = this.saasCacheExpiry.get(endpoint) ?? 0;
- return {
- endpoint,
- available,
- expiresIn: Math.max(0, expiry - now),
- };
- },
- );
-
- return {
- local: {
- size: this.localCache.size,
- entries: localEntries,
- },
- saas: {
- size: this.saasCache.size,
- entries: saasEntries,
- },
- };
+ preloadLocalCapabilities(backendUrl: string | null): void {
+ if (!backendUrl) return;
+ this.localCapabilities(backendUrl).catch(() => {});
}
}
-// Export singleton instance
export const endpointAvailabilityService = new EndpointAvailabilityService();
-// Expose to window for debugging
if (typeof window !== "undefined") {
window.endpointAvailabilityService = endpointAvailabilityService;
}
diff --git a/frontend/src/editor/desktop/services/operationRouter.test.ts b/frontend/src/editor/desktop/services/operationRouter.test.ts
index b19b4e96c4..95da304b28 100644
--- a/frontend/src/editor/desktop/services/operationRouter.test.ts
+++ b/frontend/src/editor/desktop/services/operationRouter.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
// Verifies operationRouter.getBaseUrl host selection in SaaS mode: cloud-only
// feature endpoints (payg/team/policies) must hit the SaaS backend, NOT the local
@@ -40,7 +40,6 @@ vi.mock("@editor/services/tauriBackendService", () => ({
vi.mock("@editor/services/endpointAvailabilityService", () => ({
endpointAvailabilityService: {
isEndpointSupportedLocally: vi.fn().mockResolvedValue(true),
- isEndpointSupportedOnSaaS: vi.fn().mockResolvedValue(true),
},
}));
vi.mock("@editor/services/selfHostedServerMonitor", () => ({
@@ -123,9 +122,6 @@ describe("managed local document processing", () => {
vi.mocked(
endpointAvailabilityService.isEndpointSupportedLocally,
).mockResolvedValue(true);
- vi.mocked(
- endpointAvailabilityService.isEndpointSupportedOnSaaS,
- ).mockClear();
});
test.each(["saas", "selfhosted", "local"] as const)(
"processes supported tools locally in %s mode",
@@ -134,9 +130,6 @@ describe("managed local document processing", () => {
await expect(
operationRouter.getBaseUrl("/api/v1/misc/compress-pdf"),
).resolves.toBe("http://localhost:62994");
- expect(
- endpointAvailabilityService.isEndpointSupportedOnSaaS,
- ).not.toHaveBeenCalled();
},
);
test("does not fall back to SaaS when a tool is missing locally", async () => {
@@ -146,9 +139,6 @@ describe("managed local document processing", () => {
await expect(
operationRouter.getBaseUrl("/api/v1/misc/ocr-pdf"),
).rejects.toThrow("stay on this device");
- expect(
- endpointAvailabilityService.isEndpointSupportedOnSaaS,
- ).not.toHaveBeenCalled();
await expect(
operationRouter.willRouteToSaaS("/api/v1/misc/ocr-pdf"),
).resolves.toBe(false);
@@ -226,3 +216,67 @@ describe("operationRouter — URL shared by two endpoint keys", () => {
}
});
});
+
+describe("operationRouter — Office Convert needs an account", () => {
+ const dispatchEvent = vi.fn();
+
+ beforeEach(() => {
+ vi.stubGlobal("window", { dispatchEvent });
+ dispatchEvent.mockClear();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ test.each([
+ ["/api/v1/convert/file/pdf", undefined],
+ ["/api/v1/convert/pdf/word", undefined],
+ ["/api/v1/convert/pdf/text", "pdf-to-rtf"],
+ ["/api/v1/misc/extract-image-scans", undefined],
+ ])("refuses %s (%s) in local mode and opens sign-in", async (url, key) => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("local");
+ await expect(operationRouter.getBaseUrl(url, key)).rejects.toThrow(
+ /requires an account/,
+ );
+ expect(dispatchEvent).toHaveBeenCalledTimes(1);
+ });
+
+ test("still runs free conversions locally in local mode", async () => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("local");
+ await expect(
+ operationRouter.getBaseUrl("/api/v1/convert/pdf/img"),
+ ).resolves.toBe("http://localhost:62994");
+ for (const path of [
+ "/api/v1/convert/pdf/csv",
+ "/api/v1/convert/pdf/text",
+ "/api/v1/convert/pdf/xlsx",
+ "/api/v1/convert/pdf/markdown",
+ ]) {
+ await expect(operationRouter.getBaseUrl(path)).resolves.toBe(
+ "http://localhost:62994",
+ );
+ }
+ expect(dispatchEvent).not.toHaveBeenCalled();
+ });
+
+ test("badges Office Convert tools as needing sign-in only in local mode", async () => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("local");
+ await expect(
+ operationRouter.willRouteToSaaS("/api/v1/misc/extract-image-scans"),
+ ).resolves.toBe(true);
+ await expect(
+ operationRouter.willRouteToSaaS("/api/v1/misc/compress-pdf"),
+ ).resolves.toBe(false);
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("saas");
+ await expect(
+ operationRouter.willRouteToSaaS("/api/v1/misc/extract-image-scans"),
+ ).resolves.toBe(false);
+ });
+
+ test("runs Office Convert on the bundled backend once signed in", async () => {
+ await expect(
+ operationRouter.getBaseUrl("/api/v1/convert/file/pdf"),
+ ).resolves.toBe("http://localhost:62994");
+ });
+});
diff --git a/frontend/src/editor/desktop/services/operationRouter.ts b/frontend/src/editor/desktop/services/operationRouter.ts
index cf4618656b..b4a2b49af7 100644
--- a/frontend/src/editor/desktop/services/operationRouter.ts
+++ b/frontend/src/editor/desktop/services/operationRouter.ts
@@ -12,6 +12,7 @@ import {
import { tauriBackendService } from "@editor/services/tauriBackendService";
import { endpointAvailabilityService } from "@editor/services/endpointAvailabilityService";
import { selfHostedServerMonitor } from "@editor/services/selfHostedServerMonitor";
+import { requiresSignIn } from "@editor/services/signInRequiredEndpoints";
import { STIRLING_SAAS_BACKEND_API_URL } from "@editor/constants/connection";
import {
CONVERSION_ENDPOINTS,
@@ -65,6 +66,21 @@ export class OperationRouter {
return url.replace(/\/$/, "");
}
+ private signInRequiredError(): Error {
+ // Open the connection settings so the user can sign in
+ window.dispatchEvent(
+ new CustomEvent("appConfig:navigate", {
+ detail: { key: "connectionMode" },
+ }),
+ );
+ return new Error(
+ i18n.t(
+ "localMode.toolUnavailable",
+ "This tool requires an account. Sign in to Stirling Cloud or connect to a self-hosted server to use it.",
+ ),
+ );
+ }
+
/** Standalone tools route by connection mode. Automation endpoints never reach here —
* getBaseUrl resolves those via getConnectedServerBaseUrl before this is consulted. */
async getExecutionTarget(): Promise<ExecutionTarget> {
@@ -185,6 +201,14 @@ export class OperationRouter {
* @returns Base URL for API calls
*/
async getBaseUrl(operation?: string, endpointName?: string): Promise<string> {
+ if (
+ operation &&
+ this.isToolEndpoint(operation) &&
+ requiresSignIn(this.capabilityKey(operation, endpointName)) &&
+ (await connectionModeService.getCurrentMode()) === "local"
+ ) {
+ throw this.signInRequiredError();
+ }
if (await isLocalProcessingOnly()) {
if (operation && requiresOffDeviceProcessing(operation))
throw documentPrivacyError();
@@ -224,18 +248,7 @@ export class OperationRouter {
backendUrl,
);
if (!supportedLocally) {
- // Open the connection settings so the user can sign in
- window.dispatchEvent(
- new CustomEvent("appConfig:navigate", {
- detail: { key: "connectionMode" },
- }),
- );
- throw new Error(
- i18n.t(
- "localMode.toolUnavailable",
- "This tool requires an account. Sign in to Stirling Cloud or connect to a self-hosted server to use it.",
- ),
- );
+ throw this.signInRequiredError();
}
}
}
@@ -284,26 +297,6 @@ export class OperationRouter {
);
if (!supportedLocally) {
- // Local backend doesn't support this - check if SaaS supports it
- const supportedOnSaaS =
- await endpointAvailabilityService.isEndpointSupportedOnSaaS(
- endpointToCheck,
- );
- console.debug(
- `[operationRouter] Endpoint ${endpointToCheck} supported on SaaS: ${supportedOnSaaS}`,
- );
-
- if (!supportedOnSaaS) {
- // Neither local nor SaaS support this - throw error
- console.error(
- `[operationRouter] Endpoint ${endpointToCheck} not supported on local or SaaS backend`,
- );
- throw new Error(
- `This operation (${endpointToCheck}) is not available. It may require a self-hosted instance with additional features enabled.`,
- );
- }
-
- // SaaS supports it - route to SaaS backend
if (!STIRLING_SAAS_BACKEND_API_URL) {
console.error(
"[operationRouter] VITE_SAAS_BACKEND_API_URL not configured",
@@ -314,7 +307,7 @@ export class OperationRouter {
);
}
console.debug(
- `[operationRouter] Routing ${operation} to SaaS backend (not supported locally, but supported on SaaS)`,
+ `[operationRouter] Routing ${operation} to SaaS backend (not supported locally)`,
);
return STIRLING_SAAS_BACKEND_API_URL.replace(/\/$/, "");
}
@@ -461,6 +454,7 @@ export class OperationRouter {
if (this.isToolEndpoint(endpoint)) {
// For UI data endpoints, extract the endpoint name
const endpointToCheck = this.extractEndpointName(endpoint);
+ if (mode === "local" && requiresSignIn(endpointToCheck)) return true;
const supportedLocally =
await endpointAvailabilityService.isEndpointSupportedLocally(
endpointToCheck,
diff --git a/frontend/src/editor/desktop/services/signInRequiredEndpoints.ts b/frontend/src/editor/desktop/services/signInRequiredEndpoints.ts
new file mode 100644
index 0000000000..3541770d54
--- /dev/null
+++ b/frontend/src/editor/desktop/services/signInRequiredEndpoints.ts
@@ -0,0 +1,20 @@
+const SIGN_IN_REQUIRED_ENDPOINTS: ReadonlySet<string> = new Set([
+ "file-to-pdf",
+ "pdf-to-word",
+ "pdf-to-presentation",
+ "pdf-to-rtf",
+ "pdf-to-html",
+ "pdf-to-xml",
+ "pdf-to-epub",
+ "pdf-to-pdfa",
+ "html-to-pdf",
+ "url-to-pdf",
+ "markdown-to-pdf",
+ "eml-to-pdf",
+ "ebook-to-pdf",
+ "extract-image-scans",
+]);
+
+export function requiresSignIn(endpointName: string): boolean {
+ return SIGN_IN_REQUIRED_ENDPOINTS.has(endpointName);
+}