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(app): don't stop recording / wall an entitled user on a transient token loss (#4271)

Louis Beaumont46220e97327e
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 138156a9b..4369d5dd3 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
spawnScreenpipe: vi.fn().mockResolvedValue(undefined),
openLoginWindow: vi.fn().mockResolvedValue(undefined),
setCloudToken: vi.fn().mockResolvedValue(undefined),
+ getCloudToken: vi.fn().mockResolvedValue(null),
loadUser: vi.fn().mockResolvedValue(undefined),
updateSettings: vi.fn().mockResolvedValue(undefined),
state: { isSettingsLoaded: true, user: null as any },
@@ -41,6 +42,7 @@ vi.mock("@/lib/utils/tauri", () => ({
spawnScreenpipe: mocks.spawnScreenpipe,
openLoginWindow: mocks.openLoginWindow,
setCloudToken: mocks.setCloudToken,
+ getCloudToken: mocks.getCloudToken,
},
}));
@@ -223,6 +225,103 @@ describe("AppEntitlementGate", () => {
await waitFor(() => expect(mocks.loadUser).toHaveBeenCalledWith("tok", true));
});
+ it("keeps recording for an entitled account whose token failed to hydrate (corrupt secret store)", async () => {
+ // store.bin still shows a paid account (id + app_entitled survive), but the
+ // token lives in the secret store and didn't hydrate — the exact mid-meeting
+ // lockout. We must fail OPEN: render the app, never stop the recorder.
+ mocks.state.user = baseUser({
+ id: "u1",
+ token: undefined,
+ app_entitled: true,
+ subscription_plan: "pro",
+ entitlement: {
+ active: true,
+ plan: "pro",
+ source: "subscription",
+ checked_at: daysAgo(5), // stale → not entitled by the normal path
+ features: { app: true },
+ },
+ });
+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();
+ expect(screen.queryByText(/sign in required/i)).not.toBeInTheDocument();
+ // Give the stop effect a chance to (wrongly) fire, then assert it didn't.
+ await new Promise((r) => setTimeout(r, 0));
+ expect(mocks.stopScreenpipe).not.toHaveBeenCalled();
+ // It actively tries to re-read the token so it self-heals without a restart.
+ await waitFor(() => expect(mocks.getCloudToken).toHaveBeenCalled());
+ });
+
+ it("stays open when access flips mid-session and never stops the recorder", async () => {
+ mocks.state.user = baseUser({
+ id: "u1",
+ app_entitled: true,
+ subscription_plan: "pro",
+ entitlement: {
+ active: true,
+ plan: "pro",
+ source: "subscription",
+ checked_at: minsAgo(5),
+ features: { app: true },
+ },
+ });
+ const { rerender } = render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();
+
+ // Token + entitlement vanish (secret store blip), but the account object
+ // persists — this is a transient failure, not a sign-out.
+ mocks.state.user = baseUser({
+ id: "u1",
+ token: undefined,
+ app_entitled: false,
+ subscription_plan: "none",
+ entitlement: null,
+ });
+ rerender(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();
+ await new Promise((r) => setTimeout(r, 0));
+ expect(mocks.stopScreenpipe).not.toHaveBeenCalled();
+ });
+
+ it("still walls and stops on a real sign-out, even after a prior entitled session", async () => {
+ mocks.state.user = baseUser({
+ id: "u1",
+ app_entitled: true,
+ subscription_plan: "pro",
+ entitlement: {
+ active: true,
+ plan: "pro",
+ source: "subscription",
+ checked_at: minsAgo(5),
+ features: { app: true },
+ },
+ });
+ const { rerender } = render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();
+
+ // A real sign-out nulls the whole user — session-sticky must NOT leak access.
+ mocks.state.user = null;
+ rerender(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ expect(screen.getByText(/sign in required/i)).toBeInTheDocument();
+ expect(screen.queryByTestId("protected-app")).not.toBeInTheDocument();
+ await waitFor(() => expect(mocks.stopScreenpipe).toHaveBeenCalled());
+ });
+
+ it("reports the gate once across re-renders of the same gated state", () => {
+ mocks.state.user = baseUser(); // signed in, unentitled → gated
+ const { rerender } = render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ rerender(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+ rerender(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ const gateShown = mocks.capture.mock.calls.filter(
+ (c) => c[0] === "app_entitlement_gate_shown",
+ );
+ expect(gateShown).toHaveLength(1);
+ });
+
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 7d117fda7..40de07e8d 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
@@ -12,8 +12,10 @@ import { Button } from "@/components/ui/button";
import {
AppUser,
hasAppEntitlement,
+ hasPersistedEntitlementEvidence,
isDevBillingBypassEnabled,
isDevLoginEnabled,
+ isTokenHydrationPending,
needsAppEntitlementRefresh,
normalizePlanLabel,
PRICING_URL,
@@ -86,10 +88,39 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
const autoVerifiedRef = useRef(false);
const prevEntitledRef = useRef<boolean | null>(null);
const resumingRef = useRef(false);
+ const everEntitledRef = useRef(false);
+ const gateReportedRef = useRef(false);
+ const rehydratingRef = useRef(false);
const user = settings.user as AppUser | null | undefined;
const devBypass = isDevBillingBypassEnabled();
const isEntitled = hasAppEntitlement(user);
const needsRefresh = needsAppEntitlementRefresh(user);
+
+ // 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).
+ if (isEntitled) everEntitledRef.current = true;
+
+ // Fail the recording gate OPEN on a *transient* loss of access. The session
+ // token lives in an encrypted secret store (the db.sqlite `secrets` table);
+ // when that table is briefly corrupt or locked, getCloudToken() returns
+ // nothing and `user.token` goes undefined — even though store.bin still shows
+ // a paid account. Treating that as "no account / no plan" used to STOP the
+ // recorder mid-meeting and throw up the sign-in wall (PostHog: ~10 signed-in
+ // users/day, the gate re-firing hundreds of times as the token flapped).
+ // Instead, keep recording and the app usable on the last-known-good
+ // entitlement until the token re-hydrates. This only ever relaxes the gate
+ // for an account we have evidence WAS entitled, and never when `user` is null
+ // (a real sign-out), so it opens no free-access hole. A genuine downgrade
+ // still takes effect on the next launch.
+ const tokenPending = isTokenHydrationPending(user);
+ const failOpenForTransientAccessLoss =
+ !devBypass &&
+ !isEntitled &&
+ !!user &&
+ (everEntitledRef.current ||
+ (tokenPending && hasPersistedEntitlementEvidence(user)));
+
const enterpriseAccountPolicyLoaded = Boolean(enterprisePolicy.orgName);
const enterpriseRequiresLogin =
isEnterprise &&
@@ -97,7 +128,8 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
!needsLicenseKey &&
!isSectionHidden("account");
const shouldGateForEnterpriseLogin = enterpriseRequiresLogin && !user?.token;
- const shouldGateForEntitlement = !devBypass && !isEntitled;
+ const shouldGateForEntitlement =
+ !devBypass && !isEntitled && !failOpenForTransientAccessLoss;
const shouldGate = shouldGateForEnterpriseLogin || shouldGateForEntitlement;
const email = user?.email || "this account";
const planLabel = useMemo(
@@ -105,8 +137,17 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
[user?.subscription_plan],
);
+ // Report the gate at most once per continuous gated period. A corrupt secret
+ // store makes the token flap (hydrate → fail → strip → retry), which used to
+ // re-fire this on every settings broadcast — 33k events from 36 users in 30d.
+ // Reset the latch only when the gate clears so a genuine re-gate still counts.
useEffect(() => {
- if (!isSettingsLoaded || !shouldGate) return;
+ if (!isSettingsLoaded || !shouldGate) {
+ gateReportedRef.current = false;
+ return;
+ }
+ if (gateReportedRef.current) return;
+ gateReportedRef.current = true;
posthog.capture("app_entitlement_gate_shown", {
logged_in: Boolean(user?.token),
reason: shouldGateForEnterpriseLogin ? "enterprise_login_required" : "app_entitlement",
@@ -115,6 +156,35 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
});
}, [isSettingsLoaded, shouldGate, shouldGateForEnterpriseLogin, user?.app_entitled, user?.subscription_plan, user?.token]);
+ // When failing open on a pending token, keep trying to re-read it from the
+ // secret store. Once the store heals (the periodic WAL checkpoint clears the
+ // `-shm` desync, or the user runs `screenpipe db recover`), the token returns
+ // and we fully restore entitlement + push it to the sidecar via loadUser — no
+ // app restart needed. Cheap local read, guarded against overlap, and the
+ // interval clears itself the moment the token comes back.
+ useEffect(() => {
+ if (devBypass || !failOpenForTransientAccessLoss || !tokenPending) return;
+ let cancelled = false;
+ const attempt = async () => {
+ if (rehydratingRef.current) return;
+ rehydratingRef.current = true;
+ try {
+ const token = await commands.getCloudToken();
+ if (!cancelled && token) await loadUser(token, true);
+ } catch {
+ // secret store still unreadable — try again on the next tick
+ } finally {
+ rehydratingRef.current = false;
+ }
+ };
+ void attempt();
+ const id = setInterval(() => void attempt(), 15_000);
+ return () => {
+ cancelled = true;
+ clearInterval(id);
+ };
+ }, [devBypass, failOpenForTransientAccessLoss, tokenPending, loadUser]);
+
useEffect(() => {
if (!isSettingsLoaded || !shouldGate) {
stoppedForGateRef.current = false;
diff --git a/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts b/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts
index 95b47e411..172a71208 100644
--- a/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts
+++ b/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts
@@ -6,7 +6,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
hasAppEntitlement,
hasCloudEntitlement,
+ hasPersistedEntitlementEvidence,
isSignedInCloudSubscriber,
+ isTokenHydrationPending,
needsAppEntitlementRefresh,
normalizeAppUser,
} from "@/lib/app-entitlement";
@@ -180,3 +182,42 @@ describe("isSignedInCloudSubscriber", () => {
expect(isSignedInCloudSubscriber(undefined)).toBe(false);
});
});
+
+describe("isTokenHydrationPending", () => {
+ // A real sign-out nulls the whole user; a hydration failure leaves the account
+ // id behind while only the secret-store-backed token is missing.
+ it("is true for a signed-in account whose token failed to hydrate", () => {
+ expect(isTokenHydrationPending(user({ id: "u1", token: null }))).toBe(true);
+ expect(isTokenHydrationPending(user({ id: "u1", token: undefined }))).toBe(true);
+ });
+
+ it("is false when the token is present", () => {
+ expect(isTokenHydrationPending(user({ id: "u1", token: "tok" }))).toBe(false);
+ });
+
+ it("is false without an account id (never signed in) and for a null user", () => {
+ expect(isTokenHydrationPending(user({ id: null, token: null }))).toBe(false);
+ expect(isTokenHydrationPending(null)).toBe(false);
+ expect(isTokenHydrationPending(undefined)).toBe(false);
+ });
+});
+
+describe("hasPersistedEntitlementEvidence", () => {
+ it("trusts store.bin signals that survive a token-hydration failure", () => {
+ expect(hasPersistedEntitlementEvidence(user({ cloud_subscribed: true }))).toBe(true);
+ expect(hasPersistedEntitlementEvidence(user({ app_entitled: true }))).toBe(true);
+ expect(
+ hasPersistedEntitlementEvidence(user({ entitlement: { features: { app: true } } })),
+ ).toBe(true);
+ expect(hasPersistedEntitlementEvidence(user({ entitlement: { active: true } }))).toBe(true);
+ });
+
+ it("is false for an account with no entitlement evidence", () => {
+ expect(
+ hasPersistedEntitlementEvidence(
+ user({ cloud_subscribed: false, app_entitled: false, entitlement: null }),
+ ),
+ ).toBe(false);
+ expect(hasPersistedEntitlementEvidence(null)).toBe(false);
+ });
+});
diff --git a/apps/screenpipe-app-tauri/lib/app-entitlement.ts b/apps/screenpipe-app-tauri/lib/app-entitlement.ts
index be3df3be4..2b3b5c36b 100644
--- a/apps/screenpipe-app-tauri/lib/app-entitlement.ts
+++ b/apps/screenpipe-app-tauri/lib/app-entitlement.ts
@@ -188,6 +188,29 @@ export function isSignedInCloudSubscriber(user: AppUser | null | undefined): boo
return !!user?.token && user?.cloud_subscribed === true;
}
+// A signed-in account whose token is momentarily missing is in a transient
+// secret-store hydration failure (see `hydrateCloudToken` / #3943), NOT a real
+// sign-out. A real sign-out nulls the whole `user`; here the account `id` (and
+// the rest of the persisted profile) survives in store.bin while only the token
+// — which lives in the encrypted secret store (the db.sqlite `secrets` table) —
+// failed to load. A corrupt or locked secrets table is the common cause. The
+// recording gate uses this to avoid treating a DB blip as "logged out".
+export function isTokenHydrationPending(user: AppUser | null | undefined): boolean {
+ return !!user && !!user.id && !user.token;
+}
+
+// store.bin keeps these entitlement signals even when the token doesn't hydrate,
+// so they're evidence the (now tokenless) account was a paying user — used to
+// fail the recording gate OPEN on a transient token loss instead of walling a
+// subscriber out mid-session.
+export function hasPersistedEntitlementEvidence(user: AppUser | null | undefined): boolean {
+ if (!user) return false;
+ if (user.cloud_subscribed === true) return true;
+ if (user.app_entitled === true) return true;
+ const entitlement = asEntitlement(user.entitlement);
+ return entitlement?.features?.app === true || entitlement?.active === true;
+}
+
export function needsAppEntitlementRefresh(user: AppUser | null | undefined) {
if (!user?.token || hasLegacyPaidAccess(user)) return false;