Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(entitlement-gate): re-verify access while gated instead of giving up after one check (#4297)

Louis Beaumont171fb7b454ef
diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
index 4369d5dd3..7d24282e0 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
@@ -322,6 +322,102 @@ describe("AppEntitlementGate", () => {
expect(gateShown).toHaveLength(1);
});
+ // Fake ONLY the timer functions (leave Date real so entitlement freshness
+ // checks keep working against the wall clock).
+ const fakeTimersNoDate = () =>
+ vi.useFakeTimers({
+ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"],
+ });
+
+ it("keeps re-verifying a still-unentitled member on a backoff instead of giving up after one check (#4161)", async () => {
+ fakeTimersNoDate();
+ try {
+ mocks.state.user = baseUser(); // signed in, not entitled → gated
+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ // First verify is immediate and uses the Stripe fallback (verify=true).
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.loadUser).toHaveBeenNthCalledWith(1, "tok", true);
+
+ // The old gate stopped here forever. It must keep checking so a backend
+ // grant that lands seconds later (eager/lazy enterprise upgrade, webhook)
+ // reaches the app on its own.
+ await vi.advanceTimersByTimeAsync(3_000);
+ await vi.advanceTimersByTimeAsync(6_000);
+ expect(mocks.loadUser.mock.calls.length).toBeGreaterThanOrEqual(3);
+ // Later ticks skip verify=true to spare the per-poll Stripe round-trip.
+ expect(mocks.loadUser).toHaveBeenNthCalledWith(2, "tok", false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("stops re-verifying the moment the member becomes entitled", async () => {
+ fakeTimersNoDate();
+ try {
+ mocks.state.user = baseUser();
+ const { rerender } = render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(3_000); // a couple of ticks
+
+ // Backend lifts the member to Pro (the eager/lazy upgrade lands).
+ mocks.state.user = baseUser({
+ app_entitled: true,
+ subscription_plan: "pro",
+ entitlement: {
+ active: true,
+ plan: "pro",
+ source: "subscription",
+ checked_at: minsAgo(1),
+ features: { app: true },
+ },
+ });
+ rerender(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ await vi.advanceTimersByTimeAsync(0);
+
+ const callsWhenEntitled = mocks.loadUser.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(120_000); // 2 min later
+ expect(mocks.loadUser.mock.calls.length).toBe(callsWhenEntitled); // poll stopped
+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("bounds the re-verify poll so a never-entitled session can't hammer the server", async () => {
+ fakeTimersNoDate();
+ try {
+ mocks.state.user = baseUser(); // never becomes entitled
+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ await vi.advanceTimersByTimeAsync(30 * 60_000); // 30 minutes
+ const total = mocks.loadUser.mock.calls.length;
+ expect(total).toBeLessThanOrEqual(12);
+ expect(total).toBeGreaterThanOrEqual(3); // but it did retry, not one-shot
+ await vi.advanceTimersByTimeAsync(30 * 60_000); // 30 more minutes
+ expect(mocks.loadUser.mock.calls.length).toBe(total); // stopped, no growth
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not background-verify when the gate is a required enterprise login (no token)", async () => {
+ fakeTimersNoDate();
+ try {
+ mocks.enterprise = {
+ isEnterprise: true,
+ hiddenSections: [],
+ needsLicenseKey: false,
+ orgName: "Acme",
+ };
+ mocks.state.user = null; // no token → enterprise-login gate, not entitlement
+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.loadUser).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("resumes recording when access transitions to entitled", async () => {
mocks.state.user = baseUser(); // unentitled first
const { rerender } = render(
diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
index 40de07e8d..b5073bd17 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
@@ -85,7 +85,6 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
const [devSubmitting, setDevSubmitting] = useState(false);
const [devError, setDevError] = useState<string | null>(null);
const stoppedForGateRef = useRef(false);
- const autoVerifiedRef = useRef(false);
const prevEntitledRef = useRef<boolean | null>(null);
const resumingRef = useRef(false);
const everEntitledRef = useRef(false);
@@ -96,6 +95,13 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
const isEntitled = hasAppEntitlement(user);
const needsRefresh = needsAppEntitlementRefresh(user);
+ // loadUser is re-created on every render (it is NOT memoized), so the
+ // background re-verify poll below can't depend on its identity without
+ // tearing itself down and restarting every render. Keep the latest in a ref
+ // and call through that instead.
+ const loadUserRef = useRef(loadUser);
+ loadUserRef.current = loadUser;
+
// Latch "was entitled at least once this session". Mutating a ref during
// render is safe here because the write is idempotent (only ever flips
// false→true).
@@ -261,15 +267,69 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
}
}, [devToken, loadUser]);
- // A signed-in user who is not yet entitled may have just paid, with the Stripe
- // webhook still in flight. Verify once against the server (Stripe fallback) so
- // they unlock without waiting for the next periodic poll.
+ // A signed-in user who is gated ONLY on entitlement (has a token, but the
+ // backend doesn't yet report an active plan) is often mid-provisioning:
+ // - an enterprise *member* whose null plan is being lifted to Pro — eagerly
+ // on invite, or by the lazy /api/user enterprise→pro upgrade, or after an
+ // admin re-invites — none of which is instant;
+ // - a user who just paid, with the Stripe webhook still in flight.
+ // The old behavior verified exactly ONCE and then left them stranded behind
+ // the wall until they manually hit "refresh access" or relaunched the app —
+ // which is the enterprise member sign-in loop (issue #4161): the gate bounces
+ // them before they ever re-check, so a backend grant that lands seconds later
+ // never reaches the app. Instead, keep re-verifying in the background with
+ // backoff while gated; the moment the backend entitles them the gate clears
+ // itself (and the resume-capture effect below restarts recording) with no
+ // user action. Bounded so we never hammer the server — after the window the
+ // manual button is still there.
useEffect(() => {
+ // Poll the exact stuck state only: settings loaded, not dev-bypassed,
+ // signed in, and gated *specifically* on a missing entitlement — not on a
+ // required enterprise login (no token), and not while failing open on a
+ // transient token loss (that path has its own re-hydration loop above).
if (!isSettingsLoaded || devBypass || isEntitled) return;
- if (!user?.token || autoVerifiedRef.current) return;
- autoVerifiedRef.current = true;
- void refreshUser();
- }, [devBypass, isEntitled, isSettingsLoaded, user?.token, refreshUser]);
+ if (!user?.token || !shouldGateForEntitlement) return;
+ const token = user.token;
+
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let attempt = 0;
+ const MAX_ATTEMPTS = 12; // ~7 min of backoff, then fall back to the button
+
+ const run = async () => {
+ if (cancelled) return;
+ attempt += 1;
+ try {
+ // First tick uses verify=true so a just-paid user unlocks via the
+ // Stripe fallback; later ticks omit it (cheaper) since the enterprise
+ // grant and webhook-updated cache resolve without hitting Stripe.
+ await loadUserRef.current(token, attempt === 1);
+ } catch {
+ // offline / transient 5xx — keep trying on the schedule
+ }
+ if (cancelled || attempt >= MAX_ATTEMPTS) return;
+ // backoff: 3, 6, 12, 24, 48, then 60s capped
+ const delay = Math.min(3_000 * 2 ** (attempt - 1), 60_000);
+ timer = setTimeout(() => void run(), delay);
+ };
+
+ posthog.capture("app_entitlement_autoverify_poll_started", {
+ plan: user?.subscription_plan ?? null,
+ app_entitled: user?.app_entitled ?? null,
+ });
+ // Fire the first verify immediately (preserving the old one-shot's instant
+ // check so a just-paid user unlocks fast), then `run` schedules the backoff.
+ void run();
+ return () => {
+ cancelled = true;
+ if (timer) clearTimeout(timer);
+ };
+ // Keyed on stable gating booleans + the token string only — NOT on loadUser
+ // (unstable) or the `user` object (new identity on every settings write),
+ // so a poll tick that writes settings doesn't restart the poll. When the
+ // grant lands, isEntitled flips → this effect tears down and stops.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isSettingsLoaded, devBypass, isEntitled, user?.token, shouldGateForEntitlement]);
// Resume capture when access transitions to entitled within a session (after
// sign-in, purchase, or a successful refresh). Native autostart only runs once
@@ -287,6 +347,12 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
const previouslyEntitled = prevEntitledRef.current;
prevEntitledRef.current = isEntitled;
if (previouslyEntitled !== false || !isEntitled) return;
+ // Access was restored in-session (auto-verify poll, manual refresh, sign-in,
+ // or purchase). Tracked so we can confirm gated members actually escape the
+ // wall on their own rather than churning at sign-in (issue #4161).
+ posthog.capture("app_entitlement_restored", {
+ plan: user?.subscription_plan ?? null,
+ });
// Single owner: only the primary window restarts the engine, so secondary
// webviews don't fire overlapping spawns that race each other.
if (!isPrimaryWindow()) return;