Skip to content

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

Require accounts for SaaS Processor and remind guests to sign up (#8045)

ConnorYoh40748502e287
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java
index 2acad55f41..27cca0fe97 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java
@@ -155,12 +155,17 @@ public class PaygWalletController {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
+ if (AuthenticationUtils.isAnonymous(auth)
+ || "ANONYMOUS".equalsIgnoreCase(user.getAuthenticationType())) {
+ return ResponseEntity.ok(emptySnapshot(0));
+ }
+
Optional<Long> resolvedTeam = userTeamResolver.teamId(user);
if (resolvedTeam.isEmpty()) {
// Authenticated user without a team — shouldn't happen post-migration, but we don't
// want to 500. Return a free-tier-shaped empty snapshot so the FE renders the gated UI
// rather than blowing up on a null body.
- return ResponseEntity.ok(emptySnapshot());
+ return ResponseEntity.ok(emptySnapshot(FREE_TIER_LIMIT_UNITS_FALLBACK));
}
Long teamId = resolvedTeam.get();
boolean isLeader = userTeamResolver.isLeader(user);
@@ -503,7 +508,7 @@ public class PaygWalletController {
return (int) v;
}
- private WalletSnapshotResponse emptySnapshot() {
+ private WalletSnapshotResponse emptySnapshot(int allowance) {
LocalDateTime[] window = currentMonthWindow();
return new WalletSnapshotResponse(
null, // teamId — unknown when the caller has no team membership
@@ -514,9 +519,9 @@ public class PaygWalletController {
ISO_DATE.format(window[0].toLocalDate()),
ISO_DATE.format(window[1].toLocalDate()),
0,
- FREE_TIER_LIMIT_UNITS_FALLBACK,
- FREE_TIER_LIMIT_UNITS_FALLBACK,
- FREE_TIER_LIMIT_UNITS_FALLBACK,
+ allowance,
+ allowance,
+ allowance,
UserLicenseSettingsService.DEFAULT_USER_LIMIT,
null,
null,
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
index b9856a17b5..d4be0aef56 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
@@ -29,7 +29,9 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.AutoJobPostMapping;
+import stirling.software.proprietary.controller.api.PortalApiKeysController;
import stirling.software.proprietary.policy.controller.PolicyRunRoutes;
+import stirling.software.proprietary.security.controller.api.UserController;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
@@ -41,7 +43,7 @@ import stirling.software.saas.util.AuthenticationUtils;
import tools.jackson.databind.ObjectMapper;
/**
- * Hot-path entitlement check. Runs after {@code PaygChargeInterceptor} in the MVC chain and short-
+ * Hot-path entitlement check. Runs before {@code PaygChargeInterceptor} in the MVC chain and short-
* circuits the request before any handler work happens when the team's snapshot is missing one of
* the gates the route declared via {@link RequiresFeature}.
*
@@ -58,13 +60,13 @@ import tools.jackson.databind.ObjectMapper;
* <table>
* <tr><th>auth</th><th>required gates</th><th>snapshot enabled?</th><th>outcome</th></tr>
* <tr><td>anonymous</td><td>AUTOMATION or AI_SUPPORT</td><td>n/a</td><td>401 SIGNUP_REQUIRED</td></tr>
- * <tr><td>anonymous</td><td>OFFSITE_PROCESSING / CLIENT_SIDE</td><td>n/a</td><td>200 (pass through)</td></tr>
+ * <tr><td>guest</td><td>OFFSITE_PROCESSING / CLIENT_SIDE</td><td>n/a</td><td>200</td></tr>
* <tr><td>authenticated</td><td>required ⊆ enabled</td><td>yes</td><td>200</td></tr>
* <tr><td>authenticated</td><td>required ⊄ enabled</td><td>no</td><td>402 FEATURE_DEGRADED</td></tr>
* </table>
*
- * <p>Fail-open: any unexpected exception is logged at WARN and the request passes through. The cap
- * pipeline must never block a customer because the guard tripped on a transient DB error.
+ * <p>Account billing lookups fail open on transient errors. Guests may use manual tools without
+ * billing or usage tracking; billable Processor features require an account.
*/
@Slf4j
@Component
@@ -124,6 +126,15 @@ public class EntitlementGuard implements HandlerInterceptor {
if (!(handler instanceof HandlerMethod hm)) {
return true;
}
+ Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+ boolean keyManagement =
+ PortalApiKeysController.class.isAssignableFrom(hm.getBeanType())
+ || (UserController.class.isAssignableFrom(hm.getBeanType())
+ && (hm.getMethod().getName().equals("getApiKey")
+ || hm.getMethod().getName().equals("updateApiKey")));
+ if (keyManagement && AuthenticationUtils.isAnonymous(auth)) {
+ return write401SignupRequired(response, "API");
+ }
// Scope: AutoJobPostMapping routes (multipart tool POSTs) OR routes that explicitly
// declare @RequiresFeature (e.g. AI controllers — JSON-bodied, no AutoJobPostMapping).
// Admin / info / config endpoints carry neither annotation and never trip the guard.
@@ -143,7 +154,14 @@ public class EntitlementGuard implements HandlerInterceptor {
// Policy execute routes (/api/v1/policies/**/run etc.) are proprietary and can't carry
// @RequiresFeature; recognise them by path and gate on AUTOMATION (mirrors aiToolRoute).
boolean policyRunRoute = PolicyRunRoutes.matches(request);
- if (!hasAutoJobPostMapping && !hasRequiresFeature && !aiToolRoute && !policyRunRoute) {
+ String automationHeader = request.getHeader("X-Stirling-Automation");
+ boolean automationStep =
+ automationHeader != null && "true".equalsIgnoreCase(automationHeader.trim());
+ if (!hasAutoJobPostMapping
+ && !hasRequiresFeature
+ && !aiToolRoute
+ && !policyRunRoute
+ && !automationStep) {
skippedNoAnnotationCounter.increment();
return true;
}
@@ -151,20 +169,16 @@ public class EntitlementGuard implements HandlerInterceptor {
FeatureGate[] required =
aiToolRoute
? new FeatureGate[] {FeatureGate.AI_SUPPORT}
- : policyRunRoute
+ : policyRunRoute || automationStep
? new FeatureGate[] {FeatureGate.AUTOMATION}
: resolveRequiredGates(hm);
- Authentication auth = SecurityContextHolder.getContext().getAuthentication();
-
- boolean anonymous = isAnonymous(auth);
- boolean billable = isBillable(required);
+ boolean anonymous = AuthenticationUtils.isAnonymous(auth);
+ boolean billable = isBillable(required) || auth instanceof ApiKeyAuthenticationToken;
if (anonymous) {
if (billable) {
return write401SignupRequired(response, required);
}
- // Anonymous user calling a manual / OFFSITE-only tool — let it through; PAYG only
- // charges authenticated requests.
passCounter.increment();
return true;
}
@@ -226,14 +240,6 @@ public class EntitlementGuard implements HandlerInterceptor {
return DEFAULT_REQUIRED_GATES;
}
- private static boolean isAnonymous(Authentication auth) {
- if (auth == null || !auth.isAuthenticated()) {
- return true;
- }
- // Spring's anonymous filter installs a token whose name is "anonymousUser".
- return "anonymousUser".equals(auth.getName());
- }
-
private static boolean isBillable(FeatureGate[] required) {
for (FeatureGate g : required) {
if (g == FeatureGate.AUTOMATION || g == FeatureGate.AI_SUPPORT) {
@@ -266,10 +272,14 @@ public class EntitlementGuard implements HandlerInterceptor {
}
private boolean write401SignupRequired(HttpServletResponse response, FeatureGate[] required) {
+ return write401SignupRequired(response, inferCategory(required));
+ }
+
+ private boolean write401SignupRequired(HttpServletResponse response, String category) {
deniedSignupRequiredCounter.increment();
Map<String, Object> body = new LinkedHashMap<>();
body.put("error", "SIGNUP_REQUIRED");
- body.put("category", inferCategory(required));
+ body.put("category", category);
writeJson(response, HttpStatus.UNAUTHORIZED, body);
return false;
}
diff --git a/app/saas/src/main/java/stirling/software/saas/util/AuthenticationUtils.java b/app/saas/src/main/java/stirling/software/saas/util/AuthenticationUtils.java
index 3780573fb3..ab28adc078 100644
--- a/app/saas/src/main/java/stirling/software/saas/util/AuthenticationUtils.java
+++ b/app/saas/src/main/java/stirling/software/saas/util/AuthenticationUtils.java
@@ -1,7 +1,9 @@
package stirling.software.saas.util;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
+import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
@@ -14,6 +16,22 @@ import stirling.software.saas.security.EnhancedJwtAuthenticationToken;
*/
public class AuthenticationUtils {
+ /** Supabase guests have authenticated JWTs; authentication alone does not confer an account. */
+ public static boolean isAnonymous(Authentication authentication) {
+ if (authentication == null
+ || !authentication.isAuthenticated()
+ || authentication instanceof AnonymousAuthenticationToken
+ || "anonymousUser".equals(authentication.getName())) {
+ return true;
+ }
+ if (authentication instanceof JwtAuthenticationToken jwt
+ && Boolean.TRUE.equals(jwt.getToken().getClaimAsBoolean("is_anonymous"))) {
+ return true;
+ }
+ return authentication.getPrincipal() instanceof User user
+ && "ANONYMOUS".equalsIgnoreCase(user.getAuthenticationType());
+ }
+
private AuthenticationUtils() {
// Utility class - no instances
}
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java
index ddc80d39ca..f6fb15b0e9 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java
@@ -626,6 +626,30 @@ class PaygWalletControllerTest {
// Fixtures
// -----------------------------------------------------------------------------------------
+ @Test
+ void supabaseGuestHasNoProcessorAllowanceEvenWithLegacyTeam() {
+ UUID id = UUID.randomUUID();
+ User user = userWithId(12L, id);
+ user.setTeam(teamWithId(77L));
+ when(userRepository.findBySupabaseId(id)).thenReturn(Optional.of(user));
+ Jwt jwt =
+ Jwt.withTokenValue("guest")
+ .header("alg", "RS256")
+ .claim("sub", id.toString())
+ .claim("is_anonymous", true)
+ .build();
+ Authentication auth =
+ new EnhancedJwtAuthenticationToken(jwt, List.of(), "anon_" + id, id.toString());
+
+ WalletSnapshotResponse body = controller.getWallet(auth).getBody();
+
+ assertThat(body.freeAllowance()).isZero();
+ assertThat(body.freeRemaining()).isZero();
+ assertThat(body.billableLimit()).isZero();
+ assertThat(body.teamId()).isNull();
+ org.mockito.Mockito.verifyNoInteractions(billingService, entitlementService, memberRepo);
+ }
+
private static User userWithId(Long id, UUID supabaseId) {
User u = new User();
u.setId(id);
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
index dad953d61e..31024e5252 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
@@ -338,7 +338,7 @@ class EntitlementGuardTest {
}
@Test
- void anonymousUser_manualTool_passesThroughUnbilled() throws Exception {
+ void anonymousUser_manualTools_passThrough() throws Exception {
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken(
@@ -354,7 +354,7 @@ class EntitlementGuardTest {
assertThat(proceed).isTrue();
assertThat(res.getStatus()).isEqualTo(200);
- Mockito.verifyNoInteractions(entitlementService);
+ Mockito.verifyNoInteractions(entitlementService, userRepository);
}
// ---------------------------------------------------------------------------------------
@@ -640,6 +640,76 @@ class EntitlementGuardTest {
return u;
}
+ @Test
+ void supabaseGuestCannotUseProcessorEvenWithExistingTeam() throws Exception {
+ SecurityContextHolder.getContext().setAuthentication(guestAuth(UUID.randomUUID()));
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ assertThat(guard.preHandle(new MockHttpServletRequest(), response, handlerFor("aiOnly")))
+ .isFalse();
+ assertThat(response.getStatus()).isEqualTo(401);
+ assertThat(json.readTree(response.getContentAsString()).get("error").asText())
+ .isEqualTo("SIGNUP_REQUIRED");
+ Mockito.verifyNoInteractions(entitlementService, userRepository);
+ }
+
+ @Test
+ void supabaseGuestManualToolsRemainUnlimitedWithoutDatabaseLookups() throws Exception {
+ SecurityContextHolder.getContext().setAuthentication(guestAuth(UUID.randomUUID()));
+ for (int run = 0; run < 10; run++) {
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ assertThat(
+ guard.preHandle(
+ new MockHttpServletRequest(),
+ response,
+ handlerFor("manualTool")))
+ .isTrue();
+ assertThat(response.getStatus()).isEqualTo(200);
+ }
+ Mockito.verifyNoInteractions(entitlementService, userRepository);
+ }
+
+ private static EnhancedJwtAuthenticationToken guestAuth(UUID id) {
+ Jwt jwt =
+ new Jwt(
+ "token",
+ Instant.now(),
+ Instant.now().plusSeconds(3600),
+ Map.of("alg", "RS256"),
+ Map.of("sub", id.toString(), "is_anonymous", true));
+ return new EnhancedJwtAuthenticationToken(
+ jwt,
+ List.of(new SimpleGrantedAuthority("ROLE_LIMITED_API_USER")),
+ "anon_" + id,
+ id.toString());
+ }
+
+ @Test
+ void guestCannotMintLegacyApiKey() throws Exception {
+ SecurityContextHolder.getContext().setAuthentication(guestAuth(UUID.randomUUID()));
+ Class<stirling.software.proprietary.security.controller.api.UserController> type =
+ stirling.software.proprietary.security.controller.api.UserController.class;
+ HandlerMethod handler =
+ new HandlerMethod(
+ Mockito.mock(type),
+ type.getMethod("updateApiKey", java.security.Principal.class));
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ assertThat(guard.preHandle(new MockHttpServletRequest(), response, handler)).isFalse();
+ assertThat(json.readTree(response.getContentAsString()).get("category").asText())
+ .isEqualTo("API");
+ Mockito.verifyNoInteractions(entitlementService);
+ }
+
+ @Test
+ void guestCannotBypassProcessorGateWithAutomationHeader() throws Exception {
+ SecurityContextHolder.getContext().setAuthentication(guestAuth(UUID.randomUUID()));
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.addHeader("X-Stirling-Automation", "true");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ assertThat(guard.preHandle(request, response, handlerFor("plainEndpoint"))).isFalse();
+ assertThat(response.getStatus()).isEqualTo(401);
+ Mockito.verifyNoInteractions(entitlementService);
+ }
+
private static EnhancedJwtAuthenticationToken jwtAuth(UUID supabaseId) {
Map<String, Object> headers = new HashMap<>();
headers.put("alg", "RS256");
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index dfa138d970..9a172630a3 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6500,17 +6500,16 @@ leader = "Team owner"
member = "Member"
[payg.signupRequired]
-bodyMonthlyAllowance = "Stirling PDF gives every signed-up account a free monthly allowance for operations. You're currently using Stirling as a guest, which doesn't include billable tools like AI, automations, or hosted processing."
-cancel = "Not now"
-cta = "Sign up free"
-subtext = "Creating an account is free and takes a few seconds. No credit card required."
-title = "Sign up to use {{category}}"
-
-[payg.signupRequired.category]
-ai = "AI features"
-api = "this tool"
-automation = "automations"
-default = "this feature"
+aiPromo = "Create, edit and ask about PDFs with AI"
+apiPromo = "Connect your apps and AI assistants"
+automationPromo = "Automate repetitive PDF tasks"
+createAccount = "Create free account"
+editorLabel = "PDF Editor"
+login = "Log in"
+manualToolsPromo = "Unlimited free manual PDF tools"
+processorLabel = "PDF Processor"
+processorTitle = "Create an account to unlock the best of Stirling"
+readerLabel = "PDF Reader"
[payg.spendCapMeter]
barAria = "Spend against cap"
diff --git a/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts b/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts
index bed7d1dab7..04319ffa4b 100644
--- a/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts
+++ b/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import { useWallet } from "@app/hooks/useWallet";
+import { useAuth } from "@app/auth/UseSession";
import {
readCachedCredits,
writeCachedCredits,
@@ -23,15 +24,16 @@ function toCredits(
* Cloud builds read the free grant off the live wallet — the same snapshot the
* Plan page's free meter renders, so the sidebar and Plan can't disagree.
*
- * Seeded from the last figures this browser saw, so the row is right at first
- * paint and stays put while the wallet refetches underneath. Only a browser
- * that has never loaded a wallet has nothing to show, and that one time the row
- * animates in. The seed is read once, at first render: later reads would fight
- * the live value, and the whole point is that the row stops moving.
+ * Cached figures are read once and shown only after authentication resolves.
+ * Live wallet data takes precedence. Guest sessions discard the seed as well
+ * as the stored cache so signup cannot revive a previous account's figures.
*/
export function useFreeCreditsSummary(): NavFooterCredits | null {
- const { wallet } = useWallet();
- const [seed] = useState(readCachedCredits);
+ const { isAnonymous, loading } = useAuth();
+ const { wallet } = useWallet(!loading && !isAnonymous);
+ const [seed, setSeed] = useState(() =>
+ isAnonymous ? null : readCachedCredits(),
+ );
const live = wallet
? toCredits(wallet.status, wallet.freeRemaining, wallet.freeAllowance)
@@ -40,9 +42,13 @@ export function useFreeCreditsSummary(): NavFooterCredits | null {
// useWallet reuses the snapshot reference when nothing changed, so keying on
// it writes only on a real change, not on every render.
useEffect(() => {
- if (live !== undefined) writeCachedCredits(live);
+ if (isAnonymous) {
+ setSeed(null);
+ writeCachedCredits(null);
+ } else if (live !== undefined) writeCachedCredits(live);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [wallet]);
+ }, [wallet, isAnonymous]);
+ if (loading || isAnonymous) return null;
return (live !== undefined ? live : seed) ?? null;
}
diff --git a/frontend/editor/src/cloud/services/paygErrorInterceptor.ts b/frontend/editor/src/cloud/services/paygErrorInterceptor.ts
index 5b11392f0e..338a2e71fb 100644
--- a/frontend/editor/src/cloud/services/paygErrorInterceptor.ts
+++ b/frontend/editor/src/cloud/services/paygErrorInterceptor.ts
@@ -47,6 +47,24 @@ export interface PaygSignupRequiredDetail {
category: string | null;
}
+/** Decodes JSON entitlement errors from file downloads before the session-refresh interceptor. */
+export async function normalizePaygError(error: unknown): Promise<void> {
+ if (!error || typeof error !== "object") return;
+ const response = (error as { response?: { status?: number; data?: unknown } })
+ .response;
+ if (!response || (response.status !== 401 && response.status !== 402)) return;
+ const data = response.data;
+ try {
+ if (data instanceof Blob && data.size <= 65_536) {
+ response.data = JSON.parse(await data.text());
+ } else if (typeof data === "string" && data.length <= 65_536) {
+ response.data = JSON.parse(data);
+ }
+ } catch {
+ // Non-JSON failures still belong to the normal HTTP error handler.
+ }
+}
+
/**
* Inspect an axios-style error and decide whether it's one of the known
* PAYG sentinels. Returns the kind, or {@code null} if it isn't.
@@ -138,7 +156,9 @@ export function handlePaygError(kind: PaygErrorKind, error: unknown): void {
try {
window.dispatchEvent(
new CustomEvent<PaygSignupRequiredDetail>("payg:signupRequired", {
- detail: { category },
+ detail: {
+ category,
+ },
}),
);
} catch {
diff --git a/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx b/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
index 2ea522610c..cf7ea78773 100644
--- a/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
+++ b/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
@@ -42,6 +42,10 @@ export interface OnboardingSlideShellProps {
/** "close" dismisses; "forward" advances, for a flow with no way out. Both call
* {@link onClose}; forward is drawn even when `allowDismiss` is false. */
headerControl?: "close" | "forward";
+ /** Standalone prompts supply their own dialog name instead of "Onboarding". */
+ ariaLabel?: string;
+ /** Prompts opened over a fullscreen editor must sit above that surface. */
+ zIndex?: number;
}
/**
@@ -82,6 +86,8 @@ export default function OnboardingSlideShell({
onClose,
allowDismiss = true,
headerControl = "close",
+ ariaLabel,
+ zIndex = Z_INDEX_ONBOARDING_CARD,
}: OnboardingSlideShellProps) {
const { t } = useTranslation();
const showProgress = stepCount > 1;
@@ -119,7 +125,7 @@ export default function OnboardingSlideShell({
centered
size="lg"
radius={20}
- zIndex={Z_INDEX_ONBOARDING_CARD}
+ zIndex={zIndex}
styles={{
body: { padding: 0, maxHeight: "90vh", overflow: "hidden" },
content: {
@@ -133,7 +139,7 @@ export default function OnboardingSlideShell({
<Modal.Overlay />
<Modal.Content
radius={20}
- aria-label={t("onboarding.dialogLabel", "Onboarding")}
+ aria-label={ariaLabel ?? t("onboarding.dialogLabel", "Onboarding")}
>
<Modal.Body>
<div className={styles.card}>
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
index ffa0c33c7f..f6630cdf9e 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
@@ -17,6 +17,7 @@ import { stripBasePath } from "@app/constants/app";
import { rememberSettingsOrigin } from "@app/utils/settingsNavigation";
import { canCreateProcessingFolders } from "@app/hooks/useProcessingFolderCreation";
import { requestProcessingFolderCreation } from "@app/utils/pendingProcessingFolderCreation";
+import { requestProcessorSignup } from "@app/services/processorSignup";
import { Icon } from "@app/ui/Icon";
const SIZE = "1.125rem";
@@ -114,12 +115,17 @@ export function QuickNavRailHost() {
label: t("quickNav.processor", "Processor"),
icon: <Icon name="cpu" size={SIZE} filled={inPortal} />,
current: inPortal,
- disabled: HAS_PORTAL && !inPortal && !host?.portalAccess,
+ disabled:
+ HAS_PORTAL && !inPortal && !host?.portalAccess && !host?.isAnonymous,
reason:
- HAS_PORTAL && !inPortal && !host?.portalAccess
+ HAS_PORTAL && !inPortal && !host?.portalAccess && !host?.isAnonymous
? t("quickNav.noProcessorAccess", "Ask an admin for processor access")
: undefined,
onClick: () => {
+ if (host?.isAnonymous) {
+ requestProcessorSignup();
+ return;
+ }
if (inPortal) {
returnHome();
return;
@@ -176,6 +182,10 @@ export function QuickNavRailHost() {
label: t("processingFolders.setup.title"),
icon: <Icon name="folder-plus" size={SIZE} />,
onClick: () => {
+ if (host?.isAnonymous) {
+ requestProcessorSignup();
+ return;
+ }
const open = host?.actions.current?.createProcessingFolder;
if (open) open();
else
diff --git a/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts b/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts
index 8b3169561d..27a3701bb6 100644
--- a/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts
+++ b/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts
@@ -8,7 +8,7 @@ import { useSigningBadgeState } from "@app/hooks/signing/useSigningBadgeCount";
/** Publishes resolved account fields from the mounted view into the root cache. */
export function useSyncQuickNavAccount(): void {
const updateAccount = useQuickNavHost()?.updateAccount;
- const { user, loading: authLoading } = useAuth();
+ const { user, isAnonymous, loading: authLoading } = useAuth();
const {
displayName,
profilePictureUrl,
@@ -22,6 +22,7 @@ export function useSyncQuickNavAccount(): void {
if (authLoading) return;
updateAccount?.({
accountId,
+ isAnonymous: Boolean(isAnonymous),
identity: identityLoading
? undefined
: { displayName, profilePictureUrl },
@@ -31,6 +32,7 @@ export function useSyncQuickNavAccount(): void {
}, [
updateAccount,
accountId,
+ isAnonymous,
authLoading,
identityLoading,
displayName,
diff --git a/frontend/editor/src/core/contexts/quickNavAccount.ts b/frontend/editor/src/core/contexts/quickNavAccount.ts
index f258e4b2a5..ed115613e0 100644
--- a/frontend/editor/src/core/contexts/quickNavAccount.ts
+++ b/frontend/editor/src/core/contexts/quickNavAccount.ts
@@ -6,6 +6,7 @@ export interface QuickNavIdentity {
/** The last resolved account data, retained across view changes. */
export interface QuickNavAccount {
accountId: string | null;
+ isAnonymous: boolean;
identity: QuickNavIdentity | null;
signingBadge: number;
portalAccess: boolean;
@@ -16,6 +17,7 @@ export type QuickNavAccountUpdate = Partial<QuickNavAccount>;
export const EMPTY_QUICK_NAV_ACCOUNT: QuickNavAccount = {
accountId: null,
+ isAnonymous: false,
identity: null,
signingBadge: 0,
portalAccess: false,
@@ -32,6 +34,7 @@ export function updateQuickNavAccount(
accountId === previous.accountId ? previous : EMPTY_QUICK_NAV_ACCOUNT;
const next: QuickNavAccount = {
accountId,
+ isAnonymous: update.isAnonymous ?? current.isAnonymous,
identity:
update.identity === undefined ? current.identity : update.identity,
signingBadge: update.signingBadge ?? current.signingBadge,
@@ -40,6 +43,7 @@ export function updateQuickNavAccount(
const unchanged =
next.accountId === previous.accountId &&
+ next.isAnonymous === previous.isAnonymous &&
next.signingBadge === previous.signingBadge &&
next.portalAccess === previous.portalAccess &&
next.identity?.displayName === previous.identity?.displayName &&
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts
index 15516ea290..7fcb4a9858 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts
@@ -42,6 +42,38 @@ beforeEach(() => {
});
describe("processFiles failure reporting", () => {
+ it("stops at a signup gate without labelling the files as failed", async () => {
+ const blocked = {
+ response: { status: 401, data: { error: "SIGNUP_REQUIRED" } },
+ };
+ post.mockRejectedValue(blocked);
+ await expect(run([file("a.pdf", "a"), file("b.pdf", "b")])).rejects.toBe(
+ blocked,
+ );
+ expect(post).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps successful batch outputs when a later input reaches the guest limit", async () => {
+ post.mockResolvedValueOnce({
+ data: new Blob(["ok"]),
+ status: 200,
+ headers: {},
+ });
+ post.mockRejectedValue({
+ response: { status: 401, data: { error: "SIGNUP_REQUIRED" } },
+ });
+ const result = await run([
+ file("a.pdf", "a"),
+ file("b.pdf", "b"),
+ file("c.pdf", "c"),
+ ]);
+ expect(result.outputFiles).toHaveLength(1);
+ expect(result.successSourceIds).toEqual(["a"]);
+ expect(result.failedInputs).toEqual([]);
+ expect(result.unprocessedSourceIds).toEqual(["b", "c"]);
+ expect(post).toHaveBeenCalledTimes(2);
+ });
+
it("names the failed input and keeps its error while the rest succeed", async () => {
expectConsole.error("[processFiles] Failed");
const boom = new Error("corrupted");
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
index c5c9246ef7..09313c6b35 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
@@ -8,6 +8,7 @@ import {
import { isEmptyOutput } from "@app/services/errorUtils";
import type { ProcessingProgress } from "@app/hooks/tools/shared/useToolState";
import type { StirlingFile, FileId } from "@app/types/fileContext";
+import { isSignupRequiredError } from "@app/utils/toolErrorHandler";
/** An input that did not survive the batch, with the error it failed on. */
export interface FailedInput {
@@ -39,12 +40,14 @@ export const useToolApiCalls = <TParams = void>() => {
outputFiles: File[];
successSourceIds: FileId[];
failedInputs: FailedInput[];
+ unprocessedSourceIds: FileId[];
}> => {
const processedFiles: File[] = [];
const successSourceIds: FileId[] = [];
// Kept with their errors: a batch where only some inputs fail still owes the caller a
// report for each one, and it cannot derive the kind without the error.
const failedInputs: FailedInput[] = [];
+ const unprocessedSourceIds: FileId[] = [];
const failedFiles: string[] = [];
const total = validFiles.length;
@@ -123,6 +126,13 @@ export const useToolApiCalls = <TParams = void>() => {
produced: responseFiles.length,
});
} catch (error) {
+ if (isSignupRequiredError(error)) {
+ if (processedFiles.length === 0) throw error;
+ unprocessedSourceIds.push(
+ ...validFiles.slice(i).map((input) => input.fileId),
+ );
+ break;
+ }
if (axios.isCancel(error)) {
throw new Error("Operation was cancelled", { cause: error });
}
@@ -164,6 +174,7 @@ export const useToolApiCalls = <TParams = void>() => {
outputFiles: processedFiles,
successSourceIds,
failedInputs,
+ unprocessedSourceIds,
};
},
[],
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
index c1fad547bb..06df6519b6 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
@@ -18,6 +18,7 @@ import { useToolResources } from "@app/hooks/tools/shared/useToolResources";
import {
extractErrorMessage,
handle422Error,
+ isSignupRequiredError,
} from "@app/utils/toolErrorHandler";
import {
StirlingFile,
@@ -47,6 +48,7 @@ import { ensureBackendReady } from "@app/services/backendReadinessGuard";
import { trackEditorOperation } from "@app/services/analytics";
import { useWillUseCloud } from "@app/hooks/useWillUseCloud";
import { useCreditCheck } from "@app/hooks/useCreditCheck";
+import { useToolRunComplete } from "@app/hooks/useToolRunComplete";
import { notifyPdfProcessingComplete } from "@app/services/desktopNotificationService";
import {
buildInputTracking,
@@ -135,6 +137,7 @@ export const useToolOperation = <TParams>(
const willUseCloud = useWillUseCloud(endpointString);
const continueResolutions = useResolutionContinuation();
const notificationsAvailable = useNotificationsAvailable();
+ const onToolRunComplete = useToolRunComplete();
// Track last operation for undo functionality
const lastOperationRef = useRef<{
@@ -319,6 +322,7 @@ export const useToolOperation = <TParams>(
assertFilesNotBlocked(policyIds);
let processedFiles: File[];
let successSourceIds: FileId[] = [];
+ let unprocessedSourceIds: FileId[] = [];
// Use original files directly (no PDF metadata injection - history stored in IndexedDB)
const filesForAPI = extractFiles(validFiles);
@@ -346,6 +350,7 @@ export const useToolOperation = <TParams>(
);
processedFiles = result.outputFiles;
successSourceIds = result.successSourceIds;
+ unprocessedSourceIds = result.unprocessedSourceIds;
// Reported here, not in the catch: this loop only throws when EVERY input failed,
// so a batch that lost one file to a bad PDF reaches the success path.
for (const failed of result.failedInputs) {
@@ -467,7 +472,7 @@ export const useToolOperation = <TParams>(
}
// Mark errors on inputs that didn't succeed
for (const id of allInputIds) {
- if (!okSet.has(id)) {
+ if (!okSet.has(id) && !unprocessedSourceIds.includes(id)) {
try {
fileActions.markFileError(id);
} catch (_e) {
@@ -483,7 +488,11 @@ export const useToolOperation = <TParams>(
// If backend told us which sources failed, prefer that mapping
successSourceIds = validFiles
.map((f) => f.fileId)
- .filter((id) => !externalErrorFileIds.includes(id));
+ .filter(
+ (id) =>
+ !externalErrorFileIds.includes(id) &&
+ !unprocessedSourceIds.includes(id),
+ );
// Also mark failed IDs immediately
try {
for (const badId of externalErrorFileIds) {
@@ -710,8 +719,13 @@ export const useToolOperation = <TParams>(
})),
});
}
+ onToolRunComplete();
}
} catch (error) {
+ if (isSignupRequiredError(error)) {
+ actions.setStatus("");
+ return;
+ }
try {
const handled = await handle422Error(error, (id) =>
fileActions.markFileError(id as FileId),
@@ -762,6 +776,7 @@ export const useToolOperation = <TParams>(
checkCredits,
continueResolutions,
notificationsAvailable,
+ onToolRunComplete,
reportFailure,
getCompatibleFiles,
],
diff --git a/frontend/editor/src/core/hooks/useChatAccess.ts b/frontend/editor/src/core/hooks/useChatAccess.ts
new file mode 100644
index 0000000000..dd1daca746
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useChatAccess.ts
@@ -0,0 +1,4 @@
+/** Returns a guard that permits opening chat or presents the account requirement. */
+export function useChatAccess(): () => boolean {
+ return () => true;
+}
diff --git a/frontend/editor/src/core/hooks/useToolRunComplete.ts b/frontend/editor/src/core/hooks/useToolRunComplete.ts
new file mode 100644
index 0000000000..b008f17884
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useToolRunComplete.ts
@@ -0,0 +1,4 @@
+/** Called once after a manual tool run saves its outputs, regardless of batch size. */
+export function useToolRunComplete(): () => void {
+ return () => {};
+}
diff --git a/frontend/editor/src/core/services/processorSignup.ts b/frontend/editor/src/core/services/processorSignup.ts
new file mode 100644
index 0000000000..36220abdb2
--- /dev/null
+++ b/frontend/editor/src/core/services/processorSignup.ts
@@ -0,0 +1,2 @@
+/** Builds with guest accounts override this to open their signup prompt without navigating. */
+export function requestProcessorSignup(): void {}
diff --git a/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx
index aec52300ca..2c94d29b97 100644
--- a/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx
+++ b/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx
@@ -63,6 +63,10 @@ vi.mock("../../services/apiClient", () => ({
// Import the mocked apiClient
import apiClient from "@app/services/apiClient";
const mockedApiClient = vi.mocked(apiClient);
+const onToolRunComplete = vi.hoisted(() => vi.fn());
+vi.mock("@app/hooks/useToolRunComplete", () => ({
+ useToolRunComplete: () => onToolRunComplete,
+}));
// Mock only essential services that are actually called by the tests
vi.mock("../../services/fileStorage", () => ({
@@ -348,6 +352,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
);
});
+ expect(onToolRunComplete).toHaveBeenCalledTimes(1);
expect(mockedApiClient.post).toHaveBeenCalledWith(
"/api/v1/convert/file/pdf",
expect.any(FormData),
diff --git a/frontend/editor/src/core/utils/toolErrorHandler.ts b/frontend/editor/src/core/utils/toolErrorHandler.ts
index 020283135b..ddbc9646a2 100644
--- a/frontend/editor/src/core/utils/toolErrorHandler.ts
+++ b/frontend/editor/src/core/utils/toolErrorHandler.ts
@@ -5,6 +5,15 @@
import axios from "axios";
import { normalizeAxiosErrorData } from "@app/services/errorUtils";
+/** Signup gates are handled by the account modal and must not be reported as damaged files. */
+export function isSignupRequiredError(error: unknown): boolean {
+ if (!error || typeof error !== "object") return false;
+ const response = (
+ error as { response?: { status?: number; data?: { error?: string } } }
+ ).response;
+ return response?.status === 401 && response.data?.error === "SIGNUP_REQUIRED";
+}
+
/**
* Default error extractor that follows the standard pattern.
*
diff --git a/frontend/editor/src/desktop/hooks/useWallet.ts b/frontend/editor/src/desktop/hooks/useWallet.ts
index 959b609a4c..10f8ea101c 100644
--- a/frontend/editor/src/desktop/hooks/useWallet.ts
+++ b/frontend/editor/src/desktop/hooks/useWallet.ts
@@ -12,6 +12,7 @@ export type {
} from "@cloud/hooks/useWallet";
/** Local and self-hosted backends do not provide cloud billing. */
-export function useWallet() {
- return useCloudWallet(useSaaSMode());
+export function useWallet(enabled = true) {
+ const saasMode = useSaaSMode();
+ return useCloudWallet(enabled && saasMode);
}
diff --git a/frontend/editor/src/proprietary/components/chat/ChatFAB.tsx b/frontend/editor/src/proprietary/components/chat/ChatFAB.tsx
index 490a7784cb..f1fce8fa45 100644
--- a/frontend/editor/src/proprietary/components/chat/ChatFAB.tsx
+++ b/frontend/editor/src/proprietary/components/chat/ChatFAB.tsx
@@ -18,6 +18,7 @@ import { ChatFABWindow } from "@app/ui/ChatFABWindow";
import { ChatPanel } from "@app/components/chat/ChatPanel";
import { useChat } from "@app/components/chat/ChatContext";
import { useAiEngineEnabled } from "@app/hooks/useAiEngineEnabled";
+import { useChatAccess } from "@app/hooks/useChatAccess";
import { Z_INDEX_CHAT_FAB_OVERLAY } from "@app/styles/zIndex";
import {
PANEL_WIDTH_PX,
@@ -51,6 +52,7 @@ export function ChatFAB() {
// Desktop sources this from the SaaS backend (cloud kill switch); web reads it
// from the local app-config. Either way the AI engine drives FAB visibility.
const enabled = useAiEngineEnabled();
+ const requestChatAccess = useChatAccess();
// Scope the panel's nested MantineProvider to this ref; unscoped it writes
// its color scheme onto <html> and overrides the whole app's theme.
@@ -188,6 +190,7 @@ export function ChatFAB() {
<ChatFABButton
className={`chat-fab-trigger${isOpen ? " chat-fab-trigger--hidden" : ""}`}
onClick={() => {
+ if (!requestChatAccess()) return;
// Fallback: ensure a position exists before opening, in case the
// layout effect measured before the overlay was laid out.
if (rndPos === null) {
diff --git a/frontend/editor/src/saas/components/GuestFeatureGates.test.tsx b/frontend/editor/src/saas/components/GuestFeatureGates.test.tsx
new file mode 100644
index 0000000000..cf0c3f7597
--- /dev/null
+++ b/frontend/editor/src/saas/components/GuestFeatureGates.test.tsx
@@ -0,0 +1,79 @@
+import { beforeEach, expect, it, vi } from "vitest";
+import { render, renderHook, screen } from "@testing-library/react";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+import { QuickNavRailNotifications } from "@app/components/shared/quickNav/QuickNavRailNotifications";
+
+const state = vi.hoisted(() => ({
+ user: { id: "guest" } as { id: string } | null,
+ loading: false,
+ isAnonymous: true,
+ accountId: "guest" as string | null,
+ subscribe: vi.fn(),
+}));
+
+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => state }));
+vi.mock("@app/contexts/QuickNavHostContext", () => ({
+ useQuickNavHost: () => state,
+}));
+vi.mock("@app/hooks/useNotifications", () => ({
+ useNotifications: () => {
+ state.subscribe();
+ return { unreadCount: 0 };
+ },
+}));
+vi.mock("@app/components/notifications/NotificationPanel", () => ({
+ NOTIFICATIONS_PANEL_ID: "notifications",
+}));
+vi.mock("@app/components/shared/quickNav/QuickNavRailBase", () => ({
+ RailButton: () => <button>Notifications</button>,
+}));
+vi.mock("@app/ui/Icon", () => ({ Icon: () => null }));
+
+beforeEach(() => {
+ state.user = { id: "guest" };
+ state.accountId = "guest";
+ state.loading = false;
+ state.isAnonymous = true;
+ state.subscribe.mockClear();
+});
+
+it("does not mount notification polling for a guest with a valid account ID", () => {
+ render(<QuickNavRailNotifications />);
+ expect(state.subscribe).not.toHaveBeenCalled();
+ expect(screen.queryByRole("button")).toBeNull();
+});
+
+it("starts notification polling after login and unmounts it on returning to a guest", () => {
+ const view = render(<QuickNavRailNotifications />);
+ state.isAnonymous = false;
+ view.rerender(<QuickNavRailNotifications />);
+ expect(state.subscribe).toHaveBeenCalledOnce();
+ expect(
+ screen.getByRole("button", { name: "Notifications" }),
+ ).toBeInTheDocument();
+ state.isAnonymous = true;
+ view.rerender(<QuickNavRailNotifications />);
+ expect(screen.queryByRole("button")).toBeNull();
+});
+
+it("does not start notification polling before account data has resolved", () => {
+ state.accountId = null;
+ state.isAnonymous = false;
+ render(<QuickNavRailNotifications />);
+ expect(state.subscribe).not.toHaveBeenCalled();
+});
+
+it("keeps the policy controller, including local classification, disabled until registered login", () => {
+ const { result, rerender } = renderHook(() => usePoliciesEnabled());
+ expect(result.current).toBe(false);
+ state.isAnonymous = false;
+ state.loading = true;
+ rerender();
+ expect(result.current).toBe(false);
+ state.loading = false;
+ rerender();
+ expect(result.current).toBe(true);
+ state.user = null;
+ rerender();
+ expect(result.current).toBe(false);
+});
diff --git a/frontend/editor/src/saas/components/SignupRequiredBootstrap.module.css b/frontend/editor/src/saas/components/SignupRequiredBootstrap.module.css
new file mode 100644
index 0000000000..970e065039
--- /dev/null
+++ b/frontend/editor/src/saas/components/SignupRequiredBootstrap.module.css
@@ -0,0 +1,58 @@
+.title {
+ margin: 0;
+ font: inherit;
+}
+
+.heroIcon {
+ color: var(--c-accent-fg);
+}
+
+.surfaces {
+ display: flex;
+ justify-content: center;
+ gap: 24px;
+ padding: 16px 0;
+}
+
+.surface {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--c-text);
+}
+
+.body {
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+}
+
+.benefits {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ color: var(--c-text);
+}
+
+.benefits li {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.benefitIcon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 34px;
+ height: 34px;
+ border-radius: 9px;
+ background: var(--c-primary-subtle);
+ color: var(--c-accent-fg);
+}
diff --git a/frontend/editor/src/saas/components/SignupRequiredBootstrap.test.tsx b/frontend/editor/src/saas/components/SignupRequiredBootstrap.test.tsx
new file mode 100644
index 0000000000..cb650ce0bd
--- /dev/null
+++ b/frontend/editor/src/saas/components/SignupRequiredBootstrap.test.tsx
@@ -0,0 +1,237 @@
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import SignupRequiredBootstrap from "@app/components/SignupRequiredBootstrap";
+import { ChatFAB } from "@app/components/chat/ChatFAB";
+import { useToolRunComplete } from "@app/hooks/useToolRunComplete";
+import { useProcessingFolderCreation } from "@app/hooks/useProcessingFolderCreation";
+import { QuickNavRailHost } from "@app/components/shared/quickNav/QuickNavRailHost";
+import type { QuickNavEntry } from "@app/components/shared/quickNav/QuickNavRailBase";
+
+const auth = vi.hoisted(() => ({
+ isAnonymous: true,
+ user: { id: "guest-signup-test" },
+}));
+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => auth }));
+vi.mock("@app/contexts/QuickNavHostContext", () => ({
+ useQuickNavHost: () => ({
+ appMounted: true,
+ isAnonymous: auth.isAnonymous,
+ portalAccess: false,
+ actions: { current: {} },
+ }),
+}));
+vi.mock("@app/ui/Icon", () => ({ Icon: () => null }));
+vi.mock("@app/components/chat/ChatContext", () => ({
+ useChat: () => ({ isLoading: false }),
+}));
+vi.mock("@app/components/chat/ChatPanel", () => ({ ChatPanel: () => null }));
+vi.mock("@app/components/policies/ProcessingFolderSetupFlow", () => ({
+ ProcessingFolderSetupFlow: () => <div>Processing folder wizard</div>,
+}));
+vi.mock("@app/hooks/useAiEngineEnabled", () => ({
+ useAiEngineEnabled: () => true,
+}));
+vi.mock("@app/components/shared/quickNav/QuickNavRailContainer", () => ({
+ QuickNavRailContainer: ({ groups }: { groups: QuickNavEntry[][] }) => (
+ <>
+ {groups.flat().map((entry) => (
+ <button
+ key={entry.id}
+ disabled={entry.disabled}
+ onClick={entry.onClick}
+ >
+ {entry.label}
+ </button>
+ ))}
+ </>
+ ),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback = key, options?: { count?: number }) =>
+ fallback.replace("{{count}}", String(options?.count ?? "")),
+ }),
+}));
+
+function Destination() {
+ const location = useLocation();
+ return (
+ <output data-testid="destination">
+ {location.pathname + location.search}
+ </output>
+ );
+}
+
+function GuestActions() {
+ const complete = useToolRunComplete();
+ const folder = useProcessingFolderCreation();
+ return (
+ <>
+ <button onClick={complete}>Complete tool run</button>
+ <button onClick={folder.open}>Landing page processing folder</button>
+ {folder.dialog}
+ </>
+ );
+}
+
+function renderPrompt(withRail = false, withChat = false, withActions = false) {
+ return render(
+ <MemoryRouter initialEntries={["/editor?tool=compress"]}>
+ <MantineProvider>
+ <SignupRequiredBootstrap />
+ {withRail && <QuickNavRailHost />}
+ {withChat && <ChatFAB />}
+ {withActions && <GuestActions />}
+ <Destination />
+ </MantineProvider>
+ </MemoryRouter>,
+ );
+}
+
+describe("guest signup prompt", () => {
+ beforeEach(() => {
+ auth.isAnonymous = true;
+ localStorage.clear();
+ });
+
+ it("opens the Processor signup modal from the enabled guest rail without navigating", async () => {
+ renderPrompt(true);
+ const processor = screen.getByRole("button", { name: "Processor" });
+ expect(processor).toBeEnabled();
+ fireEvent.click(processor);
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ expect(
+ screen.getByText("Create an account to unlock the best of Stirling"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("destination")).toHaveTextContent(
+ "/editor?tool=compress",
+ );
+ });
+
+ it("keeps Processor disabled for registered users without access", () => {
+ auth.isAnonymous = false;
+ renderPrompt(true);
+ expect(screen.getByRole("button", { name: "Processor" })).toBeDisabled();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("opens signup instead of the assistant for guests without navigating", async () => {
+ renderPrompt(false, true);
+ const assistant = screen.getByRole("button", {
+ name: "Open Stirling AI assistant",
+ });
+ fireEvent.click(assistant);
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ expect(assistant).toHaveAttribute("aria-expanded", "false");
+ expect(screen.getByTestId("destination")).toHaveTextContent(
+ "/editor?tool=compress",
+ );
+ });
+
+ it("opens the assistant without a signup prompt for registered users", () => {
+ auth.isAnonymous = false;
+ renderPrompt(false, true);
+ const assistant = screen.getByRole("button", {
+ name: "Open Stirling AI assistant",
+ });
+ fireEvent.click(assistant);
+ expect(assistant).toHaveAttribute("aria-expanded", "true");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("reminds after every two runs, permits dismissal and preserves the login destination", async () => {
+ renderPrompt(false, false, true);
+ const complete = screen.getByRole("button", { name: "Complete tool run" });
+ fireEvent.click(complete);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ fireEvent.click(complete);
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ fireEvent.click(complete);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ fireEvent.click(complete);
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Log in" }));
+ expect(screen.getByTestId("destination")).toHaveTextContent(
+ "/login?next=%2Feditor%3Ftool%3Dcompress",
+ );
+ });
+
+ it("prompts guests from the quick access processing folder action without navigating", async () => {
+ renderPrompt(true);
+ fireEvent.click(
+ screen.getByRole("button", { name: "processingFolders.setup.title" }),
+ );
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ expect(screen.getByTestId("destination")).toHaveTextContent(
+ "/editor?tool=compress",
+ );
+ });
+
+ it("prompts guests from landing-page folder creation without mounting setup", async () => {
+ renderPrompt(false, false, true);
+ fireEvent.click(
+ screen.getByRole("button", { name: "Landing page processing folder" }),
+ );
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Processing folder wizard"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("lets registered users open folder setup without a signup prompt", async () => {
+ auth.isAnonymous = false;
+ renderPrompt(false, false, true);
+ fireEvent.click(
+ screen.getByRole("button", { name: "Landing page processing folder" }),
+ );
+ expect(
+ await screen.findByText("Processing folder wizard"),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("promotes Processor and deduplicates simultaneous blocked requests", async () => {
+ renderPrompt();
+ act(() => {
+ for (let i = 0; i < 2; i++)
+ window.dispatchEvent(
+ new CustomEvent("payg:signupRequired", {
+ detail: { category: "AI" },
+ }),
+ );
+ });
+ expect(await screen.findAllByRole("dialog")).toHaveLength(1);
+ expect(
+ screen.getByText("Create an account to unlock the best of Stirling"),
+ ).toBeInTheDocument();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Create free account" }),
+ );
+ expect(screen.getByTestId("destination")).toHaveTextContent(
+ "/signup?next=%2Feditor%3Ftool%3Dcompress",
+ );
+ });
+
+ it("does not show a guest prompt for an upgraded account", () => {
+ auth.isAnonymous = false;
+ renderPrompt();
+ act(() =>
+ window.dispatchEvent(
+ new CustomEvent("payg:signupRequired", { detail: { category: "AI" } }),
+ ),
+ );
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/saas/components/SignupRequiredBootstrap.tsx b/frontend/editor/src/saas/components/SignupRequiredBootstrap.tsx
index 1dbe97801e..860f8b8ea0 100644
--- a/frontend/editor/src/saas/components/SignupRequiredBootstrap.tsx
+++ b/frontend/editor/src/saas/components/SignupRequiredBootstrap.tsx
@@ -1,125 +1,152 @@
-import { useEffect, useState, useMemo } from "react";
-import { Modal, Stack, Text } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import PersonAddIcon from "@mui/icons-material/PersonAdd";
+import { useEffect, useState } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+import { Icon } from "@app/ui/Icon";
+import OnboardingSlideShell, {
+ ShellHero,
+} from "@app/components/onboarding/OnboardingSlideShell";
+import styles from "@app/components/SignupRequiredBootstrap.module.css";
import { useTranslation } from "react-i18next";
-import { withBasePath } from "@app/constants/app";
+import { useAuth } from "@app/auth/UseSession";
+import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";
import type { PaygSignupRequiredDetail } from "@app/services/paygErrorInterceptor";
-/**
- * Bootstrap that listens for {@code payg:signupRequired} (dispatched by
- * the {@code apiClient} response interceptor when an anonymous user hits
- * a billable endpoint and the server returns {@code 401 SIGNUP_REQUIRED})
- * and opens a Mantine modal explaining the free monthly allowance
- * with a "Sign up free" CTA.
- *
- * <h2>Why an event bus instead of direct render</h2>
- * The {@code apiClient} module is created at app boot, outside the React
- * tree, and can't import JSX. We bridge with a {@code CustomEvent}: the
- * interceptor dispatches, this bootstrap (mounted near the app root)
- * listens and renders, driven by a request-side trigger.
- *
- * <h2>De-duping</h2>
- * If the user fires multiple billable requests in quick succession (e.g.
- * clicking a tool button twice), only one modal opens — the listener
- * ignores the event when the modal is already visible. The modal closes
- * on backdrop click or Escape; we don't gate it on a localStorage flag
- * because this is a deterministic "you need an account" UI, not a one-
- * time onboarding nudge.
- */
+/** Opens one guest signup prompt for a Processor click or server account gate, preserving the return route. */
export default function SignupRequiredBootstrap() {
const { t } = useTranslation();
- const [opened, setOpened] = useState(false);
- const [category, setCategory] = useState<string | null>(null);
+ const { isAnonymous } = useAuth();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const [detail, setDetail] = useState<PaygSignupRequiredDetail | null>(null);
useEffect(() => {
const handler = (ev: Event) => {
- const detail = (ev as CustomEvent<PaygSignupRequiredDetail>).detail;
- // De-dupe: if the modal is already open, the existing copy wins.
- // The user is already being prompted; piling another open call on
- // top would just flicker the same content.
- setOpened((wasOpen) => {
- if (!wasOpen) {
- setCategory(detail?.category ?? null);
- }
- return true;
- });
+ const incoming = (ev as CustomEvent<PaygSignupRequiredDetail>).detail;
+ setDetail((current) => current ?? incoming ?? { category: null });
};
window.addEventListener("payg:signupRequired", handler);
return () => window.removeEventListener("payg:signupRequired", handler);
}, []);
- // Map the server's gate categories to user-facing nouns. The server
- // returns the FeatureGate name (AI, AUTOMATION, API); the user has
- // no idea what those are in raw form, so we pretty-print here. The
- // fallback "this feature" keeps the modal sensible if the BE adds
- // a category we don't know about.
- const categoryNoun = useMemo(() => {
- switch ((category ?? "").toUpperCase()) {
- case "AI":
- return t("payg.signupRequired.category.ai", "AI features");
- case "AUTOMATION":
- return t("payg.signupRequired.category.automation", "automations");
- case "API":
- return t("payg.signupRequired.category.api", "this tool");
- default:
- return t("payg.signupRequired.category.default", "this feature");
- }
- }, [category, t]);
+ useEffect(() => {
+ if (!isAnonymous) setDetail(null);
+ }, [isAnonymous]);
- const handleSignUp = () => {
- window.location.href = withBasePath("/signup");
+ const authenticate = (path: "/signup" | "/login") => {
+ const next = location.pathname + location.search + location.hash;
+ setDetail(null);
+ navigate(
+ isSafePostLoginRedirect(next)
+ ? `${path}?next=${encodeURIComponent(next)}`
+ : path,
+ );
};
+ const title = t(
+ "payg.signupRequired.processorTitle",
+ "Create an account to unlock the best of Stirling",
+ );
+
return (
- <Modal
- opened={opened}
- onClose={() => setOpened(false)}
- withCloseButton
- centered
- size="md"
- radius="lg"
+ <OnboardingSlideShell
+ opened={detail !== null && isAnonymous}
+ onClose={() => setDetail(null)}
+ ariaLabel={title}
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
- title={
- <Text fw={700} size="lg">
- {t("payg.signupRequired.title", "Sign up to use {{category}}", {
- category: categoryNoun,
- })}
- </Text>
+ stepIndex={0}
+ stepCount={1}
+ slideKey="guest-signup"
+ hero={
+ <div className={styles.surfaces}>
+ <div className={styles.surface}>
+ <ShellHero>
+ <Icon name="book-open" size={32} className={styles.heroIcon} />
+ </ShellHero>
+ <span>{t("payg.signupRequired.readerLabel", "PDF Reader")}</span>
+ </div>
+ <div className={styles.surface}>
+ <ShellHero>
+ <Icon name="pencil" size={32} className={styles.heroIcon} />
+ </ShellHero>
+ <span>{t("payg.signupRequired.editorLabel", "PDF Editor")}</span>
+ </div>
+ <div className={styles.surface}>
+ <ShellHero>
+ <Icon name="cpu" size={32} className={styles.heroIcon} />
+ </ShellHero>
+ <span>
+ {t("payg.signupRequired.processorLabel", "PDF Processor")}
+ </span>
+ </div>
+ </div>
}
- >
- <Stack gap="md">
- <Text>
- {t(
- "payg.signupRequired.bodyMonthlyAllowance",
- "Stirling PDF gives every signed-up account a free monthly allowance for operations. You're currently using Stirling as a guest, which doesn't include billable tools like AI, automations, or hosted processing.",
- )}
- </Text>
- <Text size="sm" c="dimmed">
- {t(
- "payg.signupRequired.subtext",
- "Creating an account is free and takes a few seconds. No credit card required.",
- )}
- </Text>
- <div
- style={{
- display: "flex",
- justifyContent: "flex-end",
- gap: "0.5rem",
- }}
- >
- <Button variant="secondary" onClick={() => setOpened(false)}>
- {t("payg.signupRequired.cancel", "Not now")}
- </Button>
- <Button
- leftSection={<PersonAddIcon style={{ fontSize: 16 }} />}
- onClick={handleSignUp}
- >
- {t("payg.signupRequired.cta", "Sign up free")}
- </Button>
+ title={<h2 className={styles.title}>{title}</h2>}
+ body={
+ <div className={styles.body}>
+ <ul className={styles.benefits}>
+ <li>
+ <span className={styles.benefitIcon}>
+ <Icon name="file-text" size={18} />
+ </span>
+ <span>
+ {t(
+ "payg.signupRequired.manualToolsPromo",
+ "Unlimited free manual PDF tools",
+ )}
+ </span>
+ </li>
+ <li>
+ <span className={styles.benefitIcon}>
+ <Icon name="sparkles" size={18} />
+ </span>
+ <span>
+ {t(
+ "payg.signupRequired.aiPromo",
+ "Create, edit and ask about PDFs with AI",
+ )}
+ </span>
+ </li>
+ <li>
+ <span className={styles.benefitIcon}>
+ <Icon name="git-branch" size={18} />
+ </span>
+ <span>
+ {t(
+ "payg.signupRequired.automationPromo",
+ "Automate repetitive PDF tasks",
+ )}
+ </span>
+ </li>
+ <li>
+ <span className={styles.benefitIcon}>
+ <Icon name="code" size={18} />
+ </span>
+ <span>
+ {t(
+ "payg.signupRequired.apiPromo",
+ "Connect your apps and AI assistants",
+ )}
+ </span>
+ </li>
+ </ul>
</div>
- </Stack>
- </Modal>
+ }
+ buttons={[
+ {
+ key: "login",
+ label: t("payg.signupRequired.login", "Log in"),
+ action: "login",
+ },
+ {
+ key: "signup",
+ label: t("payg.signupRequired.createAccount", "Create free account"),
+ primary: true,
+ action: "signup",
+ },
+ ]}
+ onAction={(action) =>
+ authenticate(action === "login" ? "/login" : "/signup")
+ }
+ />
);
}
diff --git a/frontend/editor/src/saas/components/notifications/useNotificationsAvailable.ts b/frontend/editor/src/saas/components/notifications/useNotificationsAvailable.ts
new file mode 100644
index 0000000000..0f90fae620
--- /dev/null
+++ b/frontend/editor/src/saas/components/notifications/useNotificationsAvailable.ts
@@ -0,0 +1,7 @@
+import { useQuickNavHost } from "@app/contexts/QuickNavHostContext";
+
+/** The rail lives outside auth providers, so it reads the account published by the mounted app. */
+export function useNotificationsAvailable(): boolean {
+ const account = useQuickNavHost();
+ return Boolean(account?.accountId) && !account?.isAnonymous;
+}
diff --git a/frontend/editor/src/saas/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/saas/components/policies/usePoliciesEnabled.ts
new file mode 100644
index 0000000000..77ed999006
--- /dev/null
+++ b/frontend/editor/src/saas/components/policies/usePoliciesEnabled.ts
@@ -0,0 +1,7 @@
+import { useAuth } from "@app/auth/UseSession";
+
+/** Guests cannot load or run policies, including browser-side classification. */
+export function usePoliciesEnabled(): boolean {
+ const { user, loading, isAnonymous } = useAuth();
+ return !loading && Boolean(user) && !isAnonymous;
+}
diff --git a/frontend/editor/src/saas/hooks/useChatAccess.ts b/frontend/editor/src/saas/hooks/useChatAccess.ts
new file mode 100644
index 0000000000..0e2bbd423e
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useChatAccess.ts
@@ -0,0 +1,14 @@
+import { useAuth } from "@app/auth/UseSession";
+import { requestProcessorSignup } from "@app/services/processorSignup";
+
+/** Guests see the shared signup prompt; a false result means chat must stay closed. */
+export function useChatAccess(): () => boolean {
+ const { isAnonymous } = useAuth();
+ return () => {
+ if (isAnonymous) {
+ requestProcessorSignup();
+ return false;
+ }
+ return true;
+ };
+}
diff --git a/frontend/editor/src/saas/hooks/useFreeCreditsSummary.test.tsx b/frontend/editor/src/saas/hooks/useFreeCreditsSummary.test.tsx
new file mode 100644
index 0000000000..9ea08a6fdb
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useFreeCreditsSummary.test.tsx
@@ -0,0 +1,87 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useFreeCreditsSummary } from "@app/hooks/useFreeCreditsSummary";
+
+const state = vi.hoisted(() => ({ isAnonymous: true, loading: false }));
+const wallet = vi.hoisted(() => vi.fn(() => ({ wallet: null })));
+const cacheWrite = vi.hoisted(() => vi.fn());
+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => state }));
+vi.mock("@app/hooks/useWallet", () => ({ useWallet: wallet }));
+vi.mock("@app/services/navFooterCache", () => ({
+ readCachedCredits: () => ({ remaining: 1000, total: 1000 }),
+ writeCachedCredits: cacheWrite,
+}));
+
+describe("guest credit display", () => {
+ beforeEach(() => {
+ state.isAnonymous = true;
+ state.loading = false;
+ vi.clearAllMocks();
+ });
+
+ it("hides stale account credits and stops guest wallet polling", () => {
+ const { result } = renderHook(useFreeCreditsSummary);
+ expect(result.current).toBeNull();
+ expect(wallet).toHaveBeenCalledWith(false);
+ expect(cacheWrite).toHaveBeenCalledWith(null);
+ });
+
+ it("does not flash cached credits while authentication is loading", () => {
+ state.isAnonymous = false;
+ state.loading = true;
+ const { result } = renderHook(useFreeCreditsSummary);
+ expect(result.current).toBeNull();
+ expect(wallet).toHaveBeenCalledWith(false);
+ });
+
+ it("waits for the real allowance when a guest signs up", () => {
+ const { result, rerender } = renderHook(useFreeCreditsSummary);
+ state.isAnonymous = false;
+ rerender();
+ expect(result.current).toBeNull();
+ expect(wallet).toHaveBeenLastCalledWith(true);
+ });
+
+ it("restores cached credits when loading resolves to a registered user", () => {
+ state.isAnonymous = false;
+ state.loading = true;
+ const { result, rerender } = renderHook(useFreeCreditsSummary);
+ expect(result.current).toBeNull();
+
+ state.loading = false;
+ rerender();
+ expect(result.current).toEqual({ remaining: 1000, total: 1000 });
+ expect(wallet).toHaveBeenLastCalledWith(true);
+ });
+
+ it("discards the loading seed when auth resolves to a guest, including after signup", () => {
+ state.isAnonymous = false;
+ state.loading = true;
+ const { result, rerender } = renderHook(useFreeCreditsSummary);
+
+ state.loading = false;
+ state.isAnonymous = true;
+ rerender();
+ expect(result.current).toBeNull();
+ expect(cacheWrite).toHaveBeenCalledWith(null);
+
+ state.isAnonymous = false;
+ rerender();
+ expect(result.current).toBeNull();
+ expect(wallet).toHaveBeenLastCalledWith(true);
+ });
+
+ it("does not revive a registered user's cached credits after a guest session", () => {
+ state.isAnonymous = false;
+ const { result, rerender } = renderHook(useFreeCreditsSummary);
+ expect(result.current).toEqual({ remaining: 1000, total: 1000 });
+
+ state.isAnonymous = true;
+ rerender();
+ expect(result.current).toBeNull();
+
+ state.isAnonymous = false;
+ rerender();
+ expect(result.current).toBeNull();
+ });
+});
diff --git a/frontend/editor/src/saas/hooks/useOtherAppSwitch.ts b/frontend/editor/src/saas/hooks/useOtherAppSwitch.ts
index e97d4d0ed3..2b43c0cf2a 100644
--- a/frontend/editor/src/saas/hooks/useOtherAppSwitch.ts
+++ b/frontend/editor/src/saas/hooks/useOtherAppSwitch.ts
@@ -4,6 +4,8 @@ import { useNavigationActions } from "@app/contexts/NavigationContext";
import { PORTAL_BASENAME } from "@app/routes/portalBasename";
import { saveEditorReturnPath } from "@app/services/workbenchSession";
import { type NavFooterAppLink } from "@app/components/shared/navFooter/NavFooter";
+import { useAuth } from "@app/auth/UseSession";
+import { requestProcessorSignup } from "@app/services/processorSignup";
/**
* SaaS: the editor's Supabase context never fetches /me, so processor access
@@ -12,8 +14,10 @@ import { type NavFooterAppLink } from "@app/components/shared/navFooter/NavFoote
*/
export function useOtherAppSwitch(): NavFooterAppLink | null {
const portalAccess = usePortalAccess();
+ const { isAnonymous } = useAuth();
const navigate = useNavigate();
const { actions } = useNavigationActions();
+ if (isAnonymous) return { app: "processor", onOpen: requestProcessorSignup };
if (!portalAccess) return null;
return {
app: "processor",
diff --git a/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx b/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx
index e2cfe08214..1d92cce422 100644
--- a/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx
+++ b/frontend/editor/src/saas/hooks/usePortalAccess.test.tsx
@@ -6,10 +6,12 @@ import {
} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
+import { qk } from "@app/query/keys";
const get = vi.fn();
let currentUserId: string | null = null;
let authLoading = false;
+let isAnonymous = false;
vi.mock("@app/services/apiClient", () => ({
default: {
@@ -21,6 +23,7 @@ vi.mock("@app/auth/UseSession", () => ({
useAuth: () => ({
user: currentUserId ? { id: currentUserId } : null,
loading: authLoading,
+ isAnonymous,
}),
}));
@@ -51,6 +54,7 @@ describe("usePortalAccess", () => {
get.mockReset();
currentUserId = null;
authLoading = false;
+ isAnonymous = false;
client = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
});
@@ -65,6 +69,22 @@ describe("usePortalAccess", () => {
await waitFor(() => expect(result.current).toBe(true));
});
+ it("skips the access request for guests even with cached access, then queries after signup", async () => {
+ currentUserId = "guest-1";
+ isAnonymous = true;
+ client.setQueryData(qk.portalAccess(currentUserId), true);
+ get.mockResolvedValue(meReturning(true));
+
+ const { result, rerender } = renderHook(() => usePortalAccessState());
+ expect(result.current).toEqual({ granted: false, settled: true });
+ expect(get).not.toHaveBeenCalled();
+
+ isAnonymous = false;
+ rerender();
+ await waitFor(() => expect(result.current.granted).toBe(true));
+ expect(get).toHaveBeenCalledOnce();
+ });
+
it("does not report a settled denial while the incoming session is loading", async () => {
authLoading = true;
const { result, rerender } = renderHook(() => usePortalAccessState());
diff --git a/frontend/editor/src/saas/hooks/usePortalAccess.ts b/frontend/editor/src/saas/hooks/usePortalAccess.ts
index c090d36ded..5b7de6f542 100644
--- a/frontend/editor/src/saas/hooks/usePortalAccess.ts
+++ b/frontend/editor/src/saas/hooks/usePortalAccess.ts
@@ -37,8 +37,9 @@ async function fetchPortalAccess(): Promise<boolean> {
* instead of appearing a request later. Guests skip the request entirely.
*/
export function usePortalAccessState(): PortalAccessState {
- const { user, loading } = useAuth();
+ const { user, loading, isAnonymous } = useAuth();
const userId = user?.id ?? null;
+ const canQuery = !loading && userId !== null && !isAnonymous;
// The query cache is per-tree and per-load, so it can't help a cold start or
// the hop into the processor, which mounts its own client. Seed from the last
// answer this browser saw so the switcher and the footer's "Open ..." row are
@@ -49,7 +50,7 @@ export function usePortalAccessState(): PortalAccessState {
queryKey: qk.portalAccess(userId),
queryFn: fetchPortalAccess,
// Signed out: nothing to ask, and any previous answer is void.
- enabled: userId !== null,
+ enabled: canQuery,
// Backend unreachable or guest (401) means no access now; a later refetch
// asks again rather than trusting the failure.
retry: false,
@@ -60,15 +61,15 @@ export function usePortalAccessState(): PortalAccessState {
useEffect(() => {
// Only a real answer is recorded — a failed probe is not one, so the next
// mount trusts the last backend response rather than a network blip.
- if (isSuccess && data !== undefined) writeCachedOtherApp(data);
- }, [isSuccess, data]);
+ if (canQuery && isSuccess && data !== undefined) writeCachedOtherApp(data);
+ }, [canQuery, isSuccess, data]);
// A signed-out user has nothing to look up, so that answer is settled at
// once. Otherwise the seeded value is a guess until the probe comes back -
// callers that hide UI on "no access" must not act on the guess.
return {
- granted: userId !== null && data === true,
- settled: !loading && (userId === null || (isFetched && !isFetching)),
+ granted: canQuery && data === true,
+ settled: !loading && (!canQuery || (isFetched && !isFetching)),
};
}
diff --git a/frontend/editor/src/saas/hooks/useProcessingFolderCreation.tsx b/frontend/editor/src/saas/hooks/useProcessingFolderCreation.tsx
new file mode 100644
index 0000000000..0c1690549b
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useProcessingFolderCreation.tsx
@@ -0,0 +1,15 @@
+import { useProcessingFolderCreation as useBaseProcessingFolderCreation } from "@proprietary/hooks/useProcessingFolderCreation";
+import { useAuth } from "@app/auth/UseSession";
+import { requestProcessorSignup } from "@app/services/processorSignup";
+
+export { canCreateProcessingFolders } from "@proprietary/hooks/useProcessingFolderCreation";
+export type { ProcessingFolderCreation } from "@proprietary/hooks/useProcessingFolderCreation";
+
+/** Both landing-page and editor actions require an account before mounting the setup wizard. */
+export function useProcessingFolderCreation() {
+ const { isAnonymous } = useAuth();
+ const creation = useBaseProcessingFolderCreation();
+ return isAnonymous
+ ? { open: requestProcessorSignup, dialog: null }
+ : creation;
+}
diff --git a/frontend/editor/src/saas/hooks/useToolRunComplete.test.ts b/frontend/editor/src/saas/hooks/useToolRunComplete.test.ts
new file mode 100644
index 0000000000..f2870e46a6
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useToolRunComplete.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useToolRunComplete } from "@app/hooks/useToolRunComplete";
+
+const auth = vi.hoisted(() => ({ isAnonymous: true, user: { id: "guest-a" } }));
+const signup = vi.hoisted(() => vi.fn());
+vi.mock("@app/auth/UseSession", () => ({ useAuth: () => auth }));
+vi.mock("@app/services/processorSignup", () => ({
+ requestProcessorSignup: signup,
+}));
+
+describe("tool completion signup reminders", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ signup.mockClear();
+ auth.isAnonymous = true;
+ auth.user = { id: "guest-a" };
+ });
+
+ it("does not track registered users", () => {
+ auth.isAnonymous = false;
+ const { result } = renderHook(useToolRunComplete);
+ act(() => {
+ result.current();
+ result.current();
+ });
+ expect(signup).not.toHaveBeenCalled();
+ expect(localStorage.length).toBe(0);
+ });
+
+ it("does not prompt when a guest upgrades during a run", () => {
+ const { result, rerender } = renderHook(useToolRunComplete);
+ const completeInFlight = result.current;
+ auth.isAnonymous = false;
+ rerender();
+ act(() => {
+ completeInFlight();
+ completeInFlight();
+ });
+ expect(signup).not.toHaveBeenCalled();
+ expect(localStorage.length).toBe(0);
+ });
+
+ it("does not attribute an old account's run to a new guest", () => {
+ const { result, rerender } = renderHook(useToolRunComplete);
+ const completeInFlight = result.current;
+ auth.user = { id: "guest-b" };
+ rerender();
+ act(() => completeInFlight());
+ expect(localStorage.length).toBe(0);
+ });
+});
diff --git a/frontend/editor/src/saas/hooks/useToolRunComplete.ts b/frontend/editor/src/saas/hooks/useToolRunComplete.ts
new file mode 100644
index 0000000000..276b5d2056
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useToolRunComplete.ts
@@ -0,0 +1,17 @@
+import { useCallback, useRef } from "react";
+import { useAuth } from "@app/auth/UseSession";
+import { recordGuestToolRun } from "@app/services/guestToolReminder";
+import { requestProcessorSignup } from "@app/services/processorSignup";
+
+/** Counts completed manual runs for the same guest session and offers a dismissible signup reminder. */
+export function useToolRunComplete(): () => void {
+ const { isAnonymous, user } = useAuth();
+ const guestId = isAnonymous ? user?.id : undefined;
+ const currentGuestId = useRef(guestId);
+ currentGuestId.current = guestId;
+
+ return useCallback(() => {
+ if (!guestId || currentGuestId.current !== guestId) return;
+ if (recordGuestToolRun(guestId)) requestProcessorSignup();
+ }, [guestId]);
+}
diff --git a/frontend/editor/src/saas/services/apiClient.ts b/frontend/editor/src/saas/services/apiClient.ts
index a2738efaa4..3e06d4f42a 100644
--- a/frontend/editor/src/saas/services/apiClient.ts
+++ b/frontend/editor/src/saas/services/apiClient.ts
@@ -3,6 +3,7 @@ import { supabase } from "@app/auth/supabase";
import { handleHttpError } from "@app/services/httpErrorHandler";
import {
classifyPaygError,
+ normalizePaygError,
handlePaygError,
} from "@app/services/paygErrorInterceptor";
import { stripBasePath, withBasePath } from "@app/constants/app";
@@ -159,6 +160,7 @@ apiClient.interceptors.response.use(
// - The handleHttpError() generic toast at the bottom won't fire.
// The error itself is still propagated to the caller so any
// component-level catch can react if needed.
+ await normalizePaygError(error);
const paygKind = classifyPaygError(error);
if (paygKind !== null) {
handlePaygError(paygKind, error);
diff --git a/frontend/editor/src/saas/services/guestToolReminder.test.ts b/frontend/editor/src/saas/services/guestToolReminder.test.ts
new file mode 100644
index 0000000000..092f555a7f
--- /dev/null
+++ b/frontend/editor/src/saas/services/guestToolReminder.test.ts
@@ -0,0 +1,45 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { recordGuestToolRun } from "@app/services/guestToolReminder";
+
+describe("guest tool signup reminders", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("reminds every two runs without exhausting an allowance", () => {
+ expect(
+ Array.from({ length: 6 }, () => recordGuestToolRun("cadence")),
+ ).toEqual([false, true, false, true, false, true]);
+ });
+
+ it("persists the cadence across a fresh module load", async () => {
+ expect(recordGuestToolRun("reload")).toBe(false);
+ vi.resetModules();
+ const reloaded = await import("@app/services/guestToolReminder");
+ expect(reloaded.recordGuestToolRun("reload")).toBe(true);
+ });
+
+ it("keeps guest accounts separate", () => {
+ expect(recordGuestToolRun("first")).toBe(false);
+ expect(recordGuestToolRun("second")).toBe(false);
+ expect(recordGuestToolRun("first")).toBe(true);
+ });
+
+ it("ignores invalid stored counts", () => {
+ localStorage.setItem("stirling:guest-tool-reminder:invalid", "broken");
+ expect(recordGuestToolRun("invalid")).toBe(false);
+ expect(recordGuestToolRun("invalid")).toBe(true);
+ });
+
+ it("falls back to this tab when storage is unavailable", () => {
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("full");
+ });
+ expect(recordGuestToolRun("no-storage")).toBe(false);
+ expect(recordGuestToolRun("no-storage")).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/saas/services/guestToolReminder.ts b/frontend/editor/src/saas/services/guestToolReminder.ts
new file mode 100644
index 0000000000..0be3860c39
--- /dev/null
+++ b/frontend/editor/src/saas/services/guestToolReminder.ts
@@ -0,0 +1,25 @@
+/** Successful manual runs between dismissible signup reminders; this is not an execution limit. */
+export const GUEST_SIGNUP_REMINDER_INTERVAL = 2;
+
+const pendingRuns = new Map<string, number>();
+
+/** Browser-local, best-effort cadence per guest. Storage failures never block processing. */
+export function recordGuestToolRun(userId: string): boolean {
+ const key = `stirling:guest-tool-reminder:${userId}`;
+ let count = pendingRuns.get(key) ?? 0;
+ try {
+ const stored = localStorage.getItem(key);
+ const parsed = stored === null ? 0 : Number(stored);
+ count = Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : 0;
+ } catch {
+ // Keep the reminder working in this tab when browser storage is unavailable.
+ }
+ const next = (count + 1) % GUEST_SIGNUP_REMINDER_INTERVAL;
+ pendingRuns.set(key, next);
+ try {
+ localStorage.setItem(key, String(next));
+ } catch {
+ // The in-memory count remains available without making tool success depend on storage.
+ }
+ return next === 0;
+}
diff --git a/frontend/editor/src/saas/services/paygErrorInterceptor.test.ts b/frontend/editor/src/saas/services/paygErrorInterceptor.test.ts
index a260ddbcd1..0e7883cd77 100644
--- a/frontend/editor/src/saas/services/paygErrorInterceptor.test.ts
+++ b/frontend/editor/src/saas/services/paygErrorInterceptor.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { Blob as NodeBlob } from "node:buffer";
import {
FREE_LIMIT_MODAL_EVENT,
@@ -9,8 +10,60 @@ import {
extractSignupCategory,
extractSubscribed,
handlePaygError,
+ normalizePaygError,
} from "@app/services/paygErrorInterceptor";
+describe("download entitlement errors", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("recognises a signup-required JSON Blob before session refresh", async () => {
+ vi.stubGlobal("Blob", NodeBlob);
+ const error = {
+ response: {
+ status: 401,
+ data: new NodeBlob(
+ [
+ JSON.stringify({
+ error: "SIGNUP_REQUIRED",
+ category: "AI",
+ }),
+ ],
+ { type: "application/json" },
+ ),
+ },
+ };
+ await normalizePaygError(error);
+ expect(classifyPaygError(error)).toBe("SIGNUP_REQUIRED");
+ const listener = vi.fn();
+ window.addEventListener("payg:signupRequired", listener);
+ try {
+ handlePaygError("SIGNUP_REQUIRED", error);
+ expect(listener.mock.calls[0][0].detail).toEqual({
+ category: "AI",
+ });
+ } finally {
+ window.removeEventListener("payg:signupRequired", listener);
+ }
+ });
+
+ it("leaves non-JSON authentication errors for the existing handler", async () => {
+ vi.stubGlobal("Blob", NodeBlob);
+ const data = new NodeBlob(["Unauthorized"]);
+ const error = { response: { status: 401, data } };
+ await normalizePaygError(error);
+ expect(error.response.data).toBe(data);
+ expect(classifyPaygError(error)).toBeNull();
+ });
+
+ it("also recognises string JSON and keeps ordinary failures unchanged", async () => {
+ const error = {
+ response: { status: 402, data: '{"error":"FEATURE_DEGRADED"}' },
+ };
+ await normalizePaygError(error);
+ expect(classifyPaygError(error)).toBe("FEATURE_DEGRADED");
+ });
+});
+
describe("classifyPaygError", () => {
it("returns FEATURE_DEGRADED for 402 + error sentinel", () => {
const err = {
diff --git a/frontend/editor/src/saas/services/processorSignup.ts b/frontend/editor/src/saas/services/processorSignup.ts
new file mode 100644
index 0000000000..62c66709ee
--- /dev/null
+++ b/frontend/editor/src/saas/services/processorSignup.ts
@@ -0,0 +1,10 @@
+import type { PaygSignupRequiredDetail } from "@app/services/paygErrorInterceptor";
+
+/** Opens the shared Processor signup prompt while preserving the current editor session. */
+export function requestProcessorSignup(): void {
+ window.dispatchEvent(
+ new CustomEvent<PaygSignupRequiredDetail>("payg:signupRequired", {
+ detail: { category: "PROCESSOR" },
+ }),
+ );
+}