Skip to content

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

Gate desktop premium surfaces on any connected server (#7961)

Anthony Stirling2b6439f25fe3
diff --git a/AGENTS.md b/AGENTS.md
index 9f2f3e9b7b..462c9ab58f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -235,7 +235,7 @@ What goes where:
Rule of thumb — **move, don't copy**: share via `cloud/`, override by shadowing the same `@app/*` path in a leaf (`saas/` or `desktop/`).
-**Cloud feature flags on desktop.** The local `AppConfigContext` reads `/api/v1/config/app-config` from the LOCAL bundled backend, so cloud-only flags (`aiEngineEnabled`, `premiumEnabled`, …) are never seen on desktop. To read the cloud's view, use `useSaasAppConfig()` (`desktop/hooks/useSaasAppConfig.ts`, backed by the general `saasAppConfigService` — SaaS-mode-only, public endpoint, native HTTP, 5-min cache). It returns `null` outside SaaS mode, so cloud features stay off in local/self-hosted and the server keeps the on/off switch (no desktop release needed to flip a flag). Gate a feature behind a per-platform seam — e.g. `useAiEngineEnabled()` (core reads `useAppConfig()`, desktop reads `useSaasAppConfig()`) — rather than hardcoding the flag on.
+**Cloud feature flags on desktop.** The local `AppConfigContext` reads `/api/v1/config/app-config` from the LOCAL bundled backend, so cloud-only flags (`aiEngineEnabled`, `premiumEnabled`, …) are never seen on desktop. To read the cloud's view, use `useSaasAppConfig()` (`desktop/hooks/useSaasAppConfig.ts`, backed by the general `saasAppConfigService` — SaaS-mode-only, public endpoint, native HTTP, 5-min cache). It returns `null` outside SaaS mode, so cloud features stay off in local mode and the server keeps the on/off switch (no desktop release needed to flip a flag). In self-hosted mode the connected server's own `AppConfigContext` is the authority instead. Gate a feature behind a per-platform seam - e.g. `useAiEngineEnabled()` (core reads `useAppConfig()`, desktop reads `useAppConfig()` when signed in to a self-hosted server and `useSaasAppConfig()` otherwise) - rather than hardcoding the flag on.
#### Component Override Pattern (Stub/Shadow)
Use this pattern for desktop-specific or proprietary-specific features WITHOUT runtime checks or conditionals.
diff --git a/frontend/editor/src/core/hooks/useConnectedServer.test.ts b/frontend/editor/src/core/hooks/useConnectedServer.test.ts
new file mode 100644
index 0000000000..fde07f8bb4
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useConnectedServer.test.ts
@@ -0,0 +1,10 @@
+import { describe, expect, it } from "vitest";
+import { useConnectedServer } from "@app/hooks/useConnectedServer";
+
+describe("useConnectedServer (core)", () => {
+ // Pins the stub: moving real logic in here would dark-ship the surfaces it gates
+ // on every web build, with no error anywhere.
+ it("is always true - a web build is served by the backend it calls", () => {
+ expect(useConnectedServer()).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/core/hooks/useConnectedServer.ts b/frontend/editor/src/core/hooks/useConnectedServer.ts
new file mode 100644
index 0000000000..f27b04a9b0
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useConnectedServer.ts
@@ -0,0 +1,5 @@
+/** Whether a server serving the non-core API - policies, processing folders, AI - backs the app.
+ * Always true on web, which is served by that backend; builds without one shadow this file. */
+export function useConnectedServer(): boolean {
+ return true;
+}
diff --git a/frontend/editor/src/core/services/aiBaseUrl.ts b/frontend/editor/src/core/services/aiBaseUrl.ts
index fe9ccb183a..aabd17363e 100644
--- a/frontend/editor/src/core/services/aiBaseUrl.ts
+++ b/frontend/editor/src/core/services/aiBaseUrl.ts
@@ -3,9 +3,8 @@ import { getApiBaseUrl } from "@app/services/apiClientConfig";
/**
* Base URL for AI-engine calls (orchestrate stream, AI result-file download).
*
- * Web builds talk to whichever backend the app is served from, so the normal API
- * base is correct. Desktop shadows this (desktop/services/aiBaseUrl) to point at
- * the SaaS backend, since the AI engine only runs in the cloud.
+ * Web builds talk to the backend they are served from. Desktop shadows this, where the bundled
+ * backend has no engine and the base is the connected server.
*/
export function getAiBaseUrl(): string {
return getApiBaseUrl().replace(/\/$/, ""); // Remove trailing slash
diff --git a/frontend/editor/src/desktop/auth/teamSession.ts b/frontend/editor/src/desktop/auth/teamSession.ts
index 7311cb0b4c..c6b1f13103 100644
--- a/frontend/editor/src/desktop/auth/teamSession.ts
+++ b/frontend/editor/src/desktop/auth/teamSession.ts
@@ -6,8 +6,8 @@
* gated on a live "authenticated" status from authService rather than a
* Supabase session.
*
- * Teams are a cloud-only surface: the endpoints (/api/v1/team/**) live on the
- * SaaS backend, not the local bundled backend or a self-hosted server. The
+ * Every path SaaSTeamContext calls is declared only on the SaaS backend; self-hosted serves
+ * /api/v1/team/** as a disjoint admin-only set this context never touches. The
* SaaSTeamProvider is mounted unconditionally in AppProviders, so canUseTeams
* is the ONLY thing stopping its mount effect from fetching teams. It must
* therefore also require SaaS connection mode — otherwise an authenticated user
diff --git a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
index e04859a45e..c64ee8483b 100644
--- a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
+++ b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
@@ -1,5 +1,5 @@
-import { useConfirmedSaaSMode } from "@app/hooks/useConfirmedSaaSMode";
+import { useConnectedServer } from "@app/hooks/useConnectedServer";
export function usePoliciesEnabled(): boolean {
- return useConfirmedSaaSMode();
+ return useConnectedServer();
}
diff --git a/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts b/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts
index 70c14fb798..a0cb20795d 100644
--- a/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts
+++ b/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts
@@ -1,13 +1,16 @@
+import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useSaasAppConfig } from "@app/hooks/useSaasAppConfig";
+import { useSelfHostedAuth } from "@app/hooks/useSelfHostedAuth";
-/**
- * Desktop: the AI engine runs on the SaaS backend, so its enabled flag must come
- * from the SaaS app-config (not the local bundled backend, which never has the
- * engine). useSaasAppConfig() returns null outside SaaS mode, so AI is implicitly
- * hidden in local/self-hosted — and the cloud retains the on/off switch (flip
- * aiEngineEnabled server-side and the desktop FAB disappears on next load, no
- * release required).
- */
+/** Desktop: the engine runs on the connected server, so the flag comes from that server's own
+ * app-config. Local mode reaches neither and reports the engine off. */
export function useAiEngineEnabled(): boolean {
- return Boolean(useSaasAppConfig()?.aiEngineEnabled);
+ const saasConfig = useSaasAppConfig();
+ const { config } = useAppConfig();
+ const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
+
+ if (isSelfHosted && isAuthenticated) {
+ return config?.aiEngineEnabled === true;
+ }
+ return Boolean(saasConfig?.aiEngineEnabled);
}
diff --git a/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts b/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts
index 53cfd3ab40..bdff432824 100644
--- a/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts
+++ b/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts
@@ -5,8 +5,8 @@ import { connectionModeService } from "@app/services/connectionModeService";
* Like {@link useSaaSMode}, but starts pessimistically FALSE: it returns true
* only once the connection mode has been CONFIRMED to be "saas".
*
- * Use this to gate mounting components that fire a network call on mount — the
- * cloud team context, the Policies rail + auto-run controller. useSaaSMode()
+ * Use this to gate mounting components that fire a network call on mount against
+ * Stirling Cloud specifically - the cloud team context. useSaaSMode()
* starts optimistically true (right for tool-availability UX, where a flash of
* "unavailable" is worse than a flash of "available"), but for a network-
* triggering gate that optimism leaks a request: the gated surface mounts on
diff --git a/frontend/editor/src/desktop/hooks/useConnectedServer.test.ts b/frontend/editor/src/desktop/hooks/useConnectedServer.test.ts
new file mode 100644
index 0000000000..324e983e5c
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useConnectedServer.test.ts
@@ -0,0 +1,161 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const {
+ getCachedModeMock,
+ getCurrentModeMock,
+ subscribeToModeChangesMock,
+ subscribeToAuthMock,
+} = vi.hoisted(() => ({
+ getCachedModeMock: vi.fn(),
+ getCurrentModeMock: vi.fn(),
+ subscribeToModeChangesMock: vi.fn(),
+ subscribeToAuthMock: vi.fn(),
+}));
+
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCachedMode: getCachedModeMock,
+ getCurrentMode: getCurrentModeMock,
+ subscribeToModeChanges: subscribeToModeChangesMock,
+ },
+}));
+vi.mock("@app/services/authService", () => ({
+ authService: { subscribeToAuth: subscribeToAuthMock },
+}));
+
+import { useConnectedServer } from "@app/hooks/useConnectedServer";
+
+/** subscribeToAuth replays the current status on subscribe, as the real service does. */
+function withAuthStatus(status: string, userInfo: unknown = null) {
+ subscribeToAuthMock.mockImplementation(
+ (cb: (s: string, u: unknown) => void) => {
+ cb(status, userInfo);
+ return () => {};
+ },
+ );
+}
+
+describe("useConnectedServer", () => {
+ beforeEach(() => {
+ getCachedModeMock.mockReset().mockReturnValue(null);
+ getCurrentModeMock.mockReset();
+ subscribeToModeChangesMock.mockReset().mockReturnValue(() => {});
+ subscribeToAuthMock.mockReset();
+ withAuthStatus("unauthenticated");
+ });
+ afterEach(() => vi.clearAllMocks());
+
+ it("starts false before either signal resolves", () => {
+ getCurrentModeMock.mockReturnValue(new Promise<never>(() => {}));
+ const { result } = renderHook(() => useConnectedServer());
+ expect(result.current).toBe(false);
+ });
+
+ it("is true when authenticated against a self-hosted server", async () => {
+ withAuthStatus("authenticated", { username: "ada" });
+ getCurrentModeMock.mockResolvedValue("selfhosted");
+ const { result } = renderHook(() => useConnectedServer());
+ await waitFor(() => expect(result.current).toBe(true));
+ });
+
+ it("is true when authenticated against Stirling Cloud", async () => {
+ withAuthStatus("authenticated", { username: "ada" });
+ getCurrentModeMock.mockResolvedValue("saas");
+ const { result } = renderHook(() => useConnectedServer());
+ await waitFor(() => expect(result.current).toBe(true));
+ });
+
+ it("is false in local mode even when authenticated", async () => {
+ withAuthStatus("authenticated", { username: "ada" });
+ getCurrentModeMock.mockResolvedValue("local");
+ const { result } = renderHook(() => useConnectedServer());
+ await act(async () => {});
+ expect(result.current).toBe(false);
+ });
+
+ it("is false when signed out of a connected server", async () => {
+ getCurrentModeMock.mockResolvedValue("selfhosted");
+ const { result } = renderHook(() => useConnectedServer());
+ await act(async () => {});
+ expect(result.current).toBe(false);
+ });
+
+ it("stays true while a token refresh is in flight", async () => {
+ let notifyAuth: ((s: string, u: unknown) => void) | undefined;
+ subscribeToAuthMock.mockImplementation(
+ (cb: (s: string, u: unknown) => void) => {
+ notifyAuth = cb;
+ cb("authenticated", { username: "ada" });
+ return () => {};
+ },
+ );
+ getCurrentModeMock.mockResolvedValue("saas");
+ const { result } = renderHook(() => useConnectedServer());
+ await waitFor(() => expect(result.current).toBe(true));
+
+ await act(async () => notifyAuth?.("refreshing", { username: "ada" }));
+ expect(result.current).toBe(true);
+ });
+
+ it("is connected when it mounts midway through a token refresh", async () => {
+ // A fresh mount sees only the replayed "refreshing"; its live user distinguishes that
+ // from a cold start.
+ withAuthStatus("refreshing", { username: "ada" });
+ getCurrentModeMock.mockResolvedValue("selfhosted");
+ const { result } = renderHook(() => useConnectedServer());
+ await waitFor(() => expect(result.current).toBe(true));
+ });
+
+ it("is not connected during an OAuth handshake, which carries no user", async () => {
+ withAuthStatus("oauth_pending", null);
+ getCurrentModeMock.mockResolvedValue("saas");
+ const { result } = renderHook(() => useConnectedServer());
+ await act(async () => {});
+ expect(result.current).toBe(false);
+ });
+
+ it("drops to false when the session ends", async () => {
+ let notifyAuth: ((s: string, u: unknown) => void) | undefined;
+ subscribeToAuthMock.mockImplementation(
+ (cb: (s: string, u: unknown) => void) => {
+ notifyAuth = cb;
+ cb("authenticated", { username: "ada" });
+ return () => {};
+ },
+ );
+ getCurrentModeMock.mockResolvedValue("selfhosted");
+ const { result } = renderHook(() => useConnectedServer());
+ await waitFor(() => expect(result.current).toBe(true));
+
+ await act(async () => notifyAuth?.("unauthenticated", null));
+ expect(result.current).toBe(false);
+ });
+
+ it("reacts to a later switch onto a server", async () => {
+ withAuthStatus("authenticated", { username: "ada" });
+ getCurrentModeMock.mockResolvedValue("local");
+ let notifyMode: ((cfg: { mode: string }) => void) | undefined;
+ subscribeToModeChangesMock.mockImplementation(
+ (cb: (cfg: { mode: string }) => void) => {
+ notifyMode = cb;
+ return () => {};
+ },
+ );
+
+ const { result } = renderHook(() => useConnectedServer());
+ await act(async () => {});
+ expect(result.current).toBe(false);
+
+ await act(async () => notifyMode?.({ mode: "selfhosted" }));
+ expect(result.current).toBe(true);
+ });
+
+ it("seeds from the cached mode so a remount answers on its first frame", () => {
+ withAuthStatus("authenticated", { username: "ada" });
+ getCachedModeMock.mockReturnValue("saas");
+ getCurrentModeMock.mockReturnValue(new Promise<never>(() => {}));
+ const { result } = renderHook(() => useConnectedServer());
+ expect(result.current).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/desktop/hooks/useConnectedServer.ts b/frontend/editor/src/desktop/hooks/useConnectedServer.ts
new file mode 100644
index 0000000000..54468ed5c5
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useConnectedServer.ts
@@ -0,0 +1,54 @@
+import { useEffect, useState } from "react";
+import { authService } from "@app/services/authService";
+import {
+ connectionModeService,
+ type ConnectionMode,
+} from "@app/services/connectionModeService";
+
+function isServerMode(mode: ConnectionMode | null): boolean {
+ return mode === "saas" || mode === "selfhosted";
+}
+
+/** Whether the app is signed in to Stirling Cloud or a self-hosted server. Starts false: this
+ * gates surfaces that fetch on mount, and the bundled backend 404s every one of those calls. */
+export function useConnectedServer(): boolean {
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
+ const [isServer, setIsServer] = useState(() =>
+ isServerMode(connectionModeService.getCachedMode()),
+ );
+
+ useEffect(
+ () =>
+ authService.subscribeToAuth((status, userInfo) => {
+ // subscribeToAuth replays, so a mount mid-refresh sees only "refreshing"; the live user
+ // it carries is what separates a warm refresh from a cold OAuth handshake.
+ if (status === "authenticated") {
+ setIsAuthenticated(true);
+ } else if (status === "unauthenticated") {
+ setIsAuthenticated(false);
+ } else {
+ setIsAuthenticated(userInfo != null);
+ }
+ }),
+ [],
+ );
+
+ useEffect(() => {
+ let current = true;
+ void connectionModeService.getCurrentMode().then((mode) => {
+ if (current) setIsServer(isServerMode(mode));
+ });
+ const unsubscribe = connectionModeService.subscribeToModeChanges(
+ (config) => {
+ current = false;
+ setIsServer(isServerMode(config.mode));
+ },
+ );
+ return () => {
+ current = false;
+ unsubscribe();
+ };
+ }, []);
+
+ return isAuthenticated && isServer;
+}
diff --git a/frontend/editor/src/desktop/services/aiBaseUrl.test.ts b/frontend/editor/src/desktop/services/aiBaseUrl.test.ts
new file mode 100644
index 0000000000..3972e64985
--- /dev/null
+++ b/frontend/editor/src/desktop/services/aiBaseUrl.test.ts
@@ -0,0 +1,58 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ mode: null as "saas" | "selfhosted" | "local" | null,
+ serverConfig: null as { url: string } | null,
+}));
+
+// NB: vi.mock factories are hoisted above top-level consts, so they must use
+// literals to avoid a TDZ ReferenceError.
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCachedMode: () => mocks.mode,
+ getCachedServerConfig: () => mocks.serverConfig,
+ },
+}));
+vi.mock("@app/constants/connection", () => ({
+ STIRLING_SAAS_BACKEND_API_URL: "https://api.saas.test/",
+}));
+
+import { getAiBaseUrl } from "@app/services/aiBaseUrl";
+
+describe("getAiBaseUrl", () => {
+ beforeEach(() => {
+ mocks.mode = null;
+ mocks.serverConfig = null;
+ });
+
+ test("SaaS mode resolves the cloud base, trailing slash stripped", () => {
+ mocks.mode = "saas";
+ expect(getAiBaseUrl()).toBe("https://api.saas.test");
+ });
+
+ test("self-hosted resolves the connected server, not the cloud", () => {
+ mocks.mode = "selfhosted";
+ mocks.serverConfig = { url: "https://pdf.example.internal/" };
+ expect(getAiBaseUrl()).toBe("https://pdf.example.internal");
+ });
+
+ test("self-hosted stays absolute so the raw orchestrate fetch cannot resolve against the webview origin", () => {
+ mocks.mode = "selfhosted";
+ mocks.serverConfig = { url: "https://pdf.example.internal" };
+ expect(getAiBaseUrl().startsWith("https://")).toBe(true);
+ });
+
+ test("self-hosted with no server recorded yields no base", () => {
+ mocks.mode = "selfhosted";
+ expect(getAiBaseUrl()).toBe("");
+ });
+
+ test("local mode has no engine to reach", () => {
+ mocks.mode = "local";
+ expect(getAiBaseUrl()).toBe("");
+ });
+
+ test("unresolved mode fails closed rather than guessing the cloud", () => {
+ expect(getAiBaseUrl()).toBe("");
+ });
+});
diff --git a/frontend/editor/src/desktop/services/aiBaseUrl.ts b/frontend/editor/src/desktop/services/aiBaseUrl.ts
index ba629a9747..7deab03df4 100644
--- a/frontend/editor/src/desktop/services/aiBaseUrl.ts
+++ b/frontend/editor/src/desktop/services/aiBaseUrl.ts
@@ -1,14 +1,7 @@
-import { STIRLING_SAAS_BACKEND_API_URL } from "@app/constants/connection";
+import { connectedServerBaseUrl } from "@app/services/connectedServerBaseUrl";
-/**
- * Desktop: AI-engine calls must hit the SaaS backend (the local bundled backend
- * has no AI engine). The AI surface is only shown in SaaS mode (gated by
- * useAiEngineEnabled), so returning the SaaS base unconditionally is correct —
- * when an AI call is made, the app is in SaaS mode.
- *
- * Used for the orchestrate stream (a raw fetch) and the AI result-file download,
- * which would otherwise resolve to the empty/local base and miss the engine.
- */
+/** Desktop: the AI engine lives on the connected server, never on the bundled backend. Absolute
+ * because one consumer is a raw fetch, where a relative path would hit the webview origin. */
export function getAiBaseUrl(): string {
- return (STIRLING_SAAS_BACKEND_API_URL ?? "").replace(/\/$/, "");
+ return connectedServerBaseUrl();
}
diff --git a/frontend/editor/src/desktop/services/connectedServerBaseUrl.ts b/frontend/editor/src/desktop/services/connectedServerBaseUrl.ts
new file mode 100644
index 0000000000..8f6e1149f9
--- /dev/null
+++ b/frontend/editor/src/desktop/services/connectedServerBaseUrl.ts
@@ -0,0 +1,18 @@
+import { STIRLING_SAAS_BACKEND_API_URL } from "@app/constants/connection";
+import { connectionModeService } from "@app/services/connectionModeService";
+
+/** Absolute base of the connected server, or "" in local mode and before the mode resolves.
+ * Read from the cached mode so callers building a URL inline stay synchronous. */
+export function connectedServerBaseUrl(): string {
+ const mode = connectionModeService.getCachedMode();
+ if (mode === "saas") {
+ return (STIRLING_SAAS_BACKEND_API_URL ?? "").replace(/\/$/, "");
+ }
+ if (mode === "selfhosted") {
+ return (connectionModeService.getCachedServerConfig()?.url ?? "").replace(
+ /\/$/,
+ "",
+ );
+ }
+ return "";
+}
diff --git a/frontend/editor/src/desktop/services/connectionModeService.ts b/frontend/editor/src/desktop/services/connectionModeService.ts
index fe4fe320a6..b472e8ab1a 100644
--- a/frontend/editor/src/desktop/services/connectionModeService.ts
+++ b/frontend/editor/src/desktop/services/connectionModeService.ts
@@ -76,6 +76,12 @@ export class ConnectionModeService {
return this.currentConfig?.mode ?? null;
}
+ /** The server already in memory, or null before the first load. Synchronous so
+ * callers that build a URL inline (raw fetch, template string) can reach it. */
+ getCachedServerConfig(): ServerConfig | null {
+ return this.currentConfig?.server_config ?? null;
+ }
+
async getServerConfig(): Promise<ServerConfig | null> {
const config = await this.getCurrentConfig();
return config.server_config;
diff --git a/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts b/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts
new file mode 100644
index 0000000000..059793957f
--- /dev/null
+++ b/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ mode: null as "saas" | "selfhosted" | "local" | null,
+ serverConfig: null as { url: string } | null,
+}));
+
+// NB: vi.mock factories are hoisted above top-level consts, so they must use
+// literals to avoid a TDZ ReferenceError.
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCachedMode: () => mocks.mode,
+ getCachedServerConfig: () => mocks.serverConfig,
+ },
+}));
+vi.mock("@app/constants/connection", () => ({
+ STIRLING_SAAS_BACKEND_API_URL: "https://api.saas.test/",
+}));
+
+import { getPolicyOutputBaseUrl } from "@app/services/policyOutputBaseUrl";
+
+describe("getPolicyOutputBaseUrl", () => {
+ beforeEach(() => {
+ mocks.mode = null;
+ mocks.serverConfig = null;
+ });
+
+ test("SaaS run in SaaS mode resolves the cloud base", () => {
+ mocks.mode = "saas";
+ expect(getPolicyOutputBaseUrl("saas")).toBe("https://api.saas.test");
+ });
+
+ test("self-hosted names its own server", () => {
+ mocks.mode = "selfhosted";
+ mocks.serverConfig = { url: "https://pdf.example.internal/" };
+ expect(getPolicyOutputBaseUrl("saas")).toBe("https://pdf.example.internal");
+ });
+
+ test("self-hosted stays absolute so an offline blip cannot divert the download to the bundled backend", () => {
+ // Outputs come from a tool endpoint, which the router diverts to the bundled backend
+ // while the server is unreachable.
+ mocks.mode = "selfhosted";
+ mocks.serverConfig = { url: "https://pdf.example.internal" };
+ expect(getPolicyOutputBaseUrl("saas").startsWith("https://")).toBe(true);
+ });
+
+ test("self-hosted with no server recorded yields no base", () => {
+ mocks.mode = "selfhosted";
+ expect(getPolicyOutputBaseUrl("saas")).toBe("");
+ });
+
+ test("local mode never resolves the cloud base", () => {
+ mocks.mode = "local";
+ expect(getPolicyOutputBaseUrl("saas")).toBe("");
+ });
+
+ test("unresolved mode fails closed", () => {
+ expect(getPolicyOutputBaseUrl("saas")).toBe("");
+ });
+
+ test("a browser-computed run is always relative", () => {
+ mocks.mode = "saas";
+ expect(getPolicyOutputBaseUrl("local")).toBe("");
+ });
+});
diff --git a/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts b/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts
index 82b452aa0c..8548073ead 100644
--- a/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts
+++ b/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts
@@ -1,12 +1,8 @@
-import { STIRLING_SAAS_BACKEND_API_URL } from "@app/constants/connection";
+import { connectedServerBaseUrl } from "@app/services/connectedServerBaseUrl";
import type { PolicyExecutionTarget } from "@app/services/policyPipeline";
-/**
- * Desktop: a policy run's outputs live on the backend that executed it.
- */
+/** Desktop: a run's outputs live on the server that executed it. Absolute, because outputs come
+ * from a tool endpoint the router would otherwise divert to the bundled backend when offline. */
export function getPolicyOutputBaseUrl(target: PolicyExecutionTarget): string {
- if (target === "saas") {
- return (STIRLING_SAAS_BACKEND_API_URL ?? "").replace(/\/$/, "");
- }
- return "";
+ return target === "saas" ? connectedServerBaseUrl() : "";
}
diff --git a/frontend/editor/src/proprietary/components/chat/ChatContext.tsx b/frontend/editor/src/proprietary/components/chat/ChatContext.tsx
index 9ec18089a2..044f856941 100644
--- a/frontend/editor/src/proprietary/components/chat/ChatContext.tsx
+++ b/frontend/editor/src/proprietary/components/chat/ChatContext.tsx
@@ -422,8 +422,8 @@ export function ChatProvider({ children }: { children: ReactNode }) {
// Download a File from the Stirling files endpoint.
const downloadFile = useCallback(
async (descriptor: AiWorkflowResultFile): Promise<File> => {
- // AI result files live on the backend that ran the workflow (the SaaS
- // engine on desktop), so fetch from the AI base, not the local backend.
+ // AI result files live on the backend that ran the workflow (the connected
+ // server on desktop), so fetch from the AI base, not the local backend.
const response = await apiClient.get<Blob>(
`${getAiBaseUrl()}/api/v1/general/files/${descriptor.fileId}`,
{ responseType: "blob" },
diff --git a/frontend/editor/src/proprietary/components/policies/README.md b/frontend/editor/src/proprietary/components/policies/README.md
index c98f552490..22e59b0cbe 100644
--- a/frontend/editor/src/proprietary/components/policies/README.md
+++ b/frontend/editor/src/proprietary/components/policies/README.md
@@ -6,8 +6,10 @@ Automation-backed document-enforcement policies. The editor side is
uploaded files, blocks the file's exit points while a run is in flight, and
badges files a policy has produced. Always on in the proprietary/SaaS builds;
the core (OSS) build has no implementation (`usePoliciesEnabled` stub = false),
-and desktop additionally requires an active SaaS connection (runs bill through
-the cloud). The single gate is `components/policies/usePoliciesEnabled.ts`.
+and desktop additionally requires a connected server - Stirling Cloud or a
+self-hosted instance - because its bundled backend serves no policy engine. Runs
+bill through whichever server is connected. The single gate is
+`components/policies/usePoliciesEnabled.ts`.
A required upload-policy failure pauses the entire editor with `PolicyRecoveryGate`.
The modal keeps editor state mounted, makes the background inert, and pauses editor
@@ -29,7 +31,7 @@ Operation, download and upload boundaries recheck failures after asynchronous pr
| `services/policyStorage.ts` | Local persistence (localStorage) of per-policy state + change events. |
| `hooks/usePolicies.ts` | Policy state + permission flag, consumed by the auto-run controller. |
| `hooks/usePolicyFileBadges.ts` | Per-file badge map (which policies produced/are enforcing a file) — drives the shared `PolicyBadges` row and the exit-point blocking. |
-| `components/policies/usePoliciesEnabled.ts` | The single build/connection gate for mounting the auto-run controller. Core stub = false; desktop shadow adds the SaaS-connection check. |
+| `components/policies/usePoliciesEnabled.ts` | The single build/connection gate for mounting the auto-run controller. Core stub = false; desktop shadow requires a connected server (`useConnectedServer`). |
| `components/policies/PolicyAutoRunController.tsx` | Runs policies and recovery once per editor. Mounted by `HomePage`, outside the tool sidebar. |
| `components/policies/usePolicyAutoRun.ts` | The auto-run engine: dispatch, polling, retry, output import, server reconcile. |
| `components/policies/policyRunStore.ts` | `useSyncExternalStore` store of run records (status, progress, outputs), persisted to localStorage. |