Skip to content

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

Meter and enforce the free tier on an unlinked instance (#7931)

ConnorYohf59663170d27
diff --git a/app/.env.proprietary b/app/.env.proprietary
index 4e30318e57..b608beaf1c 100644
--- a/app/.env.proprietary
+++ b/app/.env.proprietary
@@ -1,8 +1,10 @@
# Committed defaults for `task backend:dev:proprietary` (self-hosted / proprietary
# flavor). Local overrides + secrets live in app/.env.proprietary.local (ignored).
-# Combined-billing account link (Mode A). Feature-flagged: OFF until release.
-# Flip to true in app/.env.proprietary.local to test linking locally.
-STIRLING_BILLING_ACCOUNT_LINK_ENABLED=false
+# Combined-billing account link (Mode A). On by default: the free tier is metered locally and
+# needs no Stirling account, so this gates linking rather than the feature.
+STIRLING_BILLING_ACCOUNT_LINK_ENABLED=true
# SaaS base URL the linked instance calls (register + entitlement).
-STIRLING_BILLING_ACCOUNT_LINK_SAAS_BASE_URL=https://stirling.com/app
+STIRLING_BILLING_ACCOUNT_LINK_SAAS_BASE_URL=https://api2.stirling.com
+# Accrual against a linked team's cloud wallet. The local free-tier meter runs either way.
+STIRLING_BILLING_ACCOUNT_LINK_METERING_ENABLED=true
diff --git a/app/core/src/main/resources/application.properties b/app/core/src/main/resources/application.properties
index f2a0d17e4d..9648f6dab2 100644
--- a/app/core/src/main/resources/application.properties
+++ b/app/core/src/main/resources/application.properties
@@ -113,3 +113,8 @@ v2=true
spring.mail.properties.mail.smtp.connectiontimeout=10000
spring.mail.properties.mail.smtp.timeout=30000
spring.mail.properties.mail.smtp.writetimeout=30000
+
+# The free tier is metered locally and needs no Stirling account, so combined billing is on by
+# default. AccountLinkProperties defaults the same way, but a field default never reaches the
+# Environment, and ConfigController reads this key from there to tell the UI linking is possible.
+stirling.billing.account-link.enabled=true
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
index 921bb1c3c0..1563e63a9d 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java
@@ -28,7 +28,10 @@ import tools.jackson.databind.node.ObjectNode;
@Slf4j
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class AccountLinkClient {
static final String HEADER_DEVICE_ID = "X-Device-Id";
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
index b1826b7cca..bac0e7d39b 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
@@ -20,19 +20,28 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
-/** Same-origin account-link surface on the self-hosted instance (combined billing). */
+/**
+ * Same-origin account-link surface on the self-hosted instance (combined billing).
+ *
+ * <p>Admin-only class-wide: everything here is server-scoped, the free-tier meter included. A
+ * non-admin learns of the wall from the {@code reason} on the 402, not from here.
+ */
@Slf4j
@Hidden
@RestController
@RequestMapping("/api/v1/account-link")
@Profile("!saas")
@PreAuthorize("hasRole('ADMIN')")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class AccountLinkController {
private final AccountLinkService service;
private final ConnectService connectService;
private final LocalUsageService localUsageService;
+ private final FreeTierUsageService freeTierUsageService;
// Present only when metering is on (its own flag); absent → /sync-now reports 409.
private final ObjectProvider<UsageSyncService> syncServiceProvider;
@@ -40,10 +49,12 @@ public class AccountLinkController {
AccountLinkService service,
ConnectService connectService,
LocalUsageService localUsageService,
+ FreeTierUsageService freeTierUsageService,
ObjectProvider<UsageSyncService> syncServiceProvider) {
this.service = service;
this.connectService = connectService;
this.localUsageService = localUsageService;
+ this.freeTierUsageService = freeTierUsageService;
this.syncServiceProvider = syncServiceProvider;
}
@@ -155,6 +166,15 @@ public class AccountLinkController {
return ResponseEntity.ok(localUsageService.currentPeriodUnsynced());
}
+ /**
+ * The instance's own monthly grant. Reported even while linked, where it is dormant but is what
+ * unlinking resumes on.
+ */
+ @GetMapping("/free-tier")
+ public ResponseEntity<FreeTierUsageService.FreeTierBalance> freeTier() {
+ return ResponseEntity.ok(freeTierUsageService.balance());
+ }
+
/** Forces an immediate usage sync to SaaS — the same work the daily scheduler does. */
@PostMapping("/sync-now")
public ResponseEntity<Void> syncNow() {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java
index 619aa10e86..996a6287b6 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java
@@ -8,15 +8,22 @@ import org.springframework.stereotype.Component;
import lombok.Getter;
import lombok.Setter;
-/** Self-hosted side of combined billing: this instance bills through a linked SaaS team. */
+/**
+ * Self-hosted side of combined billing: the instance's own free tier, plus the optional link.
+ *
+ * <p>Unconditional, so the grant size is readable before any gated bean exists.
+ */
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "stirling.billing.account-link")
public class AccountLinkProperties {
- /** Master switch. */
- private boolean enabled = false;
+ /**
+ * Kill switch for combined billing, free tier included. On by default: the free tier is the
+ * instance's own allowance, not an opt-in. Off runs every billable op unmetered.
+ */
+ private boolean enabled = true;
/** Base URL of the SaaS backend this instance links to (register + entitlement live there). */
private String saasBaseUrl = "https://stirling.com/app";
@@ -27,12 +34,18 @@ public class AccountLinkProperties {
/** Connect/read timeout for the outbound SaaS calls. */
private int requestTimeoutSeconds = 10;
+ /**
+ * Units granted each month while unlinked. Matches the SaaS default policy, so linking raises
+ * the allowance rather than introducing one. 0 means billable work needs a link.
+ */
+ private long freeTierUnits = 500;
+
/** Phase 2 usage metering + daily sync. */
private final Metering metering = new Metering();
/**
- * Separate from {@link #enabled} so linking can be exercised without billing anything. Both
- * default off, and metering needs the master flag as well.
+ * The <em>cloud</em> ledger only. Local free-tier accrual is deliberately not gated here, or
+ * the grant could not be enforced.
*/
@Getter
@Setter
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java
index e1283d83ba..a4746cf034 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java
@@ -12,7 +12,10 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class AccountLinkService {
private final AccountLinkClient client;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java
index 8c20abfa11..6d925e9dda 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java
@@ -13,10 +13,16 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
*
* <p>Whole config is gated behind {@code stirling.billing.account-link.enabled} +
* {@code @Profile("!saas")}; absent when off, so no interceptor is registered.
+ *
+ * <p>A desktop bundle registers nothing either: desktop work belongs to the server it connects to,
+ * not to the backend Tauri runs in-process.
*/
@Configuration
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class AccountLinkWebMvcConfig implements WebMvcConfigurer {
private final InstanceEntitlementInterceptor gateInterceptor;
@@ -27,10 +33,21 @@ public class AccountLinkWebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
+ if (isDesktopBundle()) {
+ return;
+ }
// AI surface is always billable; the broad /api/v1/** catch lets automation-marked manual
// calls be gated too, while the interceptor lets genuine manual tools through.
registry.addInterceptor(gateInterceptor)
.addPathPatterns("/api/v1/**")
.excludePathPatterns("/api/v1/account-link/**");
}
+
+ /**
+ * Matches {@code FolderAccessGuard.isDesktopBundle()}: only the Tauri build sets this, and a
+ * {@code Client-*} machine type is not accepted because any server can present one.
+ */
+ private static boolean isDesktopBundle() {
+ return Boolean.parseBoolean(System.getProperty("STIRLING_PDF_TAURI_MODE", "false"));
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java
index 978d6d494e..80c6ed5981 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/ConnectService.java
@@ -25,7 +25,10 @@ import stirling.software.common.model.ApplicationProperties;
@Slf4j
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class ConnectService {
/** Frontend route that consumes the callback fragment. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java
index 33658a48c6..981554b699 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java
@@ -16,7 +16,10 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class DeviceCredentialStore {
private final DeviceCredentialRepository repo;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java
index 898fb54b3a..ef459e8248 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java
@@ -23,7 +23,10 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class EntitlementCache {
private final DeviceCredentialStore credentialStore;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierPeriod.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierPeriod.java
new file mode 100644
index 0000000000..3fb9531a25
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierPeriod.java
@@ -0,0 +1,62 @@
+package stirling.software.proprietary.accountlink;
+
+import java.time.LocalDateTime;
+
+import org.springframework.data.domain.Persistable;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.Transient;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+/**
+ * Singleton row anchoring an unlinked instance's own monthly period. Written only by {@link
+ * FreeTierUsageService}.
+ *
+ * <p>{@link #anchorAt} never moves: deriving each start from the <em>previous</em> one would walk a
+ * 31st anchor permanently down to the 28th.
+ */
+@Entity
+@Table(name = "account_link_free_tier_period")
+@Getter
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
+public class FreeTierPeriod implements Persistable<Long> {
+
+ public static final long SINGLETON_ID = 1L;
+
+ @Id private Long id;
+
+ @Column(name = "anchor_at", nullable = false)
+ private LocalDateTime anchorAt;
+
+ /** Inclusive, always {@code anchorAt} plus a whole month count. */
+ @Column(name = "period_start", nullable = false)
+ private LocalDateTime periodStart;
+
+ @Column(name = "updated_at", nullable = false)
+ private LocalDateTime updatedAt;
+
+ @Transient private boolean unsaved;
+
+ public FreeTierPeriod(LocalDateTime anchorAt) {
+ this.id = SINGLETON_ID;
+ this.anchorAt = anchorAt;
+ this.periodStart = anchorAt;
+ this.updatedAt = anchorAt;
+ this.unsaved = true;
+ }
+
+ /**
+ * Forces an insert. The id is assigned, so Spring Data would otherwise read a new instance as
+ * detached and merge it, overwriting a live anchor instead of losing the race for it.
+ */
+ @Override
+ public boolean isNew() {
+ return unsaved;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierPeriodRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierPeriodRepository.java
new file mode 100644
index 0000000000..a9d6b4d84d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierPeriodRepository.java
@@ -0,0 +1,28 @@
+package stirling.software.proprietary.accountlink;
+
+import java.time.LocalDateTime;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+import org.springframework.transaction.annotation.Transactional;
+
+public interface FreeTierPeriodRepository extends JpaRepository<FreeTierPeriod, Long> {
+
+ /**
+ * Advances the stored period stamp. The {@code <} guard makes the roll monotonic and idempotent
+ * under concurrency: two threads that notice the same boundary compute the same new start, so
+ * the loser's update is a no-op rather than a lost write, and a stale thread can never drag the
+ * stamp backwards onto a period whose counters are already spent.
+ */
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE FreeTierPeriod p SET p.periodStart = :periodStart, p.updatedAt = :now"
+ + " WHERE p.id = :id AND p.periodStart < :periodStart")
+ int rollTo(
+ @Param("id") long id,
+ @Param("periodStart") LocalDateTime periodStart,
+ @Param("now") LocalDateTime now);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageCounter.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageCounter.java
new file mode 100644
index 0000000000..736114c324
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageCounter.java
@@ -0,0 +1,63 @@
+package stirling.software.proprietary.accountlink;
+
+import java.time.LocalDateTime;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.UniqueConstraint;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+/**
+ * Per-(period, category) counter for the local grant. Written only by {@link FreeTierUsageService}.
+ *
+ * <p>A separate table from {@link UsageCounter} rather than a scoped column: {@link
+ * UsageSyncService} reads only that one, so pre-link accrual cannot leak into the first cloud sync,
+ * and the two period starts can collide on a timestamp.
+ */
+@Entity
+@Table(
+ name = "account_link_free_tier_usage",
+ uniqueConstraints =
+ @UniqueConstraint(
+ name = "uk_free_tier_usage_period_category",
+ columnNames = {"period_start", "category"}))
+@Getter
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
+public class FreeTierUsageCounter {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ /** Inclusive. */
+ @Column(name = "period_start", nullable = false)
+ private LocalDateTime periodStart;
+
+ /** {@code BillingCategory} name — API / AI / AUTOMATION (never BYPASSED). */
+ @Column(name = "category", nullable = false, length = 32)
+ private String category;
+
+ @Column(name = "cumulative_units", nullable = false)
+ private long cumulativeUnits;
+
+ @Column(name = "updated_at", nullable = false)
+ private LocalDateTime updatedAt;
+
+ public FreeTierUsageCounter(
+ LocalDateTime periodStart,
+ String category,
+ long cumulativeUnits,
+ LocalDateTime updatedAt) {
+ this.periodStart = periodStart;
+ this.category = category;
+ this.cumulativeUnits = cumulativeUnits;
+ this.updatedAt = updatedAt;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageCounterRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageCounterRepository.java
new file mode 100644
index 0000000000..c69003d769
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageCounterRepository.java
@@ -0,0 +1,40 @@
+package stirling.software.proprietary.accountlink;
+
+import java.time.LocalDateTime;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+import org.springframework.transaction.annotation.Transactional;
+
+public interface FreeTierUsageCounterRepository extends JpaRepository<FreeTierUsageCounter, Long> {
+
+ /**
+ * Adds in SQL to avoid a read-modify-write race. Returns 0 when no row exists yet, which the
+ * caller then inserts.
+ */
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE FreeTierUsageCounter c SET c.cumulativeUnits = c.cumulativeUnits + :delta,"
+ + " c.updatedAt = :now"
+ + " WHERE c.periodStart = :periodStart AND c.category = :category")
+ int increment(
+ @Param("periodStart") LocalDateTime periodStart,
+ @Param("category") String category,
+ @Param("delta") long delta,
+ @Param("now") LocalDateTime now);
+
+ /** {@code [category, units]} rows: a total cannot say which meter spent the grant. */
+ @Query(
+ "SELECT c.category, SUM(c.cumulativeUnits) FROM FreeTierUsageCounter c"
+ + " WHERE c.periodStart = :periodStart GROUP BY c.category")
+ java.util.List<Object[]> sumUnitsByCategory(@Param("periodStart") LocalDateTime periodStart);
+
+ /** {@code null} when the period has no rows. */
+ @Query(
+ "SELECT SUM(c.cumulativeUnits) FROM FreeTierUsageCounter c"
+ + " WHERE c.periodStart = :periodStart")
+ Long sumUnits(@Param("periodStart") LocalDateTime periodStart);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
new file mode 100644
index 0000000000..80479772e6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
@@ -0,0 +1,214 @@
+package stirling.software.proprietary.accountlink;
+
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.function.Supplier;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.stereotype.Service;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.billing.ContentHasher;
+
+/**
+ * The local free-tier ledger an unlinked instance meters itself against.
+ *
+ * <p>Touches only {@link FreeTierUsageCounter} / {@link FreeTierPeriod}, which {@link
+ * UsageSyncService} never reads, so local usage never reaches SaaS and a link/unlink cycle cannot
+ * mint a fresh grant.
+ */
+@Slf4j
+@Service
+@Profile("!saas")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
+public class FreeTierUsageService {
+
+ /** Disjoint from the cloud meter's keyspace: the two period starts can collide. */
+ private static final String SIGNATURE_NAMESPACE = "free-tier\n";
+
+ private final FreeTierPeriodRepository periods;
+ private final FreeTierUsageCounterRepository counters;
+ private final MeteredInputWindow inputWindow;
+ private final long grantUnits;
+ private final Supplier<LocalDateTime> clock;
+
+ @Autowired
+ public FreeTierUsageService(
+ FreeTierPeriodRepository periods,
+ FreeTierUsageCounterRepository counters,
+ MeteredInputSignatureRepository signatures,
+ AccountLinkProperties properties) {
+ this(periods, counters, signatures, properties, LocalDateTime::now);
+ }
+
+ /** Lets tests drive the period boundary rather than wait a month. */
+ FreeTierUsageService(
+ FreeTierPeriodRepository periods,
+ FreeTierUsageCounterRepository counters,
+ MeteredInputSignatureRepository signatures,
+ AccountLinkProperties properties,
+ Supplier<LocalDateTime> clock) {
+ this.periods = periods;
+ this.counters = counters;
+ this.inputWindow =
+ new MeteredInputWindow(signatures, properties.getMetering().getWorkflowWindow());
+ this.grantUnits = properties.getFreeTierUnits();
+ this.clock = clock;
+ }
+
+ /** {@code remainingUnits} is floored at 0 and is what the gate enforces; end is exclusive. */
+ public record FreeTierBalance(
+ long grantUnits,
+ long usedUnits,
+ long remainingUnits,
+ LocalDateTime periodStart,
+ LocalDateTime periodEnd,
+ Map<String, Long> usedByCategory) {
+
+ public FreeTierBalance(
+ long grantUnits,
+ long usedUnits,
+ long remainingUnits,
+ LocalDateTime periodStart,
+ LocalDateTime periodEnd) {
+ this(grantUnits, usedUnits, remainingUnits, periodStart, periodEnd, Map.of());
+ }
+ }
+
+ public FreeTierBalance balance() {
+ PeriodWindow window = currentPeriod();
+ Map<String, Long> byCategory = new LinkedHashMap<>();
+ long spent = 0;
+ for (Object[] row : counters.sumUnitsByCategory(window.start())) {
+ long units = row[1] == null ? 0L : ((Number) row[1]).longValue();
+ byCategory.put(String.valueOf(row[0]), units);
+ spent += units;
+ }
+ return new FreeTierBalance(
+ grantUnits,
+ spent,
+ Math.max(0, grantUnits - spent),
+ window.start(),
+ window.end(),
+ Map.copyOf(byCategory));
+ }
+
+ /**
+ * Spends against the current period unless {@code opSignature} was already charged inside the
+ * workflow window. Best-effort: callers need not handle persistence errors.
+ */
+ public void accrue(BillingCategory category, long units, String opSignature) {
+ if (category == null || category == BillingCategory.BYPASSED || units <= 0) {
+ return;
+ }
+ LocalDateTime period;
+ try {
+ period = currentPeriodStart();
+ } catch (RuntimeException e) {
+ // No period, no key to accrue under. The same fault fails the gate open, so both
+ // err toward the user rather than charging ungated work.
+ log.debug("Free-tier period unavailable; skipping accrual: {}", e.getMessage());
+ return;
+ }
+ if (opSignature != null && !inputWindow.shouldCharge(period, namespaced(opSignature))) {
+ return;
+ }
+ incrementOrInsert(period, category.name(), units);
+ }
+
+ /** Start inclusive, end exclusive; both whole month counts from the same immutable anchor. */
+ record PeriodWindow(LocalDateTime start, LocalDateTime end) {}
+
+ LocalDateTime currentPeriodStart() {
+ return currentPeriod().start();
+ }
+
+ /**
+ * The period in force, anchoring on first use and rolling the stamp when the boundary has
+ * passed. Every bound is a whole month count from the immutable anchor, so neither drifts and
+ * the end reported to the UI is the one enforcement rolls on. Deriving the end from the
+ * <em>start</em> would report an earlier reset than the gate honours whenever the anchor day
+ * clamps: a 31st anchor starts February on the 28th, whose next month is the 28th of March,
+ * while the gate holds until the 31st.
+ */
+ PeriodWindow currentPeriod() {
+ LocalDateTime now = clock.get();
+ FreeTierPeriod stored = periods.findById(FreeTierPeriod.SINGLETON_ID).orElse(null);
+ if (stored == null) {
+ LocalDateTime first = anchorNow(now);
+ return new PeriodWindow(first, first.plusMonths(1));
+ }
+ LocalDateTime anchor = stored.getAnchorAt();
+ long elapsed = periodsElapsed(anchor, now);
+ LocalDateTime start = anchor.plusMonths(elapsed);
+ if (start.isAfter(stored.getPeriodStart())) {
+ periods.rollTo(FreeTierPeriod.SINGLETON_ID, start, now);
+ }
+ return new PeriodWindow(start, anchor.plusMonths(elapsed + 1));
+ }
+
+ /**
+ * Largest {@code n} with {@code anchor.plusMonths(n) <= now}.
+ *
+ * <p>{@link ChronoUnit#MONTHS} alone is not that number: it disagrees with {@code plusMonths}
+ * when the anchor day clamps into a shorter month, so a 31st anchor reads as 0 elapsed long
+ * after the first period ended. The clamp costs at most a month, so neither loop repeats.
+ */
+ private static long periodsElapsed(LocalDateTime anchor, LocalDateTime now) {
+ long n = Math.max(0, ChronoUnit.MONTHS.between(anchor, now));
+ while (!anchor.plusMonths(n + 1).isAfter(now)) {
+ n++;
+ }
+ while (n > 0 && anchor.plusMonths(n).isAfter(now)) {
+ n--;
+ }
+ return n;
+ }
+
+ /**
+ * Anchors the first period at {@code now}; a concurrent first request wins or loses cleanly.
+ */
+ private LocalDateTime anchorNow(LocalDateTime now) {
+ try {
+ return periods.saveAndFlush(new FreeTierPeriod(now)).getPeriodStart();
+ } catch (DataIntegrityViolationException raced) {
+ return periods.findById(FreeTierPeriod.SINGLETON_ID)
+ .map(FreeTierPeriod::getPeriodStart)
+ .orElse(now);
+ }
+ }
+
+ private void incrementOrInsert(LocalDateTime period, String category, long units) {
+ LocalDateTime now = clock.get();
+ try {
+ if (counters.increment(period, category, units, now) > 0) {
+ return;
+ }
+ try {
+ counters.saveAndFlush(new FreeTierUsageCounter(period, category, units, now));
+ } catch (DataIntegrityViolationException raceLostInsert) {
+ counters.increment(period, category, units, now);
+ }
+ } catch (RuntimeException e) {
+ // Metering must never break the request it rode in on; the next accrual self-heals.
+ log.debug("Free-tier accrual failed for {}/{}: {}", period, category, e.getMessage());
+ }
+ }
+
+ private static String namespaced(String opSignature) {
+ // Re-hashed rather than prefixed: the signature column holds exactly one SHA-256 hex.
+ return ContentHasher.sha256(
+ (SIGNATURE_NAMESPACE + opSignature).getBytes(StandardCharsets.UTF_8));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java
index 87b4ddcde9..3723a517eb 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java
@@ -2,8 +2,8 @@ package stirling.software.proprietary.accountlink;
/**
* Outcome of {@link InstanceEntitlementGate}. {@link #allowed} is what the interceptor enforces;
- * {@link #reason} carries the machine-readable signal the FE maps to a prompt (e.g. "link to
- * activate"). Manual-tool and fail-open allows carry an informational reason but never block.
+ * {@link #reason} is the only thing distinguishing "your grant is spent, linking buys more" from
+ * "your linked team is over its limit". Allows carry one too, informationally.
*/
public record GateDecision(boolean allowed, Reason reason) {
@@ -14,6 +14,7 @@ public record GateDecision(boolean allowed, Reason reason) {
MANUAL_FREE,
/** Linked + within entitlement — billable work allowed. */
ENTITLED,
+ FREE_TIER,
/** Entitlement source unreachable — fail open, allow. */
FAIL_OPEN,
/**
@@ -21,8 +22,11 @@ public record GateDecision(boolean allowed, Reason reason) {
* fail-open backstop expired) so unbounded free/unbilled billable work can't continue.
*/
GRACE_EXPIRED,
- /** Not linked — block billable work; FE should prompt to link. */
- NOT_LINKED,
+ /**
+ * Blocked until the period rolls. The FE must offer linking as <em>more</em> allowance, not
+ * as what switches the feature on: nothing here needed an account.
+ */
+ FREE_TIER_EXHAUSTED,
/** Linked but over the limit / no subscription — block billable work. */
OVER_LIMIT,
/** Credential revoked/invalid on the SaaS side — block billable work. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java
index c0cc901e1f..eba5fada99 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java
@@ -15,7 +15,8 @@ import org.springframework.stereotype.Service;
* <ol>
* <li>Flag off → always allow (feature inert).
* <li>Manual tool → always allow (manual tools are free, never metered).
- * <li>Billable + not linked → block with {@code NOT_LINKED} ("link to activate").
+ * <li>Billable + not linked → {@code FREE_TIER} while units remain, else {@code
+ * FREE_TIER_EXHAUSTED}. Linking buys a further grant, it does not activate the feature.
* <li>Billable + linked + entitlement unknown (unreachable) → <b>fail open</b>, allow — unless
* metering is on and SaaS has been unreachable past the grace window, then block with {@code
* GRACE_EXPIRED} so the fail-open can't grant unbounded free/unbilled work forever.
@@ -24,13 +25,18 @@ import org.springframework.stereotype.Service;
* <li>Billable + linked + over limit → block with {@code OVER_LIMIT}.
* </ol>
*
+ * <p>The local grant is read only when unlinked; a linked instance's pre-link counters sit
+ * untouched, and are what it resumes on if it unlinks.
+ *
* <p>The decision logic is the pure static {@link #decide}; the Spring wrapper supplies the live
- * flag / linked-state / entitlement and computes whether the grace window has expired. This is the
- * unit-tested core.
+ * flag / linked-state / entitlement / balances and resolves the grace window.
*/
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class InstanceEntitlementGate {
private final AccountLinkProperties properties;
@@ -38,18 +44,21 @@ public class InstanceEntitlementGate {
private final EntitlementCache entitlementCache;
private final AccountLinkSyncStateRepository syncStateRepository;
private final LocalUsageService localUsageService;
+ private final FreeTierUsageService freeTierUsageService;
public InstanceEntitlementGate(
AccountLinkProperties properties,
DeviceCredentialStore credentialStore,
EntitlementCache entitlementCache,
AccountLinkSyncStateRepository syncStateRepository,
- LocalUsageService localUsageService) {
+ LocalUsageService localUsageService,
+ FreeTierUsageService freeTierUsageService) {
this.properties = properties;
this.credentialStore = credentialStore;
this.entitlementCache = entitlementCache;
this.syncStateRepository = syncStateRepository;
this.localUsageService = localUsageService;
+ this.freeTierUsageService = freeTierUsageService;
}
/** Evaluates the gate for a request, resolving live state from the store + cache. */
@@ -61,6 +70,7 @@ public class InstanceEntitlementGate {
return GateDecision.allow(GateDecision.Reason.MANUAL_FREE);
}
boolean linked = credentialStore.isLinked();
+ long freeTierRemaining = linked ? 0L : freeTierUsageService.balance().remainingUnits();
Optional<InstanceEntitlement> entitlement =
linked ? entitlementCache.current() : Optional.empty();
boolean graceExpired = linked && entitlement.isEmpty() && isGraceExpired();
@@ -71,7 +81,8 @@ public class InstanceEntitlementGate {
entitlement.map(InstanceEntitlementGate::depletesCeiling).orElse(false)
? localUsageService.currentPeriodUnsynced().totalUnsyncedUnits()
: 0L;
- return decide(true, true, linked, entitlement, graceExpired, pendingUnsynced);
+ return decide(
+ true, true, linked, entitlement, graceExpired, pendingUnsynced, freeTierRemaining);
}
/** Whether local unsynced usage pushes against a real ceiling (free grant or a spend cap). */
@@ -88,6 +99,8 @@ public class InstanceEntitlementGate {
* free grant (unsubscribed) or the spend cap (capped subscription) in real time so the gate
* stops without waiting for the next sync (0 for uncapped-subscribed / unknown-entitlement
* cases, where it has no effect).
+ * @param freeTierRemainingUnits the sole ceiling when unlinked. 0 blocks, so a caller that
+ * cannot read the local ledger must throw instead: a throw fails open, 0 reads as empty.
*/
public static GateDecision decide(
boolean flagEnabled,
@@ -95,7 +108,8 @@ public class InstanceEntitlementGate {
boolean linked,
Optional<InstanceEntitlement> entitlement,
boolean graceExpired,
- long pendingUnsyncedUnits) {
+ long pendingUnsyncedUnits,
+ long freeTierRemainingUnits) {
if (!flagEnabled) {
return GateDecision.allow(GateDecision.Reason.FLAG_OFF);
}
@@ -103,7 +117,9 @@ public class InstanceEntitlementGate {
return GateDecision.allow(GateDecision.Reason.MANUAL_FREE);
}
if (!linked) {
- return GateDecision.block(GateDecision.Reason.NOT_LINKED);
+ return freeTierRemainingUnits > 0
+ ? GateDecision.allow(GateDecision.Reason.FREE_TIER)
+ : GateDecision.block(GateDecision.Reason.FREE_TIER_EXHAUSTED);
}
if (entitlement.isEmpty()) {
// Linked but entitlement unreachable: fail open, unless the grace window has expired
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
index 9e73267561..a0eb3f71e3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
@@ -40,36 +40,43 @@ import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
/**
* Request-time gate + meter for combined billing. {@code preHandle} blocks billable (API / AI /
- * automation) work when the instance is unlinked or over its limit; manual tools pass through.
- * {@code afterCompletion} meters a successful billable op into the per-period cumulative counter.
+ * automation) work once the applicable allowance is spent; manual tools pass through. {@code
+ * afterCompletion} costs the op and accrues it.
*
- * <p>Blocking responds {@code 402} with a machine-readable body the FE maps to a "link to activate"
- * prompt; fail-open and flag-off both let the request continue. Metering is separately gated behind
- * {@code …metering.enabled} via {@link ObjectProvider} — switch off means the {@link
- * UsageMeterService} bean is absent and nothing accrues, while the gate still works.
+ * <p>The ledger follows the gate's own reason rather than re-deriving linked-ness, so the two
+ * cannot disagree. Only the cloud one sits behind {@code …metering.enabled}: with it off a linked
+ * instance accrues nothing while the free tier still meters and holds.
*/
@Slf4j
@Component
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class InstanceEntitlementInterceptor implements HandlerInterceptor {
private static final String ATTR_CATEGORY =
InstanceEntitlementInterceptor.class.getName() + ".category";
+ private static final String ATTR_REASON =
+ InstanceEntitlementInterceptor.class.getName() + ".reason";
private final InstanceEntitlementGate gate;
private final EntitlementCache entitlementCache;
private final ObjectProvider<UsageMeterService> meterProvider;
+ private final FreeTierUsageService freeTierUsageService;
private final TempFileManager tempFileManager;
public InstanceEntitlementInterceptor(
InstanceEntitlementGate gate,
EntitlementCache entitlementCache,
ObjectProvider<UsageMeterService> meterProvider,
+ FreeTierUsageService freeTierUsageService,
TempFileManager tempFileManager) {
this.gate = gate;
this.entitlementCache = entitlementCache;
this.meterProvider = meterProvider;
+ this.freeTierUsageService = freeTierUsageService;
this.tempFileManager = tempFileManager;
}
@@ -99,6 +106,7 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
return true;
}
if (decision.allowed()) {
+ request.setAttribute(ATTR_REASON, decision.reason());
return true;
}
@@ -123,45 +131,46 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
if (ex != null || response.getStatus() >= 400) {
return;
}
- UsageMeterService meter = meterProvider.getIfAvailable();
- if (meter == null) {
- return; // metering switch off
- }
if (!(request.getAttribute(ATTR_CATEGORY) instanceof BillingCategory category)
|| category == BillingCategory.BYPASSED) {
return;
}
try {
+ if (request.getAttribute(ATTR_REASON) == GateDecision.Reason.FREE_TIER) {
+ MeteredOp op = measure(request, UnitCalcPolicy.DEFAULT);
+ freeTierUsageService.accrue(category, op.units(), op.opSignature());
+ return;
+ }
+ UsageMeterService meter = meterProvider.getIfAvailable();
+ if (meter == null) {
+ return; // cloud metering switch off
+ }
InstanceEntitlement ent = entitlementCache.current().orElse(null);
if (ent == null || ent.unitCalcPolicy() == null || ent.periodStart() == null) {
// Not yet synced (no policy/period) — can't compute units; skip until next sync.
return;
}
- meterRequest(request, category, ent, meter);
+ MeteredOp op = measure(request, ent.unitCalcPolicy());
+ meter.accrue(ent.periodStart(), category, op.units(), op.opSignature());
} catch (RuntimeException e) {
// Metering must never affect the response that already completed.
log.debug("Usage metering failed for {}", request.getRequestURI(), e);
}
}
+ /** {@code opSignature} null = no dedup. */
+ private record MeteredOp(long units, String opSignature) {}
+
/**
- * Computes doc-units (page + byte axes) and the input-set signature, then accrues. The instance
- * is authoritative for units (SaaS bills the delta and never sees the file), so a page-heavy
- * but small PDF must be page-counted or it under-bills. A fileless op has no input identity —
- * null signature (no dedup), billed the 1-unit floor each time.
+ * Costs the inputs on both the page and byte axes: the instance is authoritative for units and
+ * SaaS never sees the file, so a page-heavy but small PDF would otherwise under-bill. A
+ * fileless op has no input identity, so no signature and the 1-unit floor each time.
*/
- private void meterRequest(
- HttpServletRequest request,
- BillingCategory category,
- InstanceEntitlement ent,
- UsageMeterService meter) {
- UnitCalcPolicy policy = ent.unitCalcPolicy();
+ private MeteredOp measure(HttpServletRequest request, UnitCalcPolicy policy) {
MultipartHttpServletRequest mreq =
WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
if (mreq == null) {
- long fileless = DocumentUnitCalculator.unitsForFile(0, 0, policy);
- meter.accrue(ent.periodStart(), category, fileless, null);
- return;
+ return new MeteredOp(DocumentUnitCalculator.unitsForFile(0, 0, policy), null);
}
List<TempFile> temps = new ArrayList<>();
try {
@@ -204,7 +213,7 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
// different input set, so fall back to no-dedup (bill it) if any file failed.
String opSignature =
fileCount > 0 && hashes.size() == fileCount ? opSignature(hashes) : null;
- meter.accrue(ent.periodStart(), category, units, opSignature);
+ return new MeteredOp(units, opSignature);
} finally {
for (TempFile temp : temps) {
try {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalUsageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalUsageService.java
index 58d365fe28..d94e6aacf4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalUsageService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/LocalUsageService.java
@@ -19,7 +19,10 @@ import stirling.software.proprietary.billing.BillingCategory;
*/
@Service
@Profile("!saas")
-@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@ConditionalOnProperty(
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class LocalUsageService {
private final UsageCounterRepository counters;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java
new file mode 100644
index 0000000000..9c3448b51a
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/MeteredInputWindow.java
@@ -0,0 +1,58 @@
+package stirling.software.proprietary.accountlink;
+
+import java.time.Duration;
+import java.time.LocalDateTime;
+
+import org.springframework.dao.DataIntegrityViolationException;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * The workflow-window dedup rule, shared by both meters so an op costs the same either way. An
+ * identical input set inside {@code metering.workflow-window} is chaining, not a new charge.
+ *
+ * <p>Not a bean: each meter constructs one, so the rule cannot be on for one ledger and off for the
+ * other. {@link MeteredInputSignature} rows are shared, so callers namespace their own.
+ */
+@Slf4j
+class MeteredInputWindow {
+
+ private final MeteredInputSignatureRepository signatureRepo;
+ private final Duration window;
+
+ MeteredInputWindow(MeteredInputSignatureRepository signatureRepo, Duration window) {
+ this.signatureRepo = signatureRepo;
+ this.window = window;
+ }
+
+ /**
+ * Charge when unseen this period, or last seen outside the window. Records a first sighting as
+ * an atomic insert-as-claim, and fails toward charging so a store hiccup drops nothing.
+ */
+ boolean shouldCharge(LocalDateTime periodStart, String opSignature) {
+ LocalDateTime now = LocalDateTime.now();
+ MeteredInputSignature seen =
+ signatureRepo.findByPeriodStartAndSignature(periodStart, opSignature).orElse(null);
+ if (seen == null) {
+ try {
+ signatureRepo.saveAndFlush(
+ new MeteredInputSignature(periodStart, opSignature, now));
+ return true; // first sighting this period
+ } catch (DataIntegrityViolationException raced) {
+ return false; // a concurrent op just claimed it — within window → chaining
+ } catch (RuntimeException e) {
+ log.debug("Signature claim failed for {}: {}", periodStart, e.getMessage());
+ return true;
+ }
+ }
+ LocalDateTime last = seen.getLastMeteredAt() != null ? seen.getLastMeteredAt() : now;
+ boolean withinWindow = last.isAfter(now.minus(window));
+ try {
+ seen.touch(now);
+ signatureRepo.save(seen);
+ } catch (RuntimeException e) {
+ log.debug("Signature touch failed for {}: {}", periodStart, e.getMessage());
+ }
+ return !withinWindow;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageCounter.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageCounter.java
index 4c06089040..2a24637294 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageCounter.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageCounter.java
@@ -22,6 +22,9 @@ import stirling.software.proprietary.billing.BillingCategory;
* bills the delta since the last sync. The cumulative model is idempotent (a resend bills nothing)
* and tamper-evident (a counter that drops is a signal). One row per {@code (period_start,
* category)}, auto-created by Hibernate; only the flag-gated {@link UsageMeterService} writes it.
+ *
+ * <p>The cloud ledger only. An unlinked instance's own free-tier usage lives in {@link
+ * FreeTierUsageCounter}, which the sync cannot see — that is what keeps the two independent.
*/
@Entity
@Table(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java
index 6aa93606fb..31ec9e254f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageMeterService.java
@@ -1,6 +1,5 @@
package stirling.software.proprietary.accountlink;
-import java.time.Duration;
import java.time.LocalDateTime;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -13,14 +12,12 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.billing.BillingCategory;
/**
- * Accrues metered usage into the durable per-(period, category) {@link UsageCounter}; the daily
- * sync later reports the cumulative totals to SaaS.
+ * Accrues a linked team's metered usage into the durable per-(period, category) {@link
+ * UsageCounter}; the daily sync later reports the cumulative totals to SaaS. The cloud ledger only
+ * — an unlinked instance meters its own grant through {@link FreeTierUsageService}.
*
- * <p>Workflow-window dedup: an identical input set re-submitted within {@code metering.workflow-
- * window} is treated as chaining and not re-charged; the same inputs run again after the window are
- * billed afresh — matching the cloud's open-job lineage window so the same op costs the same on the
- * instance and in the cloud. Fileless ops pass a null signature and always accrue. {@link #accrue}
- * is best-effort: callers need not handle persistence errors.
+ * <p>Dedup follows the shared {@link MeteredInputWindow} rule. Fileless ops pass a null signature
+ * and always accrue. {@link #accrue} is best-effort: callers need not handle persistence errors.
*/
@Slf4j
@Service
@@ -31,16 +28,15 @@ import stirling.software.proprietary.billing.BillingCategory;
public class UsageMeterService {
private final UsageCounterRepository repo;
- private final MeteredInputSignatureRepository signatureRepo;
- private final Duration workflowWindow;
+ private final MeteredInputWindow inputWindow;
public UsageMeterService(
UsageCounterRepository repo,
MeteredInputSignatureRepository signatureRepo,
AccountLinkProperties properties) {
this.repo = repo;
- this.signatureRepo = signatureRepo;
- this.workflowWindow = properties.getMetering().getWorkflowWindow();
+ this.inputWindow =
+ new MeteredInputWindow(signatureRepo, properties.getMetering().getWorkflowWindow());
}
/**
@@ -56,44 +52,12 @@ public class UsageMeterService {
|| units <= 0) {
return;
}
- if (opSignature != null && !shouldCharge(periodStart, opSignature)) {
+ if (opSignature != null && !inputWindow.shouldCharge(periodStart, opSignature)) {
return; // identical inputs seen within the workflow window — chaining, already billed
}
incrementOrInsert(periodStart, category.name(), units);
}
- /**
- * True when this input set should be charged: unseen this period, or last seen outside the
- * workflow window. Records a first sighting (an atomic insert-as-claim under concurrency) and
- * slides the window on a repeat. Fails toward charging so a store hiccup never drops a charge.
- */
- private boolean shouldCharge(LocalDateTime periodStart, String opSignature) {
- LocalDateTime now = LocalDateTime.now();
- MeteredInputSignature seen =
- signatureRepo.findByPeriodStartAndSignature(periodStart, opSignature).orElse(null);
- if (seen == null) {
- try {
- signatureRepo.saveAndFlush(
- new MeteredInputSignature(periodStart, opSignature, now));
- return true; // first sighting this period
- } catch (DataIntegrityViolationException raced) {
- return false; // a concurrent op just claimed it — within window → chaining
- } catch (RuntimeException e) {
- log.debug("Signature claim failed for {}: {}", periodStart, e.getMessage());
- return true;
- }
- }
- LocalDateTime last = seen.getLastMeteredAt() != null ? seen.getLastMeteredAt() : now;
- boolean withinWindow = last.isAfter(now.minus(workflowWindow));
- try {
- seen.touch(now);
- signatureRepo.save(seen);
- } catch (RuntimeException e) {
- log.debug("Signature touch failed for {}: {}", periodStart, e.getMessage());
- }
- return !withinWindow;
- }
-
private void incrementOrInsert(LocalDateTime periodStart, String category, long units) {
LocalDateTime now = LocalDateTime.now();
try {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/billing/UnitCalcPolicy.java b/app/proprietary/src/main/java/stirling/software/proprietary/billing/UnitCalcPolicy.java
index b7d773d465..f39afa097a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/billing/UnitCalcPolicy.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/billing/UnitCalcPolicy.java
@@ -13,6 +13,16 @@ package stirling.software.proprietary.billing;
public record UnitCalcPolicy(
int docPagesPerUnit, long docBytesPerUnit, int minChargeUnits, int fileUnitCap) {
+ /**
+ * Knobs for an instance with no policy from SaaS — a self-hosted install metering its own free
+ * tier before (or without) ever linking. Nothing else can serve as a fallback: the constructor
+ * rejects zero on every axis, so there is no inert default to degrade to.
+ *
+ * <p>Must stay equal to the values SaaS seeds on its default pricing policy, or the same
+ * document costs a different number of units before and after linking.
+ */
+ public static final UnitCalcPolicy DEFAULT = new UnitCalcPolicy(25, 5L * 1024 * 1024, 1, 1000);
+
public UnitCalcPolicy {
if (docPagesPerUnit <= 0) {
throw new IllegalArgumentException("docPagesPerUnit must be > 0");
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java
index 6e13021a40..6498bfc341 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java
@@ -8,6 +8,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
+import java.time.LocalDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -26,6 +27,7 @@ class AccountLinkControllerTest {
private ConnectService connectService;
private UsageSyncService syncService;
private ObjectProvider<UsageSyncService> syncProvider;
+ private FreeTierUsageService freeTierService;
private AccountLinkController controller;
@BeforeEach
@@ -35,9 +37,14 @@ class AccountLinkControllerTest {
connectService = mock(ConnectService.class);
syncService = mock(UsageSyncService.class);
syncProvider = mock(ObjectProvider.class);
+ freeTierService = mock(FreeTierUsageService.class);
controller =
new AccountLinkController(
- service, connectService, mock(LocalUsageService.class), syncProvider);
+ service,
+ connectService,
+ mock(LocalUsageService.class),
+ freeTierService,
+ syncProvider);
}
// These asserted POST /link's error mapping, which distinguished 401/403 so the portal could
@@ -92,6 +99,22 @@ class AccountLinkControllerTest {
verify(syncService).syncNow();
}
+ @Test
+ void freeTier_reportsTheLocalGrant() {
+ LocalDateTime start = LocalDateTime.of(2026, 9, 1, 0, 0);
+ when(freeTierService.balance())
+ .thenReturn(
+ new FreeTierUsageService.FreeTierBalance(
+ 500, 120, 380, start, start.plusMonths(1)));
+
+ ResponseEntity<FreeTierUsageService.FreeTierBalance> resp = controller.freeTier();
+
+ assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
+ assertThat(resp.getBody()).isNotNull();
+ assertThat(resp.getBody().remainingUnits()).isEqualTo(380);
+ assertThat(resp.getBody().periodEnd()).isEqualTo(start.plusMonths(1));
+ }
+
@Test
void syncNow_returns409WhenMeteringOff() {
when(syncProvider.getIfAvailable()).thenReturn(null); // metering disabled → bean absent
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfigTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfigTest.java
new file mode 100644
index 0000000000..15b7812111
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfigTest.java
@@ -0,0 +1,60 @@
+package stirling.software.proprietary.accountlink;
+
+import static org.mockito.Mockito.RETURNS_SELF;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+
+class AccountLinkWebMvcConfigTest {
+
+ private static final String TAURI_MODE = "STIRLING_PDF_TAURI_MODE";
+
+ private final InstanceEntitlementInterceptor interceptor =
+ mock(InstanceEntitlementInterceptor.class);
+ private final InterceptorRegistry registry = mock(InterceptorRegistry.class);
+
+ /** The real registry hands back a registration to chain path patterns onto. */
+ @BeforeEach
+ void stubRegistration() {
+ when(registry.addInterceptor(interceptor))
+ .thenReturn(mock(InterceptorRegistration.class, RETURNS_SELF));
+ }
+
+ @AfterEach
+ void clearTauriMode() {
+ System.clearProperty(TAURI_MODE);
+ }
+
+ @Test
+ void aServerRegistersTheGate() {
+ new AccountLinkWebMvcConfig(interceptor).addInterceptors(registry);
+
+ verify(registry).addInterceptor(interceptor);
+ }
+
+ @Test
+ void aDesktopBundleRegistersNothing() {
+ System.setProperty(TAURI_MODE, "true");
+
+ new AccountLinkWebMvcConfig(interceptor).addInterceptors(registry);
+
+ verify(registry, never()).addInterceptor(interceptor);
+ }
+
+ /** A server can present a desktop-looking client, so only the build property counts. */
+ @Test
+ void anUnparseableTauriModeIsNotDesktop() {
+ System.setProperty(TAURI_MODE, "Client-Browser");
+
+ new AccountLinkWebMvcConfig(interceptor).addInterceptors(registry);
+
+ verify(registry).addInterceptor(interceptor);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java
new file mode 100644
index 0000000000..8550a616b1
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/FreeTierUsageServiceDbTest.java
@@ -0,0 +1,222 @@
+package stirling.software.proprietary.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+
+import stirling.software.proprietary.billing.BillingCategory;
+
+/**
+ * The local ledger against a real database, so the upsert, the {@code SUM} and the guarded roll
+ * actually run. A moveable clock stands in for waiting out a month.
+ */
+@DataJpaTest
+class FreeTierUsageServiceDbTest {
+
+ private static final LocalDateTime T0 = LocalDateTime.of(2026, 1, 31, 9, 30);
+
+ @Autowired private FreeTierPeriodRepository periods;
+ @Autowired private FreeTierUsageCounterRepository counters;
+ @Autowired private MeteredInputSignatureRepository signatures;
+ @Autowired private UsageCounterRepository cloudCounters;
+ @PersistenceContext private EntityManager em;
+
+ private final AtomicReference<LocalDateTime> now = new AtomicReference<>(T0);
+
+ private FreeTierUsageService service(long grant) {
+ AccountLinkProperties props = new AccountLinkProperties();
+ props.setFreeTierUnits(grant);
+ return new FreeTierUsageService(periods, counters, signatures, props, now::get);
+ }
+
+ @Test
+ void firstAccrualAnchorsThePeriodAndSpendsTheGrant() {
+ FreeTierUsageService service = service(500);
+
+ service.accrue(BillingCategory.API, 30, null);
+
+ FreeTierUsageService.FreeTierBalance balance = service.balance();
+ assertThat(balance.periodStart()).isEqualTo(T0);
+ assertThat(balance.periodEnd()).isEqualTo(T0.plusMonths(1));
+ assertThat(balance.grantUnits()).isEqualTo(500);
+ assertThat(balance.usedUnits()).isEqualTo(30);
+ assertThat(balance.remainingUnits()).isEqualTo(470);
+ }
+
+ @Test
+ void spendAcrossCategoriesAccumulatesIntoOnePool() {
+ FreeTierUsageService service = service(500);
+
+ service.accrue(BillingCategory.API, 30, null);
+ service.accrue(BillingCategory.AI, 12, null);
+ service.accrue(BillingCategory.AUTOMATION, 8, null);
+ service.accrue(BillingCategory.API, 5, null); // second hit on an existing row
+
+ assertThat(service.balance().usedUnits()).isEqualTo(55);
+ assertThat(counters.count()).isEqualTo(3); // one row per category, incremented in place
+ }
+
+ @Test
+ void exactlyAtTheGrantLeavesNothing() {
+ FreeTierUsageService service = service(100);
+
+ service.accrue(BillingCategory.API, 100, null);
+
+ assertThat(service.balance().remainingUnits()).isZero();
+ }
+
+ @Test
+ void overshootingTheGrantFloorsAtZeroRatherThanGoingNegative() {
+ // The gate allows before the meter charges, so the last op of a period can overshoot.
+ FreeTierUsageService service = service(100);
+
+ service.accrue(BillingCategory.API, 140, null);
+
+ assertThat(service.balance().usedUnits()).isEqualTo(140);
+ assertThat(service.balance().remainingUnits()).isZero();
+ }
+
+ @Test
+ void manualToolsAreNeverCounted() {
+ FreeTierUsageService service = service(500);
+
+ service.accrue(BillingCategory.BYPASSED, 40, null);
+ service.accrue(BillingCategory.API, 0, null);
+
+ assertThat(counters.count()).isZero();
+ assertThat(service.balance().usedUnits()).isZero();
+ }
+
+ @Test
+ void crossingTheMonthBoundaryRollsThePeriodAndRestoresTheFullGrant() {
+ FreeTierUsageService service = service(500);
+ service.accrue(BillingCategory.API, 480, null);
+ assertThat(service.balance().remainingUnits()).isEqualTo(20);
+
+ now.set(T0.plusMonths(1).plusDays(2));
+
+ FreeTierUsageService.FreeTierBalance rolled = service.balance();
+ assertThat(rolled.periodStart()).isEqualTo(T0.plusMonths(1));
+ assertThat(rolled.usedUnits()).isZero();
+ assertThat(rolled.remainingUnits()).isEqualTo(500);
+ // rollTo is a bulk update, so a loaded row would answer stale.
+ em.clear();
+ assertThat(periods.findById(FreeTierPeriod.SINGLETON_ID).orElseThrow().getPeriodStart())
+ .isEqualTo(T0.plusMonths(1));
+ assertThat(counters.sumUnits(T0)).isEqualTo(480);
+ }
+
+ @Test
+ void aServerOfflineForMonthsLandsOnTheCurrentPeriodNotTheNextOne() {
+ FreeTierUsageService service = service(500);
+ service.accrue(BillingCategory.API, 10, null);
+
+ now.set(T0.plusMonths(5).plusDays(1));
+
+ assertThat(service.balance().periodStart()).isEqualTo(T0.plusMonths(5));
+ }
+
+ @Test
+ void theAnchorDayDoesNotDriftDownShortMonths() {
+ // T0 is a 31st: rolling from the previous start would pin it to the 28th after February.
+ FreeTierUsageService service = service(500);
+ service.accrue(BillingCategory.API, 1, null);
+
+ now.set(LocalDateTime.of(2026, 3, 1, 0, 0));
+ assertThat(service.balance().periodStart()).isEqualTo(LocalDateTime.of(2026, 2, 28, 9, 30));
+
+ now.set(LocalDateTime.of(2026, 4, 1, 0, 0));
+ assertThat(service.balance().periodStart()).isEqualTo(LocalDateTime.of(2026, 3, 31, 9, 30));
+ }
+
+ @Test
+ void theReportedResetIsTheDayEnforcementActuallyRollsOn() {
+ FreeTierUsageService service = service(500);
+ service.accrue(BillingCategory.API, 1, null); // anchors on the 31st
+
+ // February clamps to the 28th, whose own next month is 28 March. Enforcement counts whole
+ // months from the anchor instead and holds until the 31st, so a reset derived from the
+ // start would promise the grant back three days early.
+ now.set(LocalDateTime.of(2026, 3, 1, 0, 0));
+ service.accrue(BillingCategory.API, 500, null);
+ FreeTierUsageService.FreeTierBalance february = service.balance();
+ assertThat(february.periodStart()).isEqualTo(LocalDateTime.of(2026, 2, 28, 9, 30));
+ assertThat(february.periodEnd()).isEqualTo(LocalDateTime.of(2026, 3, 31, 9, 30));
+ assertThat(february.remainingUnits()).isZero();
+
+ now.set(LocalDateTime.of(2026, 3, 29, 0, 0));
+ assertThat(service.balance().remainingUnits()).isZero();
+ }
+
+ @Test
+ void aFreshPeriodIsInsertedRatherThanMergedOverALiveAnchor() {
+ FreeTierUsageService service = service(500);
+ service.accrue(BillingCategory.API, 30, null);
+ em.clear();
+
+ // The id is assigned, so without Persistable a racing first request would merge: an UPDATE
+ // moving the anchor forward and handing back a fresh grant instead of losing the race.
+ assertThat(new FreeTierPeriod(T0.plusDays(3)).isNew()).isTrue();
+ assertThat(periods.findById(FreeTierPeriod.SINGLETON_ID).orElseThrow().isNew()).isFalse();
+ }
+
+ @Test
+ void repeatingAnInputSetInsideTheWorkflowWindowIsNotCharged() {
+ FreeTierUsageService service = service(500);
+
+ service.accrue(BillingCategory.API, 20, "a".repeat(64));
+ service.accrue(BillingCategory.API, 20, "a".repeat(64));
+
+ assertThat(service.balance().usedUnits()).isEqualTo(20);
+ }
+
+ @Test
+ void aDifferentInputSetIsChargedSeparately() {
+ FreeTierUsageService service = service(500);
+
+ service.accrue(BillingCategory.API, 20, "a".repeat(64));
+ service.accrue(BillingCategory.API, 7, "b".repeat(64));
+
+ assertThat(service.balance().usedUnits()).isEqualTo(27);
+ }
+
+ @Test
+ void freeTierSpendIsInvisibleToTheCloudSyncAndSurvivesALinkUnlinkCycle() {
+ FreeTierUsageService service = service(500);
+ service.accrue(BillingCategory.API, 120, null);
+
+ // Deliberately the same timestamp the free tier anchored on: the collision a shared
+ // table would suffer.
+ cloudCounters.saveAndFlush(new UsageCounter(T0, "API", 90, now.get()));
+ List<LocalDateTime> pending = cloudCounters.findPeriodsWithUnsyncedUsage();
+ cloudCounters.markSynced(T0, "API", 90);
+
+ FreeTierUsageService.FreeTierBalance after = service.balance();
+
+ assertThat(pending).containsExactly(T0); // the sync only ever saw its own 90 cloud units
+ assertThat(cloudCounters.findPeriodsWithUnsyncedUsage()).isEmpty();
+ assertThat(after.usedUnits()).isEqualTo(120);
+ assertThat(after.remainingUnits()).isEqualTo(380);
+ assertThat(after.periodStart()).isEqualTo(T0);
+ }
+
+ @Test
+ void aZeroGrantLeavesNothingToSpend() {
+ assertThat(service(0).balance().remainingUnits()).isZero();
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ static class TestApp {}
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java
index 1838034a9a..c4b29619c9 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java
@@ -3,6 +3,8 @@ package stirling.software.proprietary.accountlink;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
@@ -16,10 +18,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
import stirling.software.proprietary.accountlink.GateDecision.Reason;
/**
- * Covers the gate decision matrix: flag-off, manual-free, unlinked, fail-open, grace-expired,
- * linked-free, and over-limit. The pure {@link InstanceEntitlementGate#decide} cases need no
- * Spring; the grace-window reference computation is exercised through {@link
- * InstanceEntitlementGate#evaluate} with mocked collaborators.
+ * The gate decision matrix. {@link InstanceEntitlementGate#decide} is pure; the grace window and
+ * the ledger picked per link state go through {@link InstanceEntitlementGate#evaluate}.
*/
@ExtendWith(MockitoExtension.class)
class InstanceEntitlementGateTest {
@@ -28,6 +28,13 @@ class InstanceEntitlementGateTest {
@Mock private EntitlementCache entitlementCache;
@Mock private AccountLinkSyncStateRepository syncStateRepository;
@Mock private LocalUsageService localUsageService;
+ @Mock private FreeTierUsageService freeTierUsageService;
+
+ private static FreeTierUsageService.FreeTierBalance grant(long remaining) {
+ LocalDateTime start = LocalDateTime.of(2026, 9, 1, 0, 0);
+ return new FreeTierUsageService.FreeTierBalance(
+ 500, 500 - remaining, remaining, start, start.plusMonths(1));
+ }
private static InstanceEntitlement free() {
return new InstanceEntitlement(false, 100, 0, null, EntitlementState.OK);
@@ -48,7 +55,7 @@ class InstanceEntitlementGateTest {
@Test
void flagOff_allowsEverything_evenBillableUnlinked() {
GateDecision d =
- InstanceEntitlementGate.decide(false, true, false, Optional.empty(), false, 0L);
+ InstanceEntitlementGate.decide(false, true, false, Optional.empty(), false, 0L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.FLAG_OFF, d.reason());
}
@@ -56,23 +63,59 @@ class InstanceEntitlementGateTest {
@Test
void manualTool_alwaysFree_evenUnlinked() {
GateDecision d =
- InstanceEntitlementGate.decide(true, false, false, Optional.empty(), false, 0L);
+ InstanceEntitlementGate.decide(true, false, false, Optional.empty(), false, 0L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.MANUAL_FREE, d.reason());
}
@Test
- void billable_notLinked_blocksWithLinkSignal() {
+ void billable_notLinked_underGrant_allowsOnTheFreeTier() {
+ GateDecision d =
+ InstanceEntitlementGate.decide(
+ true, true, false, Optional.empty(), false, 0L, 500L);
+ assertTrue(d.allowed());
+ assertEquals(Reason.FREE_TIER, d.reason());
+ }
+
+ @Test
+ void billable_notLinked_lastUnitOfGrant_stillAllows() {
GateDecision d =
- InstanceEntitlementGate.decide(true, true, false, Optional.empty(), false, 0L);
+ InstanceEntitlementGate.decide(true, true, false, Optional.empty(), false, 0L, 1L);
+ assertTrue(d.allowed());
+ assertEquals(Reason.FREE_TIER, d.reason());
+ }
+
+ @Test
+ void billable_notLinked_grantSpent_blocksWithoutAskingForAnAccount() {
+ // Must be distinguishable from an over-limit linked team: here linking buys more.
+ GateDecision d =
+ InstanceEntitlementGate.decide(true, true, false, Optional.empty(), false, 0L, 0L);
assertFalse(d.allowed());
- assertEquals(Reason.NOT_LINKED, d.reason());
+ assertEquals(Reason.FREE_TIER_EXHAUSTED, d.reason());
+ }
+
+ @Test
+ void billable_notLinked_grantOverspent_blocks() {
+ // A negative balance must read as exhausted, not wrap back into "units remain".
+ GateDecision d =
+ InstanceEntitlementGate.decide(
+ true, true, false, Optional.empty(), false, 0L, -20L);
+ assertFalse(d.allowed());
+ assertEquals(Reason.FREE_TIER_EXHAUSTED, d.reason());
+ }
+
+ @Test
+ void manualTool_neverCountsAgainstTheGrant_evenWhenSpent() {
+ GateDecision d =
+ InstanceEntitlementGate.decide(true, false, false, Optional.empty(), false, 0L, 0L);
+ assertTrue(d.allowed());
+ assertEquals(Reason.MANUAL_FREE, d.reason());
}
@Test
void billable_linked_entitlementUnreachable_withinGrace_failsOpen() {
GateDecision d =
- InstanceEntitlementGate.decide(true, true, true, Optional.empty(), false, 0L);
+ InstanceEntitlementGate.decide(true, true, true, Optional.empty(), false, 0L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.FAIL_OPEN, d.reason());
}
@@ -80,7 +123,7 @@ class InstanceEntitlementGateTest {
@Test
void billable_linked_entitlementUnreachable_graceExpired_blocks() {
GateDecision d =
- InstanceEntitlementGate.decide(true, true, true, Optional.empty(), true, 0L);
+ InstanceEntitlementGate.decide(true, true, true, Optional.empty(), true, 0L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.GRACE_EXPIRED, d.reason());
}
@@ -88,7 +131,8 @@ class InstanceEntitlementGateTest {
@Test
void billable_linked_freePoolAvailable_allows() {
GateDecision d =
- InstanceEntitlementGate.decide(true, true, true, Optional.of(free()), false, 0L);
+ InstanceEntitlementGate.decide(
+ true, true, true, Optional.of(free()), false, 0L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.ENTITLED, d.reason());
}
@@ -98,7 +142,8 @@ class InstanceEntitlementGateTest {
// free() has 100 free units left per the last sync; 100 accrued locally since would exhaust
// it once charged, so the gate stops here in real time rather than waiting for the sync.
GateDecision d =
- InstanceEntitlementGate.decide(true, true, true, Optional.of(free()), false, 100L);
+ InstanceEntitlementGate.decide(
+ true, true, true, Optional.of(free()), false, 100L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.OVER_LIMIT, d.reason());
}
@@ -107,7 +152,8 @@ class InstanceEntitlementGateTest {
void billable_linked_unsubscribed_pendingLocalUsageLeavesRoom_allows() {
// 99 pending against 100 remaining → one unit of grant still projected free → allow.
GateDecision d =
- InstanceEntitlementGate.decide(true, true, true, Optional.of(free()), false, 99L);
+ InstanceEntitlementGate.decide(
+ true, true, true, Optional.of(free()), false, 99L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.ENTITLED, d.reason());
}
@@ -116,7 +162,7 @@ class InstanceEntitlementGateTest {
void billable_linked_unsubscribedAndExhausted_blocksOverLimit() {
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(exhaustedUnsubscribed()), false, 0L);
+ true, true, true, Optional.of(exhaustedUnsubscribed()), false, 0L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.OVER_LIMIT, d.reason());
}
@@ -125,7 +171,7 @@ class InstanceEntitlementGateTest {
void billable_linked_subscribedWithinCap_allows() {
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(subscribedWithinCap()), false, 0L);
+ true, true, true, Optional.of(subscribedWithinCap()), false, 0L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.ENTITLED, d.reason());
}
@@ -134,7 +180,7 @@ class InstanceEntitlementGateTest {
void billable_linked_subscribedOverCap_blocks() {
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(subscribedOverCap()), false, 0L);
+ true, true, true, Optional.of(subscribedOverCap()), false, 0L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.OVER_LIMIT, d.reason());
}
@@ -146,7 +192,7 @@ class InstanceEntitlementGateTest {
// projected spend to 105 → the gate stops now, not after the next sync reconciles.
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(subscribedWithinCap()), false, 95L);
+ true, true, true, Optional.of(subscribedWithinCap()), false, 95L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.OVER_LIMIT, d.reason());
}
@@ -156,7 +202,7 @@ class InstanceEntitlementGateTest {
// 10 synced + 80 pending = 90 < 100 cap → still room.
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(subscribedWithinCap()), false, 80L);
+ true, true, true, Optional.of(subscribedWithinCap()), false, 80L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.ENTITLED, d.reason());
}
@@ -169,7 +215,7 @@ class InstanceEntitlementGateTest {
new InstanceEntitlement(true, 50, 0, 100L, EntitlementState.OK);
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(subscribedWithGrant), false, 40L);
+ true, true, true, Optional.of(subscribedWithGrant), false, 40L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.ENTITLED, d.reason());
}
@@ -181,7 +227,7 @@ class InstanceEntitlementGateTest {
new InstanceEntitlement(true, 0, 999, null, EntitlementState.OK);
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(uncapped), false, 500L);
+ true, true, true, Optional.of(uncapped), false, 500L, 0L);
assertTrue(d.allowed());
assertEquals(Reason.ENTITLED, d.reason());
}
@@ -193,7 +239,8 @@ class InstanceEntitlementGateTest {
InstanceEntitlement revoked =
new InstanceEntitlement(false, 0, 0, null, EntitlementState.REVOKED);
GateDecision d =
- InstanceEntitlementGate.decide(true, true, true, Optional.of(revoked), false, 0L);
+ InstanceEntitlementGate.decide(
+ true, true, true, Optional.of(revoked), false, 0L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.REVOKED, d.reason());
}
@@ -205,7 +252,7 @@ class InstanceEntitlementGateTest {
new InstanceEntitlement(false, 5, 0, null, EntitlementState.OVER_LIMIT);
GateDecision d =
InstanceEntitlementGate.decide(
- true, true, true, Optional.of(conflicting), false, 0L);
+ true, true, true, Optional.of(conflicting), false, 0L, 0L);
assertFalse(d.allowed());
assertEquals(Reason.OVER_LIMIT, d.reason());
}
@@ -214,7 +261,12 @@ class InstanceEntitlementGateTest {
private InstanceEntitlementGate gate(AccountLinkProperties props) {
return new InstanceEntitlementGate(
- props, credentialStore, entitlementCache, syncStateRepository, localUsageService);
+ props,
+ credentialStore,
+ entitlementCache,
+ syncStateRepository,
+ localUsageService,
+ freeTierUsageService);
}
private static AccountLinkProperties props(boolean meteringEnabled, int graceDays) {
@@ -283,6 +335,45 @@ class InstanceEntitlementGateTest {
assertEquals(Reason.OVER_LIMIT, d.reason());
}
+ @Test
+ void evaluate_unlinked_readsTheLocalGrantAndNotTheCloudWallet() {
+ when(credentialStore.isLinked()).thenReturn(false);
+ when(freeTierUsageService.balance()).thenReturn(grant(120));
+
+ GateDecision d = gate(props(true, 3)).evaluate(true);
+
+ assertTrue(d.allowed());
+ assertEquals(Reason.FREE_TIER, d.reason());
+ verify(entitlementCache, never()).current();
+ verify(localUsageService, never()).currentPeriodUnsynced();
+ }
+
+ @Test
+ void evaluate_unlinked_grantSpent_blocks() {
+ when(credentialStore.isLinked()).thenReturn(false);
+ when(freeTierUsageService.balance()).thenReturn(grant(0));
+
+ GateDecision d = gate(props(true, 3)).evaluate(true);
+
+ assertFalse(d.allowed());
+ assertEquals(Reason.FREE_TIER_EXHAUSTED, d.reason());
+ }
+
+ @Test
+ void evaluate_linked_ignoresTheLocalGrantEntirely() {
+ // The ledgers are separate in both directions.
+ when(credentialStore.isLinked()).thenReturn(true);
+ when(entitlementCache.current()).thenReturn(Optional.of(free()));
+ when(localUsageService.currentPeriodUnsynced())
+ .thenReturn(new LocalUsageService.LocalUsage(LocalDateTime.now(), 0, 0, 0, 0));
+
+ GateDecision d = gate(props(true, 3)).evaluate(true);
+
+ assertTrue(d.allowed());
+ assertEquals(Reason.ENTITLED, d.reason());
+ verify(freeTierUsageService, never()).balance();
+ }
+
@Test
void evaluate_subscribedCapped_localUsageWouldExceedCap_blocksInRealTime() {
// Subscribed within cap per the last sync (spend 10 / cap 100), but 90 accrued locally
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java
index 06b99e0eb5..210ad277e4 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java
@@ -1,13 +1,13 @@
package stirling.software.proprietary.accountlink;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.time.LocalDateTime;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
@@ -20,6 +20,7 @@ class InstanceEntitlementGateWiringTest {
private DeviceCredentialStore store;
private EntitlementCache cache;
private LocalUsageService localUsage;
+ private FreeTierUsageService freeTier;
private InstanceEntitlementGate gate;
@BeforeEach
@@ -29,13 +30,21 @@ class InstanceEntitlementGateWiringTest {
store = mock(DeviceCredentialStore.class);
cache = mock(EntitlementCache.class);
localUsage = mock(LocalUsageService.class);
+ freeTier = mock(FreeTierUsageService.class);
gate =
new InstanceEntitlementGate(
properties,
store,
cache,
mock(AccountLinkSyncStateRepository.class),
- localUsage);
+ localUsage,
+ freeTier);
+ }
+
+ private static FreeTierUsageService.FreeTierBalance grant(long remaining) {
+ LocalDateTime start = LocalDateTime.of(2026, 9, 1, 0, 0);
+ return new FreeTierUsageService.FreeTierBalance(
+ 500, 500 - remaining, remaining, start, start.plusMonths(1));
}
@Test
@@ -48,11 +57,12 @@ class InstanceEntitlementGateWiringTest {
}
@Test
- void billableUnlinkedDoesNotHitCache() {
+ void billableUnlinkedReadsTheLocalGrantNotTheCache() {
when(store.isLinked()).thenReturn(false);
+ when(freeTier.balance()).thenReturn(grant(10));
GateDecision d = gate.evaluate(true);
- assertFalse(d.allowed());
- assertEquals(GateDecision.Reason.NOT_LINKED, d.reason());
+ assertTrue(d.allowed());
+ assertEquals(GateDecision.Reason.FREE_TIER, d.reason());
verify(cache, never()).current();
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
index 4d35d009c5..b6261a3382 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
@@ -43,11 +43,12 @@ class InstanceEntitlementInterceptorTest {
@Mock private InstanceEntitlementGate gate;
@Mock private EntitlementCache entitlementCache;
@Mock private ObjectProvider<UsageMeterService> meterProvider;
+ @Mock private FreeTierUsageService freeTierUsageService;
@Mock private TempFileManager tempFileManager;
private InstanceEntitlementInterceptor interceptor() {
return new InstanceEntitlementInterceptor(
- gate, entitlementCache, meterProvider, tempFileManager);
+ gate, entitlementCache, meterProvider, freeTierUsageService, tempFileManager);
}
private boolean preHandle(MockHttpServletResponse response) throws Exception {
@@ -67,16 +68,61 @@ class InstanceEntitlementInterceptorTest {
}
@Test
- void blocksWith402AndLinkSignalWhenGateBlocks() throws Exception {
+ void blocksWith402AndTheTerminalReasonWhenGateBlocks() throws Exception {
when(gate.evaluate(anyBoolean()))
- .thenReturn(GateDecision.block(GateDecision.Reason.NOT_LINKED));
+ .thenReturn(GateDecision.block(GateDecision.Reason.FREE_TIER_EXHAUSTED));
MockHttpServletResponse response = new MockHttpServletResponse();
assertFalse(preHandle(response));
assertEquals(HttpStatus.PAYMENT_REQUIRED.value(), response.getStatus());
assertEquals("application/json", response.getContentType());
assertTrue(response.getContentAsString().contains("ACCOUNT_LINK_REQUIRED"));
- assertTrue(response.getContentAsString().contains("NOT_LINKED"));
+ assertTrue(response.getContentAsString().contains("FREE_TIER_EXHAUSTED"));
+ }
+
+ @Test
+ void metersTheFreeTierLedgerWhenUnlinked() throws Exception {
+ // FREE_TIER is the gate saying "unlinked, inside the grant", so the op must land on the
+ // local ledger with the compiled-in policy and never touch the cloud one.
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.FREE_TIER));
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ verify(freeTierUsageService).accrue(eq(BillingCategory.AI), eq(1L), isNull());
+ verifyNoInteractions(entitlementCache, meterProvider);
+ }
+
+ @Test
+ void manualToolNeverReachesEitherLedger() throws Exception {
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.MANUAL_FREE));
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/rotate-pdf");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ verifyNoInteractions(freeTierUsageService, entitlementCache, meterProvider);
+ }
+
+ @Test
+ void blockedFreeTierRequestAccruesNothing() throws Exception {
+ when(gate.evaluate(anyBoolean()))
+ .thenReturn(GateDecision.block(GateDecision.Reason.FREE_TIER_EXHAUSTED));
+
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ verifyNoInteractions(freeTierUsageService, entitlementCache, meterProvider);
}
@Test
@@ -158,9 +204,9 @@ class InstanceEntitlementInterceptorTest {
@Test
void gatesPolicyRunUpFrontEvenWithoutAutomationHeader() throws Exception {
// The policy /run call carries no automation header, but must be blocked up front (not
- // after its first tool) when the instance is unlinked.
+ // after its first tool) when the allowance is spent.
when(gate.evaluate(anyBoolean()))
- .thenReturn(GateDecision.block(GateDecision.Reason.NOT_LINKED));
+ .thenReturn(GateDecision.block(GateDecision.Reason.FREE_TIER_EXHAUSTED));
InstanceEntitlementInterceptor interceptor = interceptor();
MockHttpServletRequest req =
@@ -179,8 +225,6 @@ class InstanceEntitlementInterceptorTest {
// here), so the /run request itself never accrues usage.
when(gate.evaluate(anyBoolean()))
.thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
- UsageMeterService meter = mock(UsageMeterService.class);
- when(meterProvider.getIfAvailable()).thenReturn(meter);
InstanceEntitlementInterceptor interceptor = interceptor();
MockHttpServletRequest req =
@@ -189,7 +233,7 @@ class InstanceEntitlementInterceptorTest {
interceptor.preHandle(req, resp, new Object());
interceptor.afterCompletion(req, resp, new Object(), null);
- verifyNoInteractions(meter);
+ verifyNoInteractions(meterProvider, freeTierUsageService);
}
private static InstanceEntitlement entitled(UnitCalcPolicy policy, LocalDateTime period) {
diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
index 7853c56856..19cc6cd2a2 100644
--- a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
@@ -81,6 +81,8 @@ public final class SaasSchemaOwnership {
Set.of(
"account_link_connect_state",
"account_link_device_credential",
+ "account_link_free_tier_period",
+ "account_link_free_tier_usage",
"account_link_metered_signature",
"account_link_sync_state",
"account_link_usage_counter",
diff --git a/frontend/editor/.env.proprietary b/frontend/editor/.env.proprietary
index 4d25e380da..75ee70ec61 100644
--- a/frontend/editor/.env.proprietary
+++ b/frontend/editor/.env.proprietary
@@ -24,4 +24,4 @@ VITE_SAAS_SUPABASE_ANON_KEY=
# ATTENDED portal -> SaaS reads (wallet, billing, plans, checkout) with the
# admin's Supabase JWT. Distinct from the local backend (reached same-origin via
# the editor's vite proxy). Absent -> wallet/billing surfaces stay on the mock.
-VITE_SAAS_API_URL=
+VITE_SAAS_API_URL=https://api2.stirling.com
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index b9d481e21d..55dcf80c8c 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7062,6 +7062,7 @@ title = "SaaS login not configured"
[portal.accountLink.connect]
close = "Close"
+exhaustedLede = "This server has used its free credits for the month. They reset when the period rolls over. Connecting a Stirling account adds a further monthly allowance on top."
notNow = "Not now"
start = "Connect Stirling account"
step = "Step {{current}} of {{total}}"
@@ -7114,11 +7115,6 @@ going = "Taking you to stirling.com"
reauthLede = "Your Stirling session expired. Signing in again keeps usage and billing visible. This server stays connected either way."
title = "Connecting"
-[portal.accountLink.gate]
-error = "Couldn't check the Stirling account connection"
-loading = "Checking the Stirling account connection..."
-retry = "Try again"
-
[portal.accountLink.instances]
active = "Active"
revoke = "Revoke"
@@ -7148,6 +7144,7 @@ never = "never"
[portal.accountLink.modal]
cancel = "Cancel"
continueReauth = "Sign in again"
+exhaustedTitle = "Add more monthly credits"
linkTitle = "Connect your Stirling account"
noAuthorizeUrl = "Stirling did not return somewhere to continue. Try again in a moment."
reauthTitle = "Sign in again"
@@ -7173,7 +7170,7 @@ title = "Couldn't load linked instances"
[portal.accountLink.rail]
cta = "Connect"
later = "Not now"
-sub = "Unlocks teams, PDF processor, pipelines, and policies. PDF editing stays free."
+sub = "Adds monthly credits and room for more users. Everything on this server already works without one."
title = "Connect your Stirling account"
[portal.accountLink.state]
@@ -9750,6 +9747,21 @@ loadWallet = "Couldn't load wallet"
openStripePortal = "Couldn't open Stripe portal"
walletUnavailable = "Wallet unavailable: {{status}} {{statusText}}"
+[portal.usage.freeTier]
+adminOnly = "This server's monthly credits are shared by everyone on it, so only an administrator can see the figures. Everything you can run stays available."
+barAria = "Free credits remaining"
+capSuffix_one = "of {{allowance}} free credit left this month"
+capSuffix_other = "of {{allowance}} free credits left this month"
+connect = "Connect a Stirling account"
+loadError = "Couldn't read this server's credit usage. Try again in a moment."
+loadErrorTitle = "Couldn't load credit usage"
+resets = "Resets {{date}}"
+statusLabel_one = "{{used}} used"
+statusLabel_other = "{{used}} used"
+subtitle = "What this server has processed against its monthly credits."
+title_one = "{{allowance}} free credit every month"
+title_other = "{{allowance}} free credits every month"
+
[portal.usage.sessionExpired]
action = "Sign in again"
body = "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked."
diff --git a/frontend/editor/src/portal-saas/hooks/useAdminNavVisible.test.ts b/frontend/editor/src/portal-saas/hooks/useAdminNavVisible.test.ts
new file mode 100644
index 0000000000..af9a602584
--- /dev/null
+++ b/frontend/editor/src/portal-saas/hooks/useAdminNavVisible.test.ts
@@ -0,0 +1,10 @@
+import { describe, expect, it } from "vitest";
+import { renderHook } from "@testing-library/react";
+// Resolves to the SaaS override (src/portal-saas) via the @portal cascade.
+import { useAdminNavVisible } from "@portal/hooks/useAdminNavVisible";
+
+describe("useAdminNavVisible (SaaS)", () => {
+ it("keeps admin-gated entries visible, since the billing page renders for any member", () => {
+ expect(renderHook(() => useAdminNavVisible()).result.current).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/portal-saas/hooks/useAdminNavVisible.ts b/frontend/editor/src/portal-saas/hooks/useAdminNavVisible.ts
new file mode 100644
index 0000000000..c7bd224ee0
--- /dev/null
+++ b/frontend/editor/src/portal-saas/hooks/useAdminNavVisible.ts
@@ -0,0 +1,8 @@
+/**
+ * SaaS has no server-admin concept: the signed-in account IS the SaaS account, and portal-saas'
+ * billing gate renders for any member of it. Inheriting the self-hosted check would leave that page
+ * reachable only by typed URL.
+ */
+export function useAdminNavVisible(): boolean {
+ return true;
+}
diff --git a/frontend/editor/src/portal/PortalProviders.tsx b/frontend/editor/src/portal/PortalProviders.tsx
index 6b7749b3c3..76b2655dd8 100644
--- a/frontend/editor/src/portal/PortalProviders.tsx
+++ b/frontend/editor/src/portal/PortalProviders.tsx
@@ -5,14 +5,15 @@ import { LinkAccountModal } from "@portal/components/account-link/LinkAccountMod
import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";
import { ConnectCallbackHost } from "@portal/components/account-link/ConnectCallbackHost";
import { PortalChrome } from "@portal/components/PortalChrome";
-import { useConnectPrompt } from "@portal/hooks/useConnectPrompt";
+import { useFreeTierExhaustedPrompt } from "@portal/hooks/useFreeTierExhaustedPrompt";
/** The one and only account-link modal, whichever step it is on. */
function LinkModalHost() {
const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =
useUI();
- // Ask once a session while the instance is unlinked, rather than waiting to be found.
- useConnectPrompt();
+ // Being unlinked prompts nothing: the free tier is the whole product. The only unprompted ask is
+ // the server reporting the month's grant spent.
+ useFreeTierExhaustedPrompt();
// Mounted only while open, so closing discards the flow. Kept mounted, an interrupted hand-off
// stays flagged and every later open resumes on the ghost step with no way forward.
diff --git a/frontend/editor/src/portal/ViewRouter.tsx b/frontend/editor/src/portal/ViewRouter.tsx
index 00387430d2..239104fef6 100644
--- a/frontend/editor/src/portal/ViewRouter.tsx
+++ b/frontend/editor/src/portal/ViewRouter.tsx
@@ -16,7 +16,6 @@ import { Sources } from "@portal/views/Sources";
import { Integrations } from "@portal/views/Integrations";
import { Infrastructure } from "@portal/views/Infrastructure";
import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";
-import { ConnectGuardedRoute } from "@portal/components/account-link/ConnectGuardedRoute";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
import { useUI } from "@portal/contexts/UIContext";
@@ -65,24 +64,13 @@ export function ViewRouter() {
<Route index element={<Home />} />
<Route path={rel(VIEW_PATHS.users)} element={<Users />} />
<Route path={rel(VIEW_PATHS.pipelines)} element={<Pipelines />} />
- {/* Building and editing need a linked account. Gated at the route so every way in is
- covered: the list, the Documents review queue, the Connect flow's next steps, and a
- typed URL. */}
<Route
path={`${rel(VIEW_PATHS.pipelines)}/new`}
- element={
- <ConnectGuardedRoute fallback={toPortalPath(VIEW_PATHS.pipelines)}>
- <PipelineBuilder />
- </ConnectGuardedRoute>
- }
+ element={<PipelineBuilder />}
/>
<Route
path={`${rel(VIEW_PATHS.pipelines)}/:id`}
- element={
- <ConnectGuardedRoute fallback={toPortalPath(VIEW_PATHS.pipelines)}>
- <PipelineBuilder />
- </ConnectGuardedRoute>
- }
+ element={<PipelineBuilder />}
/>
<Route path={rel(VIEW_PATHS.sources)} element={<Sources />} />
{/* Source create/edit is a modal on the list now; old deep links land there. */}
diff --git a/frontend/editor/src/portal/api/http.ts b/frontend/editor/src/portal/api/http.ts
index fb4f62cb8e..d34d9c62ea 100644
--- a/frontend/editor/src/portal/api/http.ts
+++ b/frontend/editor/src/portal/api/http.ts
@@ -42,6 +42,7 @@
* admin and uses the Supabase JWT for SaaS reads. Don't add it here.
*/
import { getPortalSaasToken } from "@portal/auth/portalSaasSession";
+import { reportAccountLinkBlock } from "@portal/services/accountLinkBlock";
import { resolveDemoResponse } from "@portal/api/demoData";
import { saasApiBase } from "@portal/api/saasApiBase";
import {
@@ -130,7 +131,12 @@ async function unwrap<T>(res: Response): Promise<T> {
} catch {
// ignore — non-JSON error response
}
- throw new HttpError(res.status, res.statusText, body);
+ const error = new HttpError(res.status, res.statusText, body);
+ // The instance's entitlement gate answers a spent free grant here, and the prompt it raises is
+ // the actionable surface. Reported for every domain rather than only the local one because the
+ // classifier keys on a sentinel only the local backend sends, so a SaaS 402 cannot reach it.
+ reportAccountLinkBlock(error);
+ throw error;
}
// 204 / empty-body responses have nothing to parse.
if (res.status === 204 || res.headers.get("Content-Length") === "0") {
diff --git a/frontend/editor/src/portal/api/link.ts b/frontend/editor/src/portal/api/link.ts
index c3684b3dd2..0e773f8dc0 100644
--- a/frontend/editor/src/portal/api/link.ts
+++ b/frontend/editor/src/portal/api/link.ts
@@ -17,6 +17,19 @@ export interface LocalUsage {
totalUnsyncedUnits: number;
}
+/**
+ * The instance's own monthly grant. {@code remainingUnits} is floored at 0; dormant while linked.
+ */
+export interface FreeTierBalance {
+ grantUnits: number;
+ usedUnits: number;
+ remainingUnits: number;
+ /** ISO local timestamp, inclusive. */
+ periodStart: string;
+ /** ISO local timestamp, exclusive — when the grant resets. */
+ periodEnd: string;
+}
+
/** A linked instance row (GET /api/v1/account-link/instances). */
export interface LinkedInstanceRow {
instanceId: number;
@@ -45,6 +58,14 @@ export async function fetchLocalUsage(): Promise<LocalUsage> {
return apiClient.local.json<LocalUsage>(`${BASE}/usage`);
}
+/**
+ * Admin-only server-side, the allowance being instance-wide: a caller must render a 403 as figures
+ * it may not see, not as a fault.
+ */
+export async function fetchFreeTier(): Promise<FreeTierBalance> {
+ return apiClient.local.json<FreeTierBalance>(`${BASE}/free-tier`);
+}
+
/** Drop this instance's link. */
export async function unlinkInstance(): Promise<void> {
await apiClient.local.json<void>(`${BASE}/unlink`, { method: "POST" });
diff --git a/frontend/editor/src/portal/api/policies.test.ts b/frontend/editor/src/portal/api/policies.test.ts
index 9ea68ff5fb..3ea4f6ce0e 100644
--- a/frontend/editor/src/portal/api/policies.test.ts
+++ b/frontend/editor/src/portal/api/policies.test.ts
@@ -45,12 +45,12 @@ function classificationPolicy(required: boolean): Policy {
describe("parseSimplePolicy", () => {
it("carries required through so the wizard reopens org-mandated", () => {
- const entry = parseSimplePolicy(classificationPolicy(true));
+ const entry = parseSimplePolicy(classificationPolicy(true), []);
expect(entry?.policy?.state.required).toBe(true);
});
it("keeps a non-required policy non-required", () => {
- const entry = parseSimplePolicy(classificationPolicy(false));
+ const entry = parseSimplePolicy(classificationPolicy(false), []);
expect(entry?.policy?.state.required).toBe(false);
});
@@ -65,10 +65,50 @@ describe("parseSimplePolicy", () => {
},
editor: { allowed: true, runOn: "export" },
};
- const entry = parseSimplePolicy(policy);
+ const entry = parseSimplePolicy(policy, []);
expect(entry?.policy?.state.runOn).toBe("export");
expect(entry?.policy?.state.runsOnEditor).toBe(true);
});
+
+ it("carries the run history of the policy it was handed", () => {
+ const policy = classificationPolicy(true);
+ const runs = [
+ {
+ runId: "admin:r1",
+ policyId: policy.id,
+ status: "COMPLETED",
+ currentStep: 2,
+ stepCount: 2,
+ error: null,
+ errorCode: null,
+ errorSubscribed: null,
+ outputs: [{ fileName: "invoice_redacted.pdf" }],
+ createdAt: Date.now(),
+ fileName: null,
+ },
+ // A run belonging to some other policy must not leak in.
+ {
+ ...{},
+ runId: "admin:r2",
+ policyId: "other",
+ status: "COMPLETED",
+ currentStep: 1,
+ stepCount: 1,
+ error: null,
+ errorCode: null,
+ errorSubscribed: null,
+ outputs: [],
+ createdAt: Date.now(),
+ fileName: null,
+ },
+ ] as unknown as Parameters<typeof parseSimplePolicy>[1];
+
+ const entry = parseSimplePolicy(policy, runs);
+
+ expect(entry?.policy?.activity).toHaveLength(1);
+ expect(entry?.policy?.activity[0]?.doc).toBe("invoice_redacted.pdf");
+ expect(entry?.policy?.stats.enforced).toBe(1);
+ });
});
describe("buildWireFromSetup", () => {
@@ -78,7 +118,7 @@ describe("buildWireFromSetup", () => {
name: "My classifier",
icon: "shield",
};
- const entry = parseSimplePolicy(policy);
+ const entry = parseSimplePolicy(policy, []);
const wire = buildWireFromSetup(entry!, setupResult(), t);
expect(wire.icon).toBe("shield");
expect(wire.name).toBe("My classifier");
diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.ts
index 660b07c514..2fe40de500 100644
--- a/frontend/editor/src/portal/api/policies.ts
+++ b/frontend/editor/src/portal/api/policies.ts
@@ -17,6 +17,7 @@ import {
policyStepFromWire,
type PolicyToolId,
} from "@app/policies/operations";
+import { HttpError } from "@portal/api/http";
import type { Policy } from "@portal/api/pipelines";
import type {
PolicyDecodedState,
@@ -90,11 +91,22 @@ export function fetchPoliciesList(): Promise<WirePolicy[]> {
return apiClient.local.json<WirePolicy[]>("/api/v1/policies");
}
-/** GET /api/v1/policies/runs — best-effort (empty on a backend without runs). */
+/**
+ * GET /api/v1/policies/runs.
+ *
+ * <p>Only a 404 means "this backend has no run history", which is the case worth treating as an
+ * empty list. Swallowing every failure made an unreachable or forbidden endpoint render exactly
+ * like a policy that has never run, so a missing activity list could not be told from a broken one.
+ */
export function fetchPolicyRuns(): Promise<PolicyRunView[]> {
return apiClient.local
.json<PolicyRunView[]>("/api/v1/policies/runs")
- .catch(() => [] as PolicyRunView[]);
+ .catch((e: unknown) => {
+ if (e instanceof HttpError && e.status === 404) {
+ return [] as PolicyRunView[];
+ }
+ throw e;
+ });
}
/**
@@ -151,7 +163,7 @@ function isOrderedSubset<T>(inner: T[], outer: T[]): boolean {
*/
export function parseSimplePolicy(
policy: Policy,
- runs: PolicyRunView[] = [],
+ runs: PolicyRunView[],
): CatalogueEntry | null {
const rawCategory = policy.output?.options?.categoryId;
const categoryId = typeof rawCategory === "string" ? rawCategory : "";
diff --git a/frontend/editor/src/portal/components/ConnectAccountRail.tsx b/frontend/editor/src/portal/components/ConnectAccountRail.tsx
index 9f1e09c0ce..82c8048aa0 100644
--- a/frontend/editor/src/portal/components/ConnectAccountRail.tsx
+++ b/frontend/editor/src/portal/components/ConnectAccountRail.tsx
@@ -40,7 +40,7 @@ export function ConnectAccountRail() {
<span className="portal-connect-rail__sub">
{t(
"portal.accountLink.rail.sub",
- "Unlocks teams, PDF processor, pipelines, and policies. PDF editing stays free.",
+ "Adds monthly credits and room for more users. Everything on this server already works without one.",
)}
</span>
</div>
diff --git a/frontend/editor/src/portal/components/Sidebar.tsx b/frontend/editor/src/portal/components/Sidebar.tsx
index 6d4cad1945..dde5b01bfe 100644
--- a/frontend/editor/src/portal/components/Sidebar.tsx
+++ b/frontend/editor/src/portal/components/Sidebar.tsx
@@ -6,12 +6,12 @@ import { Logo } from "@app/ui/Logo";
import { NavFooter } from "@app/components/shared/navFooter/NavFooter";
import { useAccountIdentity } from "@app/hooks/useAccountIdentity";
import { useFreeCreditsSummary } from "@portal/hooks/useFreeCreditsSummary";
+import { useAdminNavVisible } from "@portal/hooks/useAdminNavVisible";
import { useOpenPlan } from "@portal/hooks/useOpenPlan";
import { useTranslation } from "react-i18next";
import { useView, type ViewId } from "@portal/contexts/ViewContext";
import { useUI } from "@portal/contexts/UIContext";
import { LinkAccountFooterItem } from "@portal/components/LinkAccountFooterItem";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
import { CloseIcon } from "@portal/components/icons";
import {
GROUP_PROCESSOR,
@@ -43,8 +43,8 @@ export function Sidebar() {
});
const { displayName, profilePictureUrl } = useAccountIdentity();
const credits = useFreeCreditsSummary();
+ const adminNavVisible = useAdminNavVisible();
const openPlan = useOpenPlan();
- const { gated, connect } = useConnectGate();
// Collapse is a desktop-only affordance: on mobile the sidebar is an
// off-canvas drawer, so the icon-rail state never applies there.
@@ -54,38 +54,37 @@ export function Sidebar() {
// a takeover modal (matching the marketing prototype).
function renderGroup(entries: NavEntry[]) {
- return entries.map((entry) => {
- const label = t(`portal.nav.${entry.id}`);
- const item = (
- <NavItem
- key={entry.id}
- id={entry.id}
- label={label}
- icon={entry.icon}
- isActive={activeView === entry.id}
- onClick={(id) => {
- // Route changes also close the drawer (AppShell), but re-selecting the
- // active view or opening an external tab changes no route — close here.
- closeMobileNav();
- if (entry.externalUrl) {
- window.open(entry.externalUrl, "_blank", "noopener,noreferrer");
- } else if (entry.requiresLink && gated) {
- // Ask here: navigating first strands them on a page with nothing on it.
- connect();
- } else {
- setActiveView(id as ViewId);
- }
- }}
- />
- );
- return collapsed ? (
- <Tooltip key={entry.id} label={label} position="right" withinPortal>
- <div className="portal-sidebar__navtip">{item}</div>
- </Tooltip>
- ) : (
- item
- );
- });
+ return entries
+ .filter((entry) => adminNavVisible || !entry.requiresAdmin)
+ .map((entry) => {
+ const label = t(`portal.nav.${entry.id}`);
+ const item = (
+ <NavItem
+ key={entry.id}
+ id={entry.id}
+ label={label}
+ icon={entry.icon}
+ isActive={activeView === entry.id}
+ onClick={(id) => {
+ // Route changes also close the drawer (AppShell), but re-selecting the
+ // active view or opening an external tab changes no route — close here.
+ closeMobileNav();
+ if (entry.externalUrl) {
+ window.open(entry.externalUrl, "_blank", "noopener,noreferrer");
+ } else {
+ setActiveView(id as ViewId);
+ }
+ }}
+ />
+ );
+ return collapsed ? (
+ <Tooltip key={entry.id} label={label} position="right" withinPortal>
+ <div className="portal-sidebar__navtip">{item}</div>
+ </Tooltip>
+ ) : (
+ item
+ );
+ });
}
return (
diff --git a/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsx b/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsx
deleted file mode 100644
index 7fbc2348ff..0000000000
--- a/frontend/editor/src/portal/components/account-link/ConnectGuardedRoute.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useEffect, type ReactNode } from "react";
-import { useTranslation } from "react-i18next";
-import { Banner, Button, Spinner } from "@app/ui";
-import { Navigate } from "react-router-dom";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
-
-interface Props {
- children: ReactNode;
- fallback: string;
-}
-
-/**
- * At the route, not on the buttons: the pipeline builder is reachable from its list, the Documents
- * queue, the connect flow's next steps and a typed URL, and a guard per entry point is one more to
- * remember each time someone adds a link.
- */
-export function ConnectGuardedRoute({ children, fallback }: Props) {
- const { t } = useTranslation();
- const { gated, loading, error, retry, connect } = useConnectGate();
-
- useEffect(() => {
- if (gated) connect();
- }, [gated, connect]);
-
- if (error)
- return (
- <Banner
- tone="danger"
- title={t("portal.accountLink.gate.error")}
- description={error}
- action={
- <Button onClick={retry}>{t("portal.accountLink.gate.retry")}</Button>
- }
- />
- );
- if (loading) return <Spinner label={t("portal.accountLink.gate.loading")} />;
- if (gated) return <Navigate to={fallback} replace />;
- return <>{children}</>;
-}
diff --git a/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx b/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx
index 2b6315eb17..cb35772595 100644
--- a/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx
+++ b/frontend/editor/src/portal/components/account-link/LinkAccountModal.tsx
@@ -10,6 +10,7 @@ import {
type ConnectOutcome,
} from "@portal/components/account-link/ConnectCallbackView";
import { useConnectHandoff } from "@portal/hooks/useConnectHandoff";
+import type { LinkModalMode } from "@portal/contexts/UIContext";
import "@portal/views/ConnectCallback.css";
/**
@@ -24,7 +25,7 @@ interface Props {
open: boolean;
onClose: () => void;
/** "reauth" only re-establishes the browser session, so it stays one step with no pitch. */
- mode?: "link" | "reauth";
+ mode?: LinkModalMode;
/** Published by the callback route; present means the admin is returning from Stirling. */
outcome?: ConnectOutcome | null;
}
@@ -41,6 +42,7 @@ export function LinkAccountModal({
}: Props) {
const { t } = useTranslation();
const reauth = mode === "reauth";
+ const exhausted = mode === "exhausted";
const handoff = useConnectHandoff(reauth);
// Busy outranks a stale outcome, or a retry sits on the old result until the browser leaves.
@@ -87,10 +89,15 @@ export function LinkAccountModal({
return t("portal.accountLink.modal.reauthTitle", "Sign in again");
}
if (step === "ask") {
- return t(
- "portal.accountLink.modal.linkTitle",
- "Connect your Stirling account",
- );
+ return exhausted
+ ? t(
+ "portal.accountLink.modal.exhaustedTitle",
+ "Add more monthly credits",
+ )
+ : t(
+ "portal.accountLink.modal.linkTitle",
+ "Connect your Stirling account",
+ );
}
if (step === "handoff") {
return t("portal.accountLink.connect.handoff.title", "Connecting");
@@ -104,7 +111,13 @@ export function LinkAccountModal({
function stepBody() {
switch (step) {
case "ask":
- return <ConnectAskStep reauth={reauth} error={handoff.error} />;
+ return (
+ <ConnectAskStep
+ reauth={reauth}
+ exhausted={exhausted}
+ error={handoff.error}
+ />
+ );
case "handoff":
return <ConnectHandoffGhost />;
case "outcome":
diff --git a/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx b/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx
index 7c795645b7..5dc580d120 100644
--- a/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx
+++ b/frontend/editor/src/portal/components/account-link/connect/ConnectAskStep.tsx
@@ -7,11 +7,16 @@ import "@portal/components/account-link/connect/connect.css";
interface Props {
/** Re-auth says why it is being asked; a first link is pitched instead. */
reauth: boolean;
+ /**
+ * Reached by spending this month's local free grant. Leads with the allowance connecting adds,
+ * because whatever the caller was doing already works without an account.
+ */
+ exhausted?: boolean;
/** A hand-off that failed to start drops back here, so this is where its reason belongs. */
error?: string | null;
}
-export function ConnectAskStep({ reauth, error }: Props) {
+export function ConnectAskStep({ reauth, exhausted = false, error }: Props) {
const { t } = useTranslation();
return (
@@ -24,7 +29,17 @@ export function ConnectAskStep({ reauth, error }: Props) {
)}
</p>
) : (
- <ConnectBenefitsSlide />
+ <>
+ {exhausted && (
+ <p className="portal-connect__lede">
+ {t(
+ "portal.accountLink.connect.exhaustedLede",
+ "This server has used its free credits for the month. They reset when the period rolls over. Connecting a Stirling account adds a further monthly allowance on top.",
+ )}
+ </p>
+ )}
+ <ConnectBenefitsSlide />
+ </>
)}
{!isSaasSupabaseConfigured && (
diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx
new file mode 100644
index 0000000000..a2283ef660
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx
@@ -0,0 +1,102 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { PortalTestProviders } from "@portal/test/TestQueryProvider";
+
+/**
+ * The unlinked usage page reads the instance's own ledger and nothing else — no wallet, so no
+ * claim about linkage — and it has to survive the endpoint being admin-only, since a non-admin can
+ * hold a portal grant and reach this page.
+ */
+const { fetchFreeTier, openLinkModal } = vi.hoisted(() => ({
+ fetchFreeTier: vi.fn(),
+ openLinkModal: vi.fn(),
+}));
+
+vi.mock("@portal/api/link", () => ({ fetchFreeTier }));
+vi.mock("@portal/contexts/UIContext", () => ({
+ useUI: () => ({ openLinkModal }),
+}));
+vi.mock("@portal/components/billing/FreePdfEditorsCard", () => ({
+ FreePdfEditorsCard: () => null,
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ // Interpolated so the figures themselves are what the assertions read.
+ t: (_key: string, fallback: string, vars?: Record<string, unknown>) =>
+ typeof fallback === "string" && vars
+ ? fallback.replace(/\{\{(\w+)\}\}/g, (_m, n) => String(vars[n] ?? ""))
+ : fallback,
+ i18n: { changeLanguage: vi.fn() },
+ }),
+}));
+
+import { HttpError } from "@portal/api/http";
+import { FreeTierPlanView } from "@portal/components/billing/FreeTierPlanView";
+
+const BALANCE = {
+ grantUnits: 500,
+ usedUnits: 120,
+ remainingUnits: 380,
+ periodStart: "2026-09-01T00:00:00",
+ periodEnd: "2026-10-01T00:00:00",
+};
+
+const renderView = () =>
+ render(
+ <PortalTestProviders>
+ <MemoryRouter>
+ <FreeTierPlanView />
+ </MemoryRouter>
+ </PortalTestProviders>,
+ );
+
+describe("FreeTierPlanView", () => {
+ beforeEach(() => {
+ fetchFreeTier.mockReset();
+ openLinkModal.mockReset();
+ });
+
+ it("renders the local meter: used, grant, remaining and when it resets", async () => {
+ fetchFreeTier.mockResolvedValue(BALANCE);
+ renderView();
+ expect(await screen.findByText("380")).toBeInTheDocument();
+ expect(
+ screen.getByText("of 500 free credits left this month"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("120 used")).toBeInTheDocument();
+ expect(screen.getByText(/^Resets /)).toBeInTheDocument();
+ });
+
+ it("reads only the instance's own ledger", async () => {
+ fetchFreeTier.mockResolvedValue(BALANCE);
+ renderView();
+ await screen.findByText("380");
+ expect(fetchFreeTier).toHaveBeenCalledTimes(1);
+ });
+
+ it("offers the account as more allowance, and asks for it only on request", async () => {
+ fetchFreeTier.mockResolvedValue(BALANCE);
+ renderView();
+ await screen.findByText("380");
+ expect(openLinkModal).not.toHaveBeenCalled();
+ expect(screen.getByText("Connect a Stirling account")).toBeInTheDocument();
+ });
+
+ it("tells a non-admin the figures are not theirs to see, rather than failing", async () => {
+ fetchFreeTier.mockRejectedValue(new HttpError(403, "Forbidden", null));
+ renderView();
+ expect(
+ await screen.findByText(/only an administrator/),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Couldn't load credit usage")).toBeNull();
+ });
+
+ it("reports a real failure as one", async () => {
+ fetchFreeTier.mockRejectedValue(new HttpError(500, "Server Error", null));
+ renderView();
+ expect(
+ await screen.findByText("Couldn't load credit usage"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx
new file mode 100644
index 0000000000..6007c47c94
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx
@@ -0,0 +1,164 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Banner, Button, Card, Skeleton } from "@app/ui";
+import { formatPeriodDate, MeterBar, remainingMeter } from "@app/billing";
+import { fetchFreeTier, type FreeTierBalance } from "@portal/api/link";
+import { HttpError } from "@portal/api/http";
+import { useUI } from "@portal/contexts/UIContext";
+import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";
+
+/** {@code forbidden} is an outcome, not a failure: the endpoint is admin-only. */
+type Load =
+ | { state: "loading" }
+ | { state: "ready"; balance: FreeTierBalance }
+ | { state: "forbidden" }
+ | { state: "failed" };
+
+/**
+ * Usage & billing for an instance with no Stirling account. Reads the local endpoint only: loading
+ * a wallet here would assert linkage the browser's SaaS session cannot vouch for.
+ */
+export function FreeTierPlanView() {
+ const { t } = useTranslation();
+ const { openLinkModal } = useUI();
+ // An outcome, not a rendered message: the effect must not depend on `t`, whose identity is
+ // not stable across renders.
+ const [load, setLoad] = useState<Load>({ state: "loading" });
+
+ useEffect(() => {
+ let cancelled = false;
+ fetchFreeTier()
+ .then((balance) => {
+ if (!cancelled) setLoad({ state: "ready", balance });
+ })
+ .catch((e: unknown) => {
+ if (cancelled) return;
+ const denied =
+ e instanceof HttpError && (e.status === 401 || e.status === 403);
+ setLoad({ state: denied ? "forbidden" : "failed" });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return (
+ <div className="portal-usage portal-billing">
+ <header className="portal-usage__header">
+ <div className="portal-usage__header-inner">
+ <div>
+ <h1 className="portal-usage__title">
+ {t("portal.usage.title", "Usage & billing")}
+ </h1>
+ <p className="portal-usage__subtitle">
+ {t(
+ "portal.usage.freeTier.subtitle",
+ "What this server has processed against its monthly credits.",
+ )}
+ </p>
+ </div>
+ <Button variant="secondary" fat onClick={() => openLinkModal()}>
+ {t("portal.usage.freeTier.connect", "Connect a Stirling account")}
+ </Button>
+ </div>
+ </header>
+
+ <div className="portal-usage__body">
+ {load.state === "loading" && (
+ <div className="portal-billing__skeleton" aria-hidden>
+ <Skeleton height="10rem" />
+ <Skeleton height="14rem" />
+ </div>
+ )}
+
+ {load.state === "failed" && (
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.usage.freeTier.loadErrorTitle",
+ "Couldn't load credit usage",
+ )}
+ >
+ {t(
+ "portal.usage.freeTier.loadError",
+ "Couldn't read this server's credit usage. Try again in a moment.",
+ )}
+ </Banner>
+ )}
+
+ {load.state !== "loading" && <FreePdfEditorsCard />}
+
+ {load.state === "forbidden" && (
+ <Card padding="loose">
+ <p className="portal-billing__section-sub">
+ {t(
+ "portal.usage.freeTier.adminOnly",
+ "This server's monthly credits are shared by everyone on it, so only an administrator can see the figures. Everything you can run stays available.",
+ )}
+ </p>
+ </Card>
+ )}
+
+ {load.state === "ready" && <FreeTierMeter balance={load.balance} />}
+ </div>
+ </div>
+ );
+}
+
+function FreeTierMeter({ balance }: { balance: FreeTierBalance }) {
+ const { t } = useTranslation();
+ const { state, pct } = remainingMeter(
+ balance.remainingUnits,
+ balance.grantUnits,
+ );
+ const resets = formatPeriodDate(balance.periodEnd);
+
+ return (
+ <Card padding="loose">
+ <div className="portal-billing__subscription-head">
+ <div>
+ <h2 className="portal-billing__meter-title">
+ {t(
+ "portal.usage.freeTier.title",
+ "{{allowance}} free credits every month",
+ {
+ count: balance.grantUnits,
+ allowance: balance.grantUnits.toLocaleString(),
+ },
+ )}
+ </h2>
+ </div>
+ </div>
+ <div className="portal-billing__trial-meter">
+ <MeterBar
+ state={state}
+ pct={pct}
+ barLabel={t(
+ "portal.usage.freeTier.barAria",
+ "Free credits remaining",
+ )}
+ figure={balance.remainingUnits.toLocaleString()}
+ capSuffix={t(
+ "portal.usage.freeTier.capSuffix",
+ "of {{allowance}} free credits left this month",
+ {
+ count: balance.grantUnits,
+ allowance: balance.grantUnits.toLocaleString(),
+ },
+ )}
+ statusLabel={t("portal.usage.freeTier.statusLabel", "{{used}} used", {
+ count: balance.usedUnits,
+ used: balance.usedUnits.toLocaleString(),
+ })}
+ meta={
+ resets
+ ? t("portal.usage.freeTier.resets", "Resets {{date}}", {
+ date: resets,
+ })
+ : null
+ }
+ />
+ </div>
+ </Card>
+ );
+}
diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
index 097eebd52e..c21414ee0f 100644
--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx
@@ -1,12 +1,16 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
-import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { MemoryRouter } from "react-router-dom";
/**
- * Usage must not render while unlinked: it reports `linked` as a fact from its wallet read, so a
- * browser holding a SaaS session with no link to this server would flip the whole portal to linked.
+ * Which usage page this instance has one of. The unlinked half must not go anywhere near the
+ * wallet: {@code onWalletLoaded} reports `linked` as a fact, and a browser can hold a SaaS session
+ * with no link to this server, so loading a wallet there would flip the whole portal to linked.
*/
const gate = { gated: false, loading: false, available: true };
+// Administrator by default: the page is theirs, and one case below is the member.
+const admin = { is: true };
+const link = { is: false };
const connect = vi.fn();
const applyLinkFacts = vi.fn();
@@ -15,68 +19,96 @@ vi.mock("@portal/hooks/useConnectGate", () => ({
}));
vi.mock("@portal/contexts/LinkContext", () => ({
useApplyLinkFacts: () => applyLinkFacts,
+ useLinkOptional: () => ({ isLinked: link.is }),
}));
vi.mock("@portal/contexts/UIContext", () => ({
useUI: () => ({ openLinkModal: vi.fn() }),
}));
+vi.mock("@portal/hooks/usePortalAdmin", () => ({
+ usePortalAdmin: () => admin.is,
+}));
vi.mock("@portal/views/Usage", () => ({
Usage: ({ onWalletLoaded }: { onWalletLoaded?: (w: unknown) => void }) => {
onWalletLoaded?.({ status: "free" });
return <div data-testid="usage" />;
},
}));
+vi.mock("@portal/components/billing/FreeTierPlanView", () => ({
+ FreeTierPlanView: () => <div data-testid="free-tier" />,
+}));
import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";
const renderGate = () =>
render(
<MemoryRouter initialEntries={["/processor/usage"]}>
- <Routes>
- <Route path="/processor/usage" element={<PortalBillingGate />} />
- <Route path="/processor" element={<div data-testid="home" />} />
- </Routes>
+ <PortalBillingGate />
</MemoryRouter>,
);
describe("PortalBillingGate — self-hosted", () => {
beforeEach(() => {
+ admin.is = true;
+ link.is = false;
connect.mockReset();
applyLinkFacts.mockReset();
gate.gated = false;
gate.loading = false;
});
- it("asks for the connection when reached unconnected", () => {
+ it("shows the instance's own meter when there is no account, rather than a bounce", () => {
gate.gated = true;
renderGate();
- expect(connect).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId("free-tier")).toBeInTheDocument();
+ expect(screen.queryByTestId("usage")).toBeNull();
});
- it("sends them back rather than onto a page about an account they lack", () => {
+ it("asks for nothing on the way in", () => {
gate.gated = true;
renderGate();
- expect(screen.queryByTestId("usage")).toBeNull();
- expect(screen.getByTestId("home")).toBeInTheDocument();
+ expect(connect).not.toHaveBeenCalled();
});
it("never reports the instance as linked while it is not", () => {
gate.gated = true;
renderGate();
- // Not rendering the page is what stops the claim.
+ // Keeping the unlinked page off the wallet is what stops the claim.
expect(applyLinkFacts).not.toHaveBeenCalled();
});
- it("holds while the capability is still unknown, rather than bouncing", () => {
+ it("commits to neither page while the answer is unknown", () => {
gate.loading = true;
renderGate();
expect(screen.queryByTestId("usage")).toBeNull();
- expect(screen.queryByTestId("home")).toBeNull();
+ expect(screen.queryByTestId("free-tier")).toBeNull();
});
- it("renders the page once connected", () => {
+ it("renders the wallet page, unchanged, once linked", () => {
+ link.is = true;
renderGate();
- expect(connect).not.toHaveBeenCalled();
expect(screen.getByTestId("usage")).toBeInTheDocument();
+ expect(screen.queryByTestId("free-tier")).toBeNull();
expect(applyLinkFacts).toHaveBeenCalledWith(true, false);
});
+
+ it("keeps an unlinked instance off the wallet even when nothing gates it", () => {
+ // Linking turned off, or a status check that failed: neither is "gated", and neither may
+ // reach a SaaS this instance has no address for.
+ gate.gated = false;
+ renderGate();
+
+ expect(screen.getByTestId("free-tier")).toBeInTheDocument();
+ expect(screen.queryByTestId("usage")).toBeNull();
+ expect(applyLinkFacts).not.toHaveBeenCalled();
+ });
+
+ it("gives a member no page at all, whatever the link state", async () => {
+ admin.is = false;
+ gate.gated = true;
+ renderGate();
+
+ expect(screen.queryByTestId("free-tier")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("usage")).not.toBeInTheDocument();
+ expect(applyLinkFacts).not.toHaveBeenCalled();
+ });
});
diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx
index b02ed7db29..2e09894710 100644
--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx
+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx
@@ -1,22 +1,28 @@
import { useCallback } from "react";
-import { useApplyLinkFacts } from "@portal/contexts/LinkContext";
+import {
+ useApplyLinkFacts,
+ useLinkOptional,
+} from "@portal/contexts/LinkContext";
import { useUI } from "@portal/contexts/UIContext";
-import { ConnectGuardedRoute } from "@portal/components/account-link/ConnectGuardedRoute";
-import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
+import { useConnectGate } from "@portal/hooks/useConnectGate";
+import { usePortalAdmin } from "@portal/hooks/usePortalAdmin";
+import { FreeTierPlanView } from "@portal/components/billing/FreeTierPlanView";
import { Usage } from "@portal/views/Usage";
import type { Wallet } from "@portal/api/billing";
/**
- * The seam the SaaS build shadows, and the backstop for a typed URL — the nav already refuses to
- * come here unlinked (the sidebar's requiresLink).
+ * The seam the SaaS build shadows: picks which usage page this instance has one of.
*
- * <p>Usage must not render while unlinked: {@link onWalletLoaded} reports linked as a fact, and the
- * browser can hold a SaaS session with no link to this server, so rendering it flipped the portal
- * to linked.
+ * <p>Two sources, never one: {@link onWalletLoaded} reports {@code linked} as a fact, and a
+ * browser can hold a SaaS session with no link to this server, so routing the unlinked page through
+ * the wallet would flip the whole portal to linked.
*/
export function PortalBillingGate() {
const applyLinkFacts = useApplyLinkFacts();
const { openLinkModal } = useUI();
+ const { loading } = useConnectGate();
+ const isAdmin = usePortalAdmin();
+ const link = useLinkOptional();
const onWalletLoaded = useCallback(
(w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),
@@ -24,9 +30,14 @@ export function PortalBillingGate() {
);
const onReauth = useCallback(() => openLinkModal("reauth"), [openLinkModal]);
- return (
- <ConnectGuardedRoute fallback={toPortalPath(VIEW_PATHS.home)}>
- <Usage onWalletLoaded={onWalletLoaded} onReauth={onReauth} />
- </ConnectGuardedRoute>
- );
+ // Administrators only: the figures are instance-wide and the endpoints ADMIN-gated. The nav
+ // hides the entry to match, so this is the backstop for a typed URL.
+ if (!isAdmin) return null;
+ // Neither page while the answer is unknown: showing the local meter to a linked instance would
+ // present a dormant ledger as its live one.
+ if (loading) return null;
+ // A positively known link, not merely "not gated": linking turned off and a failed status
+ // check are neither, and must not reach a SaaS this instance has no address for.
+ if (!link?.isLinked) return <FreeTierPlanView />;
+ return <Usage onWalletLoaded={onWalletLoaded} onReauth={onReauth} />;
}
diff --git a/frontend/editor/src/portal/components/sidebarGroups.tsx b/frontend/editor/src/portal/components/sidebarGroups.tsx
index 274fb915ba..a72298e3be 100644
--- a/frontend/editor/src/portal/components/sidebarGroups.tsx
+++ b/frontend/editor/src/portal/components/sidebarGroups.tsx
@@ -18,8 +18,8 @@ export interface NavEntry {
icon: ReactNode;
/** When set, the tab opens this URL in a new tab instead of navigating in-app. */
externalUrl?: string;
- /** The whole tab is facts about the linked account, so unlinked is asked rather than navigated. */
- requiresLink?: boolean;
+ /** Hidden from a member. The view reports instance-wide figures behind ADMIN-gated endpoints. */
+ requiresAdmin?: boolean;
}
export interface NavGroup {
@@ -46,6 +46,6 @@ export const GROUP_PLATFORM: NavEntry[] = [
{ id: "users", icon: <UsersIcon /> },
{ id: "integrations", icon: <IntegrationsIcon /> },
{ id: "infrastructure", icon: <InfrastructureIcon /> },
- { id: "usage", icon: <UsageIcon />, requiresLink: true },
+ { id: "usage", icon: <UsageIcon />, requiresAdmin: true },
{ id: "docs", icon: <DocsIcon /> },
];
diff --git a/frontend/editor/src/portal/contexts/UIContext.tsx b/frontend/editor/src/portal/contexts/UIContext.tsx
index b116486271..b4df9c5618 100644
--- a/frontend/editor/src/portal/contexts/UIContext.tsx
+++ b/frontend/editor/src/portal/contexts/UIContext.tsx
@@ -7,6 +7,13 @@ import {
} from "react";
import type { ConnectOutcome } from "@portal/components/account-link/ConnectCallbackView";
+/**
+ * Why the dialog is open. All three run the same handshake; the mode only chooses the pitch.
+ *
+ * <p>{@code reauth} must NOT re-register, which would mint a duplicate device credential.
+ */
+export type LinkModalMode = "link" | "reauth" | "exhausted";
+
interface UIContextValue {
/** Off-canvas sidebar drawer on small screens (no-op chrome on desktop). */
mobileNavOpen: boolean;
@@ -39,13 +46,8 @@ interface UIContextValue {
* login modal closes, so the admin returns to where they were.
*/
linkModalOpen: boolean;
- /**
- * "link" registers this instance (the normal first-time flow); "reauth" only
- * refreshes an expired SaaS session for attended reads — it must NOT re-register
- * (that would mint a duplicate device credential).
- */
- linkModalMode: "link" | "reauth";
- openLinkModal: (mode?: "link" | "reauth") => void;
+ linkModalMode: LinkModalMode;
+ openLinkModal: (mode?: LinkModalMode) => void;
closeLinkModal: () => void;
/**
* A one-shot signal like {@link UIContextValue.trialSetupRequested}: the callback route and the
@@ -98,7 +100,7 @@ export function UIProvider({ children }: { children: ReactNode }) {
>(null);
const [linkModalOpen, setLinkModalOpen] = useState(false);
const [trialSetupRequested, setTrialSetupRequested] = useState(false);
- const [linkModalMode, setLinkModalMode] = useState<"link" | "reauth">("link");
+ const [linkModalMode, setLinkModalMode] = useState<LinkModalMode>("link");
const [connectOutcome, setConnectOutcome] = useState<ConnectOutcome | null>(
null,
);
@@ -147,7 +149,7 @@ export function UIProvider({ children }: { children: ReactNode }) {
linkModalOpen,
linkModalMode,
- openLinkModal: (mode: "link" | "reauth" = "link") => {
+ openLinkModal: (mode: LinkModalMode = "link") => {
setMobileNavOpen(false);
setLinkModalMode(mode);
// Never stack on Settings: close it first, and remember to reopen it on
diff --git a/frontend/editor/src/portal/hooks/connectGateStatus.test.tsx b/frontend/editor/src/portal/hooks/connectGateStatus.test.tsx
deleted file mode 100644
index c3f5bc9e05..0000000000
--- a/frontend/editor/src/portal/hooks/connectGateStatus.test.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- act,
- fireEvent,
- render,
- screen,
- waitFor,
-} from "@testing-library/react";
-import { MemoryRouter, Route, Routes } from "react-router-dom";
-import { ConnectGuardedRoute } from "@portal/components/account-link/ConnectGuardedRoute";
-import { PortalTestProviders } from "@portal/test/TestQueryProvider";
-import { LinkProvider } from "@portal/contexts/LinkContext";
-import { UIProvider } from "@portal/contexts/UIContext";
-
-/** Over the real provider stack: pins apart not-yet-known, never-knowable and truly unlinked. */
-const { json, fetchStatus, guardedAction } = vi.hoisted(() => ({
- json: vi.fn(),
- fetchStatus: vi.fn(),
- guardedAction: vi.fn(),
-}));
-vi.mock("@portal/api/http", () => ({
- apiClient: { local: { json } },
- errorMessage: String,
-}));
-vi.mock("@portal/api/link", () => ({
- fetchStatus,
- unlinkInstance: vi.fn(),
-}));
-vi.mock("@portal/auth/saasSupabase", () => ({
- isSaasSupabaseConfigured: false,
-}));
-
-import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
-
-function Probe() {
- const { gated, available, guard } = useConnectGate();
- return (
- <>
- <span data-testid="g">{`${available ? "avail" : "unavail"}:${gated ? "gated" : "open"}`}</span>
- <button onClick={guard(guardedAction)}>Guarded action</button>
- </>
- );
-}
-
-const renderStack = (path = "/processor/pipelines/new") =>
- render(
- <PortalTestProviders>
- <LinkProvider initialState="unlinked" statusKnown={false}>
- <UIProvider>
- <AccountLinkProvider>
- <MemoryRouter initialEntries={[path]}>
- <Probe />
- <Routes>
- <Route
- path="/processor/pipelines/:id"
- element={
- <ConnectGuardedRoute fallback="/processor/pipelines">
- <h1>Pipeline builder</h1>
- </ConnectGuardedRoute>
- }
- />
- <Route
- path="/processor/pipelines"
- element={<h1>Pipelines list</h1>}
- />
- </Routes>
- </MemoryRouter>
- </AccountLinkProvider>
- </UIProvider>
- </LinkProvider>
- </PortalTestProviders>,
- );
-
-const state = () => screen.getByTestId("g").textContent;
-const configSaysAvailable = () =>
- json.mockResolvedValue({ accountLinkAvailable: true });
-
-beforeEach(() => {
- vi.clearAllMocks();
- json.mockReset();
- fetchStatus.mockReset();
-});
-afterEach(() => {
- sessionStorage.clear();
- window.history.replaceState({}, "", "/");
-});
-
-const builder = () =>
- screen.queryByRole("heading", { name: "Pipeline builder" });
-const assertActionBlocked = () => {
- fireEvent.click(screen.getByRole("button", { name: "Guarded action" }));
- expect(guardedAction).not.toHaveBeenCalled();
-};
-const retry = () =>
- fireEvent.click(
- screen.getByRole("button", { name: "portal.accountLink.gate.retry" }),
- );
-
-describe("connect gate and the link status", () => {
- it("waits visibly for status without opening the builder or guarded actions", async () => {
- configSaysAvailable();
- let resolve!: (v: unknown) => void;
- fetchStatus.mockReturnValue(new Promise((r) => (resolve = r)));
- renderStack();
- await waitFor(() => expect(state()).toBe("avail:open"));
- expect(
- screen.getByRole("status", { name: "portal.accountLink.gate.loading" }),
- ).toBeInTheDocument();
- expect(builder()).not.toBeInTheDocument();
- assertActionBlocked();
- await act(async () => resolve({ linked: true, name: "acme" }));
- expect(builder()).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: "Guarded action" }));
- expect(guardedAction).toHaveBeenCalledTimes(1);
- });
-
- it.each([true, false])(
- "retries a failed status check and respects linked=%s",
- async (linked) => {
- configSaysAvailable();
- fetchStatus
- .mockRejectedValueOnce(new Error("Status unavailable"))
- .mockResolvedValue({ linked, name: linked ? "acme" : null });
- renderStack();
- await screen.findByText("portal.accountLink.gate.error");
- expect(builder()).not.toBeInTheDocument();
- assertActionBlocked();
- retry();
- await screen.findByRole("heading", {
- name: linked ? "Pipeline builder" : "Pipelines list",
- });
- expect(fetchStatus).toHaveBeenCalledTimes(2);
- expect(
- screen.queryByText("portal.accountLink.gate.error"),
- ).not.toBeInTheDocument();
- },
- );
-
- it("does not honor the old dev bypass URL or stored flag for an unlinked instance", async () => {
- window.history.replaceState({}, "", "/processor?bypassConnect=true");
- sessionStorage.setItem("accountLink::dev-bypass", "true");
- configSaysAvailable();
- fetchStatus.mockResolvedValue({ linked: false, name: null });
- renderStack();
- await screen.findByRole("heading", { name: "Pipelines list" });
- expect(builder()).not.toBeInTheDocument();
- assertActionBlocked();
- });
-
- it("blocks when app configuration fails and retries without assuming linking is disabled", async () => {
- json
- .mockRejectedValueOnce(new Error("Configuration unavailable"))
- .mockResolvedValue({ accountLinkAvailable: false });
- fetchStatus.mockRejectedValue(new Error("No status endpoint"));
- renderStack();
- await screen.findByText("portal.accountLink.gate.error");
- expect(builder()).not.toBeInTheDocument();
- assertActionBlocked();
- retry();
- await screen.findByRole("heading", { name: "Pipeline builder" });
- expect(json).toHaveBeenCalledTimes(2);
- });
-});
-
-describe("pipeline routes with unknown link status", () => {
- it.each([
- ["/processor/pipelines/new", false],
- ["/processor/pipelines/plc-1", false],
- ["/processor/pipelines/new", true],
- ["/processor/pipelines/plc-1", true],
- ])(
- "requires status for %s only when linking is available (%s)",
- async (path, accountLinkAvailable) => {
- json.mockResolvedValue({ accountLinkAvailable });
- fetchStatus.mockRejectedValue(new Error("Link status unavailable"));
- renderStack(path);
- if (accountLinkAvailable) {
- await screen.findByText("portal.accountLink.gate.error");
- expect(builder()).not.toBeInTheDocument();
- } else {
- await screen.findByRole("heading", { name: "Pipeline builder" });
- expect(
- screen.queryByText("portal.accountLink.gate.error"),
- ).not.toBeInTheDocument();
- }
- expect(
- screen.queryByRole("heading", { name: "Pipelines list" }),
- ).not.toBeInTheDocument();
- },
- );
-});
diff --git a/frontend/editor/src/portal/hooks/useAdminNavVisible.test.ts b/frontend/editor/src/portal/hooks/useAdminNavVisible.test.ts
new file mode 100644
index 0000000000..9e82b63cf1
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useAdminNavVisible.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+const admin = { is: false };
+vi.mock("@portal/hooks/usePortalAdmin", () => ({
+ usePortalAdmin: () => admin.is,
+}));
+
+import { useAdminNavVisible } from "@portal/hooks/useAdminNavVisible";
+
+describe("useAdminNavVisible (self-hosted)", () => {
+ it("follows server-admin status, which is what the gated entries mean", () => {
+ admin.is = true;
+ expect(renderHook(() => useAdminNavVisible()).result.current).toBe(true);
+
+ admin.is = false;
+ expect(renderHook(() => useAdminNavVisible()).result.current).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/portal/hooks/useAdminNavVisible.ts b/frontend/editor/src/portal/hooks/useAdminNavVisible.ts
new file mode 100644
index 0000000000..5629557325
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useAdminNavVisible.ts
@@ -0,0 +1,13 @@
+import { usePortalAdmin } from "@portal/hooks/usePortalAdmin";
+
+/**
+ * Whether nav entries marked {@code requiresAdmin} appear. Those entries are gated on
+ * administering this instance, which is what self-hosted means by admin.
+ *
+ * <p>A seam because SaaS means something else by it: Supabase sessions carry no admin flag, so the
+ * same check there would hide billing from every cloud user while portal-saas' own billing gate
+ * still renders the page for them.
+ */
+export function useAdminNavVisible(): boolean {
+ return usePortalAdmin();
+}
diff --git a/frontend/editor/src/portal/hooks/useConnectGate.test.tsx b/frontend/editor/src/portal/hooks/useConnectGate.test.tsx
index c9d3731f17..db31724175 100644
--- a/frontend/editor/src/portal/hooks/useConnectGate.test.tsx
+++ b/frontend/editor/src/portal/hooks/useConnectGate.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { PortalTestProviders } from "@portal/test/TestQueryProvider";
import { LinkProvider, type LinkState } from "@portal/contexts/LinkContext";
import { UIProvider } from "@portal/contexts/UIContext";
@@ -18,13 +18,19 @@ vi.mock("@portal/api/http", () => ({
import { useConnectGate } from "@portal/hooks/useConnectGate";
function Probe() {
- const { gated, loading, available } = useConnectGate();
+ const { gated, loading, available, error, retry } = useConnectGate();
return (
- <span data-testid="state">
- {loading
- ? "loading"
- : `${available ? "available" : "unavailable"}:${gated ? "gated" : "open"}`}
- </span>
+ <>
+ <span data-testid="state">
+ {loading
+ ? "loading"
+ : `${available ? "available" : "unavailable"}:${gated ? "gated" : "open"}`}
+ </span>
+ <span data-testid="error">{error ?? "none"}</span>
+ <button type="button" onClick={retry}>
+ retry
+ </button>
+ </>
);
}
@@ -90,4 +96,38 @@ describe("useConnectGate", () => {
renderProbe("unlinked");
expect(screen.getByTestId("state").textContent).toBe("loading");
});
+
+ it("reports a configuration failure rather than reading it as linking disabled", async () => {
+ json.mockRejectedValue(new Error("Configuration unavailable"));
+ renderProbe("unlinked");
+
+ // Not "loading": hanging on a call that already failed is the blank page from #7926.
+ await settled("unavailable:open");
+ await waitFor(() =>
+ expect(screen.getByTestId("error").textContent).toContain(
+ "Configuration unavailable",
+ ),
+ );
+ });
+
+ it("clears the failure on retry and gates on the answer it then gets", async () => {
+ json
+ .mockRejectedValueOnce(new Error("Configuration unavailable"))
+ .mockResolvedValue({ accountLinkAvailable: true });
+ renderProbe("unlinked");
+ await settled("unavailable:open");
+
+ fireEvent.click(screen.getByRole("button", { name: "retry" }));
+
+ await settled("available:gated");
+ expect(screen.getByTestId("error").textContent).toBe("none");
+ });
+
+ it("honours no dev bypass, in the URL or in storage", async () => {
+ window.history.replaceState({}, "", "/processor?bypassConnect=true");
+ sessionStorage.setItem("accountLink::dev-bypass", "true");
+ json.mockResolvedValue({ accountLinkAvailable: true });
+ renderProbe("unlinked");
+ await settled("available:gated");
+ });
});
diff --git a/frontend/editor/src/portal/hooks/useConnectPrompt.test.tsx b/frontend/editor/src/portal/hooks/useConnectPrompt.test.tsx
deleted file mode 100644
index dc54fce35c..0000000000
--- a/frontend/editor/src/portal/hooks/useConnectPrompt.test.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-import { render, waitFor } from "@testing-library/react";
-
-/**
- * The cadence decision: dismissible, but it always comes back. Persisting "seen" would end the ask
- * after one dismissal, so the marker has to be session scoped and has to be written when the prompt
- * opens rather than when it closes, or an admin who ignores the dialog gets it again on every
- * re-render.
- */
-const { connect, gate } = vi.hoisted(() => ({
- connect: vi.fn(),
- gate: { gated: true, loading: false, available: true },
-}));
-
-vi.mock("@portal/hooks/useConnectGate", () => ({
- useConnectGate: () => ({ ...gate, connect, guard: (f: unknown) => f }),
-}));
-
-import { useConnectPrompt } from "@portal/hooks/useConnectPrompt";
-
-function Probe() {
- useConnectPrompt();
- return null;
-}
-
-describe("useConnectPrompt", () => {
- beforeEach(() => {
- connect.mockReset();
- sessionStorage.clear();
- gate.gated = true;
- gate.loading = false;
- });
-
- it("opens the flow once while unlinked", async () => {
- render(<Probe />);
- await waitFor(() => expect(connect).toHaveBeenCalledTimes(1));
- });
-
- it("does not open again in the same session", async () => {
- const { unmount } = render(<Probe />);
- await waitFor(() => expect(connect).toHaveBeenCalledTimes(1));
- unmount();
- render(<Probe />);
- await waitFor(() => expect(connect).toHaveBeenCalledTimes(1));
- });
-
- it("asks again in a fresh session", async () => {
- render(<Probe />).unmount();
- await waitFor(() => expect(connect).toHaveBeenCalledTimes(1));
- sessionStorage.clear();
- render(<Probe />);
- await waitFor(() => expect(connect).toHaveBeenCalledTimes(2));
- });
-
- it("never persists beyond the session", async () => {
- render(<Probe />);
- await waitFor(() => expect(connect).toHaveBeenCalledTimes(1));
- expect(localStorage.length).toBe(0);
- });
-
- it("stays quiet when the instance is not gated", async () => {
- gate.gated = false;
- render(<Probe />);
- await new Promise((r) => setTimeout(r, 0));
- expect(connect).not.toHaveBeenCalled();
- });
-
- it("waits for the capability rather than prompting on an unknown", async () => {
- gate.loading = true;
- render(<Probe />);
- await new Promise((r) => setTimeout(r, 0));
- expect(connect).not.toHaveBeenCalled();
- });
-});
diff --git a/frontend/editor/src/portal/hooks/useConnectPrompt.ts b/frontend/editor/src/portal/hooks/useConnectPrompt.ts
deleted file mode 100644
index 0a751b5c86..0000000000
--- a/frontend/editor/src/portal/hooks/useConnectPrompt.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { useEffect, useRef } from "react";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
-
-const PROMPTED_KEY = "portal::connect-prompted";
-
-function alreadyPrompted(): boolean {
- try {
- return sessionStorage.getItem(PROMPTED_KEY) === "true";
- } catch {
- return false;
- }
-}
-
-function markPrompted(): void {
- try {
- sessionStorage.setItem(PROMPTED_KEY, "true");
- } catch {
- // Prompting again later is the harmless direction.
- }
-}
-
-/**
- * Session storage, not the onboarding localStorage helpers: one dismissal should not end the ask
- * for good, and asking once per visit needs no timer to tune.
- */
-export function useConnectPrompt(): void {
- const { gated, loading, connect } = useConnectGate();
- const fired = useRef(false);
-
- useEffect(() => {
- if (loading || !gated || fired.current || alreadyPrompted()) return;
- fired.current = true;
- // Marked on open, not on close, so a session gets one whatever the admin does with it.
- markPrompted();
- connect();
- }, [gated, loading, connect]);
-}
diff --git a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx
new file mode 100644
index 0000000000..4313736f92
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.test.tsx
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render } from "@testing-library/react";
+
+/**
+ * The cadence decision, reversed from what it was: being unlinked is not a reason to ask anything.
+ * The free tier is the product, so the only unprompted ask is the server reporting the month's
+ * grant spent — and it is raised from the real reporter here rather than a hand-fired event, so the
+ * sentinel shape stays part of what this pins down.
+ */
+const { openLinkModal } = vi.hoisted(() => ({ openLinkModal: vi.fn() }));
+
+vi.mock("@portal/contexts/UIContext", () => ({
+ useUI: () => ({ openLinkModal }),
+}));
+
+import { HttpError } from "@portal/api/http";
+import { reportAccountLinkBlock } from "@portal/services/accountLinkBlock";
+import { useFreeTierExhaustedPrompt } from "@portal/hooks/useFreeTierExhaustedPrompt";
+
+function Probe() {
+ useFreeTierExhaustedPrompt();
+ return null;
+}
+
+const blocked = (reason: string) =>
+ new HttpError(402, "Payment Required", {
+ error: "ACCOUNT_LINK_REQUIRED",
+ reason,
+ });
+
+describe("the account-link prompt", () => {
+ beforeEach(() => openLinkModal.mockReset());
+
+ it("stays quiet on mount while the instance is unlinked", () => {
+ render(<Probe />);
+ expect(openLinkModal).not.toHaveBeenCalled();
+ });
+
+ it("opens on the allowance pitch when the grant is reported spent", () => {
+ render(<Probe />);
+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));
+ expect(openLinkModal).toHaveBeenCalledWith("exhausted");
+ });
+
+ it("leaves a linked team's own billing problems to their own surface", () => {
+ render(<Probe />);
+ reportAccountLinkBlock(blocked("OVER_LIMIT"));
+ reportAccountLinkBlock(blocked("REVOKED"));
+ reportAccountLinkBlock(blocked("GRACE_EXPIRED"));
+ expect(openLinkModal).not.toHaveBeenCalled();
+ });
+
+ it("ignores an unrelated failure", () => {
+ render(<Probe />);
+ reportAccountLinkBlock(new HttpError(403, "Forbidden", null));
+ reportAccountLinkBlock(new Error("network"));
+ expect(openLinkModal).not.toHaveBeenCalled();
+ });
+
+ it("stops listening once unmounted", () => {
+ render(<Probe />).unmount();
+ reportAccountLinkBlock(blocked("FREE_TIER_EXHAUSTED"));
+ expect(openLinkModal).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts
new file mode 100644
index 0000000000..a259589f9a
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useFreeTierExhaustedPrompt.ts
@@ -0,0 +1,21 @@
+import { useEffect } from "react";
+import { useUI } from "@portal/contexts/UIContext";
+import { FREE_TIER_EXHAUSTED_EVENT } from "@portal/services/accountLinkBlock";
+
+/**
+ * Opens the account-link dialog on the "allowance spent" pitch when the instance reports a spent
+ * free grant. Mount once, alongside the dialog it opens.
+ *
+ * <p>The bridge is a window event rather than a call, because the reporter is the API client and has
+ * no React context to reach: same shape as the cloud build's usage-limit modals.
+ */
+export function useFreeTierExhaustedPrompt(): void {
+ const { openLinkModal } = useUI();
+
+ useEffect(() => {
+ const onExhausted = () => openLinkModal("exhausted");
+ window.addEventListener(FREE_TIER_EXHAUSTED_EVENT, onExhausted);
+ return () =>
+ window.removeEventListener(FREE_TIER_EXHAUSTED_EVENT, onExhausted);
+ }, [openLinkModal]);
+}
diff --git a/frontend/editor/src/portal/hooks/usePortalAdmin.ts b/frontend/editor/src/portal/hooks/usePortalAdmin.ts
new file mode 100644
index 0000000000..ee69b92397
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/usePortalAdmin.ts
@@ -0,0 +1,14 @@
+import { useAuth } from "@app/auth/UseSession";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
+
+/**
+ * Whether the signed-in account administers this instance.
+ *
+ * <p>Same two sources the editor's own gates use, session first: app config answers for a build
+ * with login off, where everyone is effectively the administrator.
+ */
+export function usePortalAdmin(): boolean {
+ const authState = useAuth();
+ const { config } = useAppConfig();
+ return authState.isAdmin ?? config?.isAdmin ?? false;
+}
diff --git a/frontend/editor/src/portal/queries/policies.ts b/frontend/editor/src/portal/queries/policies.ts
index 51a8c0ff55..5fb8f40332 100644
--- a/frontend/editor/src/portal/queries/policies.ts
+++ b/frontend/editor/src/portal/queries/policies.ts
@@ -38,5 +38,7 @@ export function usePoliciesOverview(): AsyncState<PoliciesResponse> {
() => (list.data ? assemblePolicies(list.data, runs.data ?? []) : null),
[list.data, runs.data],
);
- return { data, loading: list.loading, error: list.error };
+ // The runs failure is reported too. The catalogue still renders without it, but activity
+ // silently reading empty is what made a broken history look like an unused policy.
+ return { data, loading: list.loading, error: list.error ?? runs.error };
}
diff --git a/frontend/editor/src/portal/services/accountLinkBlock.test.ts b/frontend/editor/src/portal/services/accountLinkBlock.test.ts
new file mode 100644
index 0000000000..bc23ab49b9
--- /dev/null
+++ b/frontend/editor/src/portal/services/accountLinkBlock.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import { HttpError } from "@portal/api/http";
+import { classifyAccountLinkBlock } from "@portal/services/accountLinkBlock";
+
+/**
+ * Strict on purpose: an incidental 402 from anywhere else must not be turned into a pitch for an
+ * account, and an unknown reason must not be guessed at.
+ */
+describe("classifyAccountLinkBlock", () => {
+ const body = (extra: Record<string, unknown>) =>
+ new HttpError(402, "Payment Required", extra);
+
+ it("reads the reason off the gate's sentinel", () => {
+ expect(
+ classifyAccountLinkBlock(
+ body({ error: "ACCOUNT_LINK_REQUIRED", reason: "FREE_TIER_EXHAUSTED" }),
+ ),
+ ).toBe("FREE_TIER_EXHAUSTED");
+ expect(
+ classifyAccountLinkBlock(
+ body({ error: "ACCOUNT_LINK_REQUIRED", reason: "OVER_LIMIT" }),
+ ),
+ ).toBe("OVER_LIMIT");
+ });
+
+ it("declines a 402 that is not the account-link sentinel", () => {
+ expect(
+ classifyAccountLinkBlock(body({ error: "FEATURE_DEGRADED" })),
+ ).toBeNull();
+ expect(classifyAccountLinkBlock(body({}))).toBeNull();
+ expect(
+ classifyAccountLinkBlock(new HttpError(402, "Payment Required", null)),
+ ).toBeNull();
+ });
+
+ it("declines the sentinel on any other status", () => {
+ expect(
+ classifyAccountLinkBlock(
+ new HttpError(403, "Forbidden", {
+ error: "ACCOUNT_LINK_REQUIRED",
+ reason: "FREE_TIER_EXHAUSTED",
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it("declines a reason it does not know, rather than guessing", () => {
+ expect(
+ classifyAccountLinkBlock(
+ body({ error: "ACCOUNT_LINK_REQUIRED", reason: "FLAG_OFF" }),
+ ),
+ ).toBeNull();
+ expect(
+ classifyAccountLinkBlock(
+ body({ error: "ACCOUNT_LINK_REQUIRED", reason: 7 }),
+ ),
+ ).toBeNull();
+ });
+
+ it("declines anything that is not an error shape at all", () => {
+ expect(classifyAccountLinkBlock(null)).toBeNull();
+ expect(classifyAccountLinkBlock("402")).toBeNull();
+ expect(classifyAccountLinkBlock(new Error("network"))).toBeNull();
+ });
+});
diff --git a/frontend/editor/src/portal/services/accountLinkBlock.ts b/frontend/editor/src/portal/services/accountLinkBlock.ts
new file mode 100644
index 0000000000..2c8bfc9039
--- /dev/null
+++ b/frontend/editor/src/portal/services/accountLinkBlock.ts
@@ -0,0 +1,64 @@
+/**
+ * The `402 ACCOUNT_LINK_REQUIRED` sentinel, turned into a prompt.
+ *
+ * <p>Reactive, not predictive: the free tier needs no account, so the UI cannot know whether an
+ * action is affordable, and the balance endpoint is admin-only anyway. It runs the action and lets
+ * the answer raise the dialog.
+ *
+ * <p>Only {@code FREE_TIER_EXHAUSTED} is acted on. The others mean a linked team's cloud wallet is
+ * the problem, where offering to link would be nonsense, so they fall through to the caller.
+ */
+
+/** Bridge to the always-mounted host in PortalProviders. */
+export const FREE_TIER_EXHAUSTED_EVENT = "stirling:portal-free-tier-exhausted";
+
+/** Mirrors the backend {@code GateDecision.Reason} blocking arm. */
+export type AccountLinkBlockReason =
+ | "FREE_TIER_EXHAUSTED"
+ | "OVER_LIMIT"
+ | "REVOKED"
+ | "GRACE_EXPIRED";
+
+const BLOCK_REASONS: readonly string[] = [
+ "FREE_TIER_EXHAUSTED",
+ "OVER_LIMIT",
+ "REVOKED",
+ "GRACE_EXPIRED",
+];
+
+/**
+ * The gate's block reason, or null when this is not the account-link sentinel.
+ *
+ * <p>Strict on the status and the sentinel both, so an incidental 402 is not hijacked. Reads
+ * {@link HttpError} structurally to stay off the import cycle with the client that throws it.
+ */
+export function classifyAccountLinkBlock(
+ error: unknown,
+): AccountLinkBlockReason | null {
+ if (!error || typeof error !== "object") return null;
+ if ((error as { status?: unknown }).status !== 402) return null;
+ const body = (error as { body?: unknown }).body;
+ if (!body || typeof body !== "object") return null;
+ const sentinel = (body as { error?: unknown }).error;
+ if (sentinel !== "ACCOUNT_LINK_REQUIRED") return null;
+ const reason = (body as { reason?: unknown }).reason;
+ if (typeof reason !== "string" || !BLOCK_REASONS.includes(reason)) {
+ return null;
+ }
+ return reason as AccountLinkBlockReason;
+}
+
+/**
+ * Raises the prompt if {@code error} is a spent free grant, returning whether it did so a caller
+ * can leave its own error surface alone. Safe on any error, any number of times.
+ */
+export function reportAccountLinkBlock(error: unknown): boolean {
+ if (classifyAccountLinkBlock(error) !== "FREE_TIER_EXHAUSTED") return false;
+ try {
+ window.dispatchEvent(new Event(FREE_TIER_EXHAUSTED_EVENT));
+ } catch {
+ // Non-browser env (tests / SSR) — the throw must not replace the caller's own error.
+ return false;
+ }
+ return true;
+}
diff --git a/frontend/editor/src/portal/views/Integrations.test.tsx b/frontend/editor/src/portal/views/Integrations.test.tsx
index acf1f1b1b1..8c4e684bfa 100644
--- a/frontend/editor/src/portal/views/Integrations.test.tsx
+++ b/frontend/editor/src/portal/views/Integrations.test.tsx
@@ -13,16 +13,6 @@ import type { IntegrationConfig } from "@portal/api/integrations";
const render = (ui: Parameters<typeof baseRender>[0]) =>
baseRender(ui, { wrapper: MantineProvider });
-vi.mock("@portal/hooks/useConnectGate", () => ({
- useConnectGate: () => ({
- gated: false,
- loading: false,
- available: false,
- connect: vi.fn(),
- guard: (fn: unknown) => fn,
- }),
-}));
-
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
diff --git a/frontend/editor/src/portal/views/Integrations.tsx b/frontend/editor/src/portal/views/Integrations.tsx
index fc40feb1e9..1c25a6f152 100644
--- a/frontend/editor/src/portal/views/Integrations.tsx
+++ b/frontend/editor/src/portal/views/Integrations.tsx
@@ -31,7 +31,6 @@ import {
} from "@portal/components/sources/connectionTypes";
import { STEP_OPERATIONS } from "@portal/components/policies/stepOperations";
import { COMING_SOON_SOURCE_TYPES } from "@portal/components/sources/sourceTypes";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
import "@portal/theme/surface.css";
import "@portal/views/Integrations.css";
@@ -95,7 +94,6 @@ type IntegrationRow = {
export function Integrations() {
const { t } = useTranslation();
- const { guard } = useConnectGate();
const [connections, setConnections] = useState<IntegrationConfig[] | null>(
null,
);
@@ -214,23 +212,14 @@ export function Integrations() {
return counts;
}, [catalogue]);
- // Connecting an integration and editing one both need a linked account. Memoised
- // because both land in the row-building useMemo deps below.
- const openCreate = useMemo(
- () =>
- guard((typeId: string) => {
- setModal({ open: true, editing: null, fixedTypeId: typeId });
- }),
- [guard],
- );
+ // Stable identities: both land in the row-building useMemo deps below.
+ const openCreate = useCallback((typeId: string) => {
+ setModal({ open: true, editing: null, fixedTypeId: typeId });
+ }, []);
- const openEdit = useMemo(
- () =>
- guard((connection: IntegrationConfig) => {
- setModal({ open: true, editing: connection });
- }),
- [guard],
- );
+ const openEdit = useCallback((connection: IntegrationConfig) => {
+ setModal({ open: true, editing: connection });
+ }, []);
const remove = useCallback(
async (connection: IntegrationConfig) => {
diff --git a/frontend/editor/src/portal/views/Pipelines.test.tsx b/frontend/editor/src/portal/views/Pipelines.test.tsx
index 56b0bf0690..dba6d3c02d 100644
--- a/frontend/editor/src/portal/views/Pipelines.test.tsx
+++ b/frontend/editor/src/portal/views/Pipelines.test.tsx
@@ -29,16 +29,6 @@ const render = (
options?: Parameters<typeof baseRender>[1],
) => baseRender(ui, { wrapper: PortalTestProviders, ...options });
-vi.mock("@portal/hooks/useConnectGate", () => ({
- useConnectGate: () => ({
- gated: false,
- loading: false,
- available: false,
- connect: vi.fn(),
- guard: (fn: unknown) => fn,
- }),
-}));
-
// Deterministic i18n: keys returned verbatim. initReactI18next/Trans are exported too because the
// unified page pulls in modules (the policy wizard/catalogue) that reference them at import time.
vi.mock("react-i18next", () => ({
@@ -72,6 +62,7 @@ vi.mock("@portal/api/policies", async (importOriginal) => {
// pipelines list.
vi.mock("@portal/queries/policies", () => ({
usePoliciesOverview: () => ({ data: null, loading: false, error: null }),
+ usePolicyRuns: () => ({ data: [], loading: false, error: null }),
}));
const RESPONSE: PipelinesOverviewResponse = {
diff --git a/frontend/editor/src/portal/views/Pipelines.tsx b/frontend/editor/src/portal/views/Pipelines.tsx
index 1cd4e04c24..27b095bed3 100644
--- a/frontend/editor/src/portal/views/Pipelines.tsx
+++ b/frontend/editor/src/portal/views/Pipelines.tsx
@@ -7,7 +7,7 @@ import { Banner, Button, CardRail, EmptyState, Skeleton } from "@app/ui";
import { errorMessage } from "@portal/api/http";
import { useSectionFlags } from "@portal/hooks/useAsync";
import { usePipelines } from "@portal/queries/pipelines";
-import { usePoliciesOverview } from "@portal/queries/policies";
+import { usePoliciesOverview, usePolicyRuns } from "@portal/queries/policies";
import {
fetchPipeline,
savePipeline,
@@ -32,7 +32,6 @@ import { PolicyDetailPanel } from "@portal/components/policies/PolicyDetailPanel
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
import { useAiEngineEnabled } from "@portal/hooks/useAiEngineEnabled";
import { useCanManagePolicies } from "@portal/queries/policyPermissions";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
import "@portal/views/Pipelines.css";
/**
@@ -45,14 +44,14 @@ export function Pipelines() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [searchParams, setSearchParams] = useSearchParams();
- // Building and editing a pipeline both need a linked account, so both ask for one first (#7581).
- const { guard, error: connectError, retry: retryConnect } = useConnectGate();
const listState = usePipelines();
const { data: overview } = listState;
const { isLoading: listLoading } = useSectionFlags(listState);
const catalogueState = usePoliciesOverview();
+ // Shares the cache entry the catalogue already fills, so opening a row costs no fetch.
+ const runsState = usePolicyRuns();
const { data: catalogueData } = catalogueState;
const { enabled: aiEngineEnabled, loading: aiEngineLoading } =
@@ -103,10 +102,9 @@ export function Pipelines() {
queryClient.invalidateQueries({ queryKey: qk.policyRuns() });
}, [queryClient]);
- const openCreate = guard(() => navigate(`${listPath}/new`));
- const connectSource = guard(() =>
- navigate(`${toPortalPath(VIEW_PATHS.sources)}/new`),
- );
+ const openCreate = () => navigate(`${listPath}/new`);
+ const connectSource = () =>
+ navigate(`${toPortalPath(VIEW_PATHS.sources)}/new`);
// Open a suggested template in the simple wizard (a fresh policy). AI-gated templates stay closed
// until the engine is confirmed on, so a click during the app-config load can't open a disabled one.
@@ -122,17 +120,17 @@ export function Pipelines() {
// A list row routes by representability: a policy that still fits its template opens the simple
// detail panel (edit/pause/delete there); anything else opens the full builder. The full record is
// fetched on click so parseSimplePolicy - the single authority - decides on real data.
- const openListRow = guard(async (view: PipelineView) => {
+ const openListRow = async (view: PipelineView) => {
setPageError(null);
try {
const policy = await fetchPipeline(view.id);
- const entry = parseSimplePolicy(policy);
+ const entry = parseSimplePolicy(policy, runsState.data ?? []);
if (entry) setDetail(entry);
else navigate(`${listPath}/${view.id}`);
} catch (e) {
setPageError(errorMessage(e));
}
- });
+ };
// ?setup=<categoryId> deep link (onboarding): open the wizard for that suggested policy, then
// strip the param so back/reload doesn't re-open it.
@@ -263,19 +261,6 @@ export function Pipelines() {
</Button>
</header>
- {connectError && (
- <Banner
- tone="danger"
- title={t("portal.accountLink.gate.error")}
- description={connectError}
- action={
- <Button onClick={retryConnect}>
- {t("portal.accountLink.gate.retry")}
- </Button>
- }
- />
- )}
-
{pageError && <Banner tone="danger" description={pageError} />}
{permissionsError && (
diff --git a/frontend/editor/src/portal/views/Pipelines.gated.test.tsx b/frontend/editor/src/portal/views/Pipelines.unlinked.test.tsx
similarity index 67%
rename from frontend/editor/src/portal/views/Pipelines.gated.test.tsx
rename to frontend/editor/src/portal/views/Pipelines.unlinked.test.tsx
index bc12e73969..63225bbef5 100644
--- a/frontend/editor/src/portal/views/Pipelines.gated.test.tsx
+++ b/frontend/editor/src/portal/views/Pipelines.unlinked.test.tsx
@@ -4,8 +4,8 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import { PortalViewProviders } from "@portal/test/TestQueryProvider";
/**
- * The page must look exactly as it always does: the ask is a dialog on the attempt, not a lock
- * screen in place of the feature. The route half is what a later link cannot walk around.
+ * An unlinked instance still runs pipelines on its own grant, so nothing asks for an account up
+ * front. The wall is the server's 402, not a locked button.
*/
const { connect } = vi.hoisted(() => ({ connect: vi.fn() }));
@@ -15,6 +15,8 @@ vi.mock("@portal/hooks/useConnectGate", () => ({
loading: false,
available: true,
connect,
+ // Faithful to the real hook while gated, so re-guarding any of these actions fails the test
+ // rather than passing through it.
guard:
<A extends unknown[]>(_action: (...args: A) => void) =>
() =>
@@ -22,8 +24,8 @@ vi.mock("@portal/hooks/useConnectGate", () => ({
}),
}));
-// Deterministic i18n: keys returned verbatim. initReactI18next/Trans are exported too because the
-// unified page pulls in modules (the policy wizard/catalogue) that reference them at import time.
+// Keys verbatim. initReactI18next/Trans are exported because modules this page imports
+// reference them at import time.
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
@@ -42,7 +44,6 @@ vi.mock("@portal/api/pipelines", () => ({
}));
import { Pipelines } from "@portal/views/Pipelines";
-import { ConnectGuardedRoute } from "@portal/components/account-link/ConnectGuardedRoute";
const PIPELINE = {
id: "plc-1",
@@ -62,24 +63,19 @@ function renderAt(initial: string) {
<MemoryRouter initialEntries={[initial]}>
<Routes>
<Route path="/processor/pipelines" element={<Pipelines />} />
- <Route
- path="/processor/pipelines/new"
- element={
- <ConnectGuardedRoute fallback="/processor/pipelines">
- <div>builder</div>
- </ConnectGuardedRoute>
- }
- />
+ <Route path="/processor/pipelines/new" element={<div>builder</div>} />
+ <Route path="/processor/pipelines/:id" element={<div>builder</div>} />
</Routes>
</MemoryRouter>
</PortalViewProviders>,
);
}
-describe("Pipelines when the account is not connected", () => {
+describe("Pipelines on an instance with no Stirling account", () => {
beforeEach(() => {
connect.mockReset();
fetchPipelines.mockReset();
+ fetchPipeline.mockReset();
});
it("leaves the empty state exactly as it is", async () => {
@@ -96,31 +92,31 @@ describe("Pipelines when the account is not connected", () => {
expect(await screen.findByText("Redact claims")).toBeInTheDocument();
});
- it("asks to connect instead of opening the builder", async () => {
+ it("opens the builder rather than asking for an account", async () => {
fetchPipelines.mockResolvedValue({ kpis: [], pipelines: [] });
renderAt("/processor/pipelines");
await screen.findByText("portal.pipelines.empty.title");
fireEvent.click(
screen.getByText("portal.pipelines.actions.newCustomPipeline"),
);
- expect(connect).toHaveBeenCalled();
- expect(screen.queryByText("builder")).toBeNull();
+ expect(await screen.findByText("builder")).toBeInTheDocument();
+ expect(connect).not.toHaveBeenCalled();
});
- it("asks to connect instead of opening an existing pipeline", async () => {
+ it("opens an existing pipeline rather than asking for an account", async () => {
fetchPipelines.mockResolvedValue({ kpis: [], pipelines: [PIPELINE] });
+ // Not representable as a simple policy, so the row routes to the full builder.
+ fetchPipeline.mockResolvedValue({ ...PIPELINE, steps: PIPELINE.steps });
renderAt("/processor/pipelines");
fireEvent.click(await screen.findByText("Redact claims"));
- expect(connect).toHaveBeenCalled();
+ expect(await screen.findByText("builder")).toBeInTheDocument();
+ expect(connect).not.toHaveBeenCalled();
});
- it("turns away a direct arrival at the builder, however it was reached", async () => {
+ it("lets a direct arrival at the builder through", async () => {
fetchPipelines.mockResolvedValue({ kpis: [], pipelines: [] });
renderAt("/processor/pipelines/new");
- expect(
- await screen.findByText("portal.pipelines.empty.title"),
- ).toBeInTheDocument();
- expect(screen.queryByText("builder")).toBeNull();
- expect(connect).toHaveBeenCalled();
+ expect(await screen.findByText("builder")).toBeInTheDocument();
+ expect(connect).not.toHaveBeenCalled();
});
});
diff --git a/frontend/editor/src/portal/views/Sources.test.tsx b/frontend/editor/src/portal/views/Sources.test.tsx
index abd5d22882..be161188fd 100644
--- a/frontend/editor/src/portal/views/Sources.test.tsx
+++ b/frontend/editor/src/portal/views/Sources.test.tsx
@@ -22,16 +22,6 @@ const Providers = ({ children }: { children: ReactNode }) => (
const render = (ui: Parameters<typeof baseRender>[0]) =>
baseRender(ui, { wrapper: Providers });
-vi.mock("@portal/hooks/useConnectGate", () => ({
- useConnectGate: () => ({
- gated: false,
- loading: false,
- available: false,
- connect: vi.fn(),
- guard: (fn: unknown) => fn,
- }),
-}));
-
// Deterministic i18n: keys returned verbatim.
vi.mock("react-i18next", () => ({
useTranslation: () => ({
diff --git a/frontend/editor/src/portal/views/Sources.tsx b/frontend/editor/src/portal/views/Sources.tsx
index d185ee9bea..13e326bb16 100644
--- a/frontend/editor/src/portal/views/Sources.tsx
+++ b/frontend/editor/src/portal/views/Sources.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Navigate, useSearchParams } from "react-router-dom";
import AddRoundedIcon from "@mui/icons-material/AddRounded";
@@ -9,13 +9,11 @@ import { type SourceView } from "@portal/api/sources";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
import { SourcesTable } from "@portal/components/sources/SourcesTable";
import { SourceModal } from "@portal/components/sources/SourceModal";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
import "@portal/views/Sources.css";
export function Sources() {
const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
- const { guard, gated, connect } = useConnectGate();
const state = useSources();
const { data } = state;
@@ -28,28 +26,19 @@ export function Sources() {
sourceId: string | null;
}>({ open: false, sourceId: null });
- // Ref so the effect does not loop: it writes the param back, which would re-run it.
- const connectRef = useRef(connect);
- connectRef.current = connect;
-
- // Sets the modal directly, so it needs the gate in its own right: guarding openCreate would
- // leave ?new=1 as a way past it.
useEffect(() => {
if (searchParams.get("new") !== "1") return;
- if (gated) connectRef.current();
- else setModal({ open: true, sourceId: null });
+ setModal({ open: true, sourceId: null });
const next = new URLSearchParams(searchParams);
next.delete("new");
setSearchParams(next, { replace: true });
- }, [searchParams, setSearchParams, gated]);
+ }, [searchParams, setSearchParams]);
const sources = data?.sources ?? [];
- // Connecting a source and editing one both need a linked account.
- const openCreate = guard(() => setModal({ open: true, sourceId: null }));
- const openSource = guard((source: SourceView) =>
- setModal({ open: true, sourceId: source.id }),
- );
+ const openCreate = () => setModal({ open: true, sourceId: null });
+ const openSource = (source: SourceView) =>
+ setModal({ open: true, sourceId: source.id });
// The Connections tab moved to its own Integrations view.
if (searchParams.get("tab") === "connections") {
diff --git a/frontend/editor/src/portal/views/Sources.gated.test.tsx b/frontend/editor/src/portal/views/Sources.unlinked.test.tsx
similarity index 69%
rename from frontend/editor/src/portal/views/Sources.gated.test.tsx
rename to frontend/editor/src/portal/views/Sources.unlinked.test.tsx
index 944ab8c37c..15900dd0fd 100644
--- a/frontend/editor/src/portal/views/Sources.gated.test.tsx
+++ b/frontend/editor/src/portal/views/Sources.unlinked.test.tsx
@@ -4,27 +4,24 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import { PortalViewProviders } from "@portal/test/TestQueryProvider";
/**
- * The deep link into the create flow, which the gate has to cover in its own right.
- *
- * `?new=1` opens the modal from an effect rather than through the click handler, so guarding
- * openCreate does nothing for it. Both the Documents review queue and the pipelines empty state
- * arrive here that way, so each is a way past the gate unless the deep link is guarded too.
+ * Connecting a source needs no Stirling account: the source is stored on this instance, and the
+ * processing it feeds runs against the instance's own monthly grant. So neither the button nor the
+ * `?new=1` deep link (how the Documents queue and the pipelines empty state arrive) asks for one.
*/
const { connect } = vi.hoisted(() => ({ connect: vi.fn() }));
-const gate = { gated: true };
vi.mock("@portal/hooks/useConnectGate", () => ({
useConnectGate: () => ({
- gated: gate.gated,
+ gated: true,
loading: false,
available: true,
connect,
+ // Faithful to the real hook while gated, so re-guarding any of these actions fails the test
+ // rather than passing through it.
guard:
- <A extends unknown[]>(action: (...args: A) => void) =>
- (...args: A) => {
- if (gate.gated) connect();
- else action(...args);
- },
+ <A extends unknown[]>(_action: (...args: A) => void) =>
+ () =>
+ connect(),
}),
}));
@@ -76,10 +73,9 @@ const renderAt = (initial: string) =>
</PortalViewProviders>,
);
-describe("Sources deep link when the account is not connected", () => {
+describe("Sources on an instance with no Stirling account", () => {
beforeEach(() => {
connect.mockReset();
- gate.gated = true;
fetchSources.mockReset();
fetchSources.mockResolvedValue({ kpis: [], sources: [EDITOR_ROW] });
});
@@ -88,11 +84,11 @@ describe("Sources deep link when the account is not connected", () => {
const LIST = "portal.sources.table.source";
const MODAL = "portal.sources.builder.createTitle";
- it("asks to connect instead of opening the create modal", async () => {
+ it("honours the create deep link rather than asking for an account", async () => {
renderAt("/processor/sources?new=1");
expect(await screen.findByText(LIST)).toBeInTheDocument();
- expect(connect).toHaveBeenCalled();
- expect(screen.queryByText(MODAL)).toBeNull();
+ expect(await screen.findByText(MODAL)).toBeInTheDocument();
+ expect(connect).not.toHaveBeenCalled();
});
it("leaves the page looking exactly as it always does", async () => {
@@ -100,12 +96,4 @@ describe("Sources deep link when the account is not connected", () => {
expect(await screen.findByText(LIST)).toBeInTheDocument();
expect(connect).not.toHaveBeenCalled();
});
-
- it("still honours the deep link once connected", async () => {
- gate.gated = false;
- renderAt("/processor/sources?new=1");
- expect(await screen.findByText(LIST)).toBeInTheDocument();
- expect(connect).not.toHaveBeenCalled();
- expect(await screen.findByText(MODAL)).toBeInTheDocument();
- });
});
diff --git a/frontend/editor/src/portal/views/Users.caching.test.tsx b/frontend/editor/src/portal/views/Users.caching.test.tsx
index 1a9e3e28c6..a619d883b7 100644
--- a/frontend/editor/src/portal/views/Users.caching.test.tsx
+++ b/frontend/editor/src/portal/views/Users.caching.test.tsx
@@ -29,16 +29,6 @@ import { qk } from "@portal/queries/keys";
* one /team/my resolve. Same SaaS mocks as Users.saas.test.tsx.
*/
-vi.mock("@portal/hooks/useConnectGate", () => ({
- useConnectGate: () => ({
- gated: false,
- loading: false,
- available: false,
- connect: vi.fn(),
- guard: (fn: unknown) => fn,
- }),
-}));
-
vi.mock("@app/auth", () => ({
getStoredToken: () => null,
clearStoredToken: vi.fn(),
diff --git a/frontend/editor/src/portal/views/Users.saas.test.tsx b/frontend/editor/src/portal/views/Users.saas.test.tsx
index 1ea72e5a10..5313857c2c 100644
--- a/frontend/editor/src/portal/views/Users.saas.test.tsx
+++ b/frontend/editor/src/portal/views/Users.saas.test.tsx
@@ -32,16 +32,6 @@ import {
*/
// Keep apiClient.local's transport hermetic (no real token / Supabase at import).
-vi.mock("@portal/hooks/useConnectGate", () => ({
- useConnectGate: () => ({
- gated: false,
- loading: false,
- available: false,
- connect: vi.fn(),
- guard: (fn: unknown) => fn,
- }),
-}));
-
vi.mock("@app/auth", () => ({
getStoredToken: () => null,
clearStoredToken: vi.fn(),
diff --git a/frontend/editor/src/portal/views/Users.tsx b/frontend/editor/src/portal/views/Users.tsx
index 95b51091f0..3795444c97 100644
--- a/frontend/editor/src/portal/views/Users.tsx
+++ b/frontend/editor/src/portal/views/Users.tsx
@@ -21,7 +21,6 @@ import {
import { deleteTeam as apiDeleteTeam } from "@portal/api/teams";
import { errorMessage } from "@portal/api/http";
import { usersCapabilities as caps } from "@app/portal/usersCapabilities";
-import { useConnectGate } from "@portal/hooks/useConnectGate";
import { UsersDirectory } from "@portal/components/users/UsersDirectory";
import { PendingInvitations } from "@portal/components/users/PendingInvitations";
import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";
@@ -47,7 +46,6 @@ interface Confirm {
*/
export function Users() {
const { t } = useTranslation();
- const { guard, gated, connect } = useConnectGate();
const { usersState, grantsState, teamsState, authState, refresh } =
useUsersData();
@@ -65,19 +63,13 @@ export function Users() {
const [searchParams, setSearchParams] = useSearchParams();
- // Ref so the effect does not loop: it writes the param back, which would re-run it.
- const connectRef = useRef(connect);
- connectRef.current = connect;
-
- // Sets the modal directly, so it needs the gate in its own right.
useEffect(() => {
if (searchParams.get("invite") === null) return;
- if (gated) connectRef.current();
- else setInviteOpen(true);
+ setInviteOpen(true);
const next = new URLSearchParams(searchParams);
next.delete("invite");
setSearchParams(next, { replace: true });
- }, [searchParams, setSearchParams, gated]);
+ }, [searchParams, setSearchParams]);
// Scroll to and flash the row for ?member=<id> (deep link from the super
// search), once the roster has rendered; then strip the param. Scoped to the
@@ -203,12 +195,13 @@ export function Users() {
if (!grant) return;
run(() => revokeGrant(grant.id));
}
- // Teams need a linked account, so inviting or creating one asks for the connection first.
- const openInvite = guard((teamId: number | null) => {
+ function openInvite(teamId: number | null) {
setInviteTeamId(teamId);
setInviteOpen(true);
- });
- const openNewTeam = guard(() => setNewTeamOpen(true));
+ }
+ function openNewTeam() {
+ setNewTeamOpen(true);
+ }
// Kebab actions
function toggleEnabled(member: Member) {
diff --git a/frontend/editor/src/portal/views/Users.gated.test.tsx b/frontend/editor/src/portal/views/Users.unlinked.test.tsx
similarity index 67%
rename from frontend/editor/src/portal/views/Users.gated.test.tsx
rename to frontend/editor/src/portal/views/Users.unlinked.test.tsx
index b5286964fc..e270211471 100644
--- a/frontend/editor/src/portal/views/Users.gated.test.tsx
+++ b/frontend/editor/src/portal/views/Users.unlinked.test.tsx
@@ -4,24 +4,23 @@ import { MemoryRouter, Route, Routes } from "react-router-dom";
import { PortalViewProviders } from "@portal/test/TestQueryProvider";
/**
- * `?invite` opens the modal from an effect, so guarding openInvite did nothing for it. Same hole as
- * Sources' `?new=1`, and it survived that fix.
+ * An unlinked instance has its own user limit, so inviting is a free-tier feature and nothing here
+ * asks for an account. Running out of seats is the invite endpoint's answer, not a pre-emption.
*/
const { connect } = vi.hoisted(() => ({ connect: vi.fn() }));
-const gate = { gated: true };
vi.mock("@portal/hooks/useConnectGate", () => ({
useConnectGate: () => ({
- gated: gate.gated,
+ gated: true,
loading: false,
available: true,
connect,
+ // Faithful to the real hook while gated, so re-guarding any of these actions fails the test
+ // rather than passing through it.
guard:
- <A extends unknown[]>(action: (...args: A) => void) =>
- (...args: A) => {
- if (gate.gated) connect();
- else action(...args);
- },
+ <A extends unknown[]>(_action: (...args: A) => void) =>
+ () =>
+ connect(),
}),
}));
@@ -45,9 +44,9 @@ vi.mock("@app/auth/supabase/supabaseClient", () => ({
}));
vi.mock("@portal/auth/saasSupabase", () => ({ ensureSaasSupabase: vi.fn() }));
-vi.mock("@portal/hooks/useUsersData", () => ({
+vi.mock("@portal/views/usersData", () => ({
useUsersData: () => ({
- usersState: { data: [], loading: false, error: null },
+ usersState: { data: null, loading: false, error: null },
grantsState: { data: [], loading: false, error: null },
teamsState: { data: [], loading: false, error: null },
authState: { data: null, loading: false, error: null },
@@ -70,27 +69,17 @@ const renderAt = (initial: string) =>
</PortalViewProviders>,
);
-describe("Users deep link when the account is not connected", () => {
- beforeEach(() => {
- connect.mockReset();
- gate.gated = true;
- });
+describe("Users on an instance with no Stirling account", () => {
+ beforeEach(() => connect.mockReset());
- it("asks to connect instead of opening the invite modal", () => {
+ it("honours the invite deep link rather than asking for an account", () => {
renderAt("/processor/users?invite");
- expect(connect).toHaveBeenCalled();
- expect(screen.queryByText(INVITE_MODAL)).toBeNull();
+ expect(screen.getByText(INVITE_MODAL)).toBeInTheDocument();
+ expect(connect).not.toHaveBeenCalled();
});
it("leaves the page alone when there is no deep link", () => {
renderAt("/processor/users");
expect(connect).not.toHaveBeenCalled();
});
-
- it("still honours the deep link once connected", () => {
- gate.gated = false;
- renderAt("/processor/users?invite");
- expect(connect).not.toHaveBeenCalled();
- expect(screen.getByText(INVITE_MODAL)).toBeInTheDocument();
- });
});