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

[codex] fix enterprise app gate for consumer subscribers (#4542)

Louis Beaumont9721f9f22cc5
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 2202850a9..b2037c8ab 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.test.tsx
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
openLoginWindow: vi.fn().mockResolvedValue(undefined),
setCloudToken: vi.fn().mockResolvedValue(undefined),
getCloudToken: vi.fn().mockResolvedValue(null),
+ piUpdateConfig: vi.fn().mockResolvedValue(undefined),
platform: vi.fn(() => "windows"),
arch: vi.fn(() => "x86_64"),
loadUser: vi.fn().mockResolvedValue(undefined),
@@ -45,6 +46,7 @@ vi.mock("@/lib/utils/tauri", () => ({
openLoginWindow: mocks.openLoginWindow,
setCloudToken: mocks.setCloudToken,
getCloudToken: mocks.getCloudToken,
+ piUpdateConfig: mocks.piUpdateConfig,
},
}));
@@ -458,6 +460,61 @@ describe("AppEntitlementGate", () => {
expect(downloadUrl).toContain("platform=windows");
});
+ it("clears app auth and opens a fresh browser session when switching accounts", async () => {
+ mocks.state.user = baseUser({
+ app_entitled: true,
+ cloud_subscribed: true,
+ subscription_plan: "pro",
+ enterprise_account: {
+ org_name: "Bungalow",
+ role: "member",
+ requires_enterprise_app: true,
+ },
+ entitlement: {
+ active: true,
+ plan: "pro",
+ source: "enterprise",
+ checked_at: minsAgo(1),
+ features: { app: true, cloud: true },
+ },
+ });
+
+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ fireEvent.click(screen.getByRole("button", { name: /use different account/i }));
+
+ await waitFor(() => expect(mocks.updateSettings).toHaveBeenCalledWith({ user: null }));
+ expect(mocks.setCloudToken).toHaveBeenCalledWith(null);
+ expect(mocks.piUpdateConfig).toHaveBeenCalledWith(null, null);
+ expect(mocks.openLoginWindow).toHaveBeenCalledWith(true);
+ });
+
+ it("does not route enterprise members away when they also have a consumer app subscription", () => {
+ mocks.state.user = baseUser({
+ app_entitled: true,
+ cloud_subscribed: true,
+ subscription_plan: "pro",
+ enterprise_account: {
+ org_name: "Bungalow",
+ role: "member",
+ requires_enterprise_app: true,
+ },
+ entitlement: {
+ active: true,
+ plan: "pro",
+ source: "subscription",
+ checked_at: minsAgo(1),
+ features: { app: true, cloud: true },
+ },
+ });
+
+ render(<AppEntitlementGate>{protectedApp}</AppEntitlementGate>);
+
+ expect(screen.queryByText(/enterprise app required/i)).not.toBeInTheDocument();
+ expect(screen.getByTestId("protected-app")).toBeInTheDocument();
+ expect(mocks.stopScreenpipe).not.toHaveBeenCalled();
+ });
+
it("does not show the consumer-app warning inside the enterprise build", () => {
mocks.enterprise.isEnterprise = true;
mocks.state.user = baseUser({
diff --git a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
index a8f89ba5f..ff8f945bc 100644
--- a/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
+++ b/apps/screenpipe-app-tauri/components/app-entitlement-gate.tsx
@@ -16,6 +16,7 @@ import {
ENTERPRISE_DOWNLOAD_URL,
getEnterpriseAccount,
hasAppEntitlement,
+ hasConsumerAppSubscription,
hasPersistedEntitlementEvidence,
isDevBillingBypassEnabled,
isDevLoginEnabled,
@@ -120,6 +121,7 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
const user = settings.user as AppUser | null | undefined;
const devBypass = isDevBillingBypassEnabled();
const isEntitled = hasAppEntitlement(user);
+ const hasConsumerSubscription = hasConsumerAppSubscription(user);
const needsRefresh = needsAppEntitlementRefresh(user);
const enterpriseAccount = getEnterpriseAccount(user);
@@ -166,6 +168,7 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
!devBypass &&
!isEnterprise &&
Boolean(user?.token) &&
+ !hasConsumerSubscription &&
enterpriseAccount?.requires_enterprise_app === true;
const shouldGateForEntitlement =
!devBypass && !isEntitled && !failOpenForTransientAccessLoss;
@@ -280,8 +283,15 @@ export function AppEntitlementGate({ children }: { children: React.ReactNode })
await updateSettings({ user: null as any });
try {
await commands.setCloudToken(null);
- } catch {}
- commands.openLoginWindow();
+ } catch (e) {
+ console.warn("failed to clear cloud token before switching accounts:", e);
+ }
+ try {
+ await commands.piUpdateConfig(null, null);
+ } catch (e) {
+ console.warn("failed to clear pi config before switching accounts:", e);
+ }
+ commands.openLoginWindow(true);
}, [updateSettings]);
const downloadEnterpriseApp = useCallback(() => {
diff --git a/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts b/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts
index 4cf3248ca..bea3de96d 100644
--- a/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts
+++ b/apps/screenpipe-app-tauri/lib/app-entitlement.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
hasAppEntitlement,
hasCloudEntitlement,
+ hasConsumerAppSubscription,
hasPersistedEntitlementEvidence,
isSignedInCloudSubscriber,
isTokenHydrationPending,
@@ -87,6 +88,46 @@ describe("app entitlement", () => {
expect(hasAppEntitlement(user({ cloud_subscribed: true, entitlement: null }))).toBe(true);
});
+ it("separates consumer subscriptions from enterprise-only app grants", () => {
+ expect(
+ hasConsumerAppSubscription(
+ user({
+ cloud_subscribed: true,
+ app_entitled: true,
+ entitlement: {
+ active: true,
+ checked_at: "2026-06-05T11:00:00.000Z",
+ source: "subscription",
+ features: { app: true },
+ },
+ enterprise_account: {
+ org_name: "Bungalow",
+ requires_enterprise_app: true,
+ },
+ }),
+ ),
+ ).toBe(true);
+
+ expect(
+ hasConsumerAppSubscription(
+ user({
+ cloud_subscribed: true,
+ app_entitled: true,
+ entitlement: {
+ active: true,
+ checked_at: "2026-06-05T11:00:00.000Z",
+ source: "enterprise",
+ features: { app: true },
+ },
+ enterprise_account: {
+ org_name: "Bungalow",
+ requires_enterprise_app: true,
+ },
+ }),
+ ),
+ ).toBe(false);
+ });
+
it("does not unlock new cloud features from stale entitlement data", () => {
expect(
hasCloudEntitlement(
diff --git a/apps/screenpipe-app-tauri/lib/app-entitlement.ts b/apps/screenpipe-app-tauri/lib/app-entitlement.ts
index 3dff2ea30..c5e2095be 100644
--- a/apps/screenpipe-app-tauri/lib/app-entitlement.ts
+++ b/apps/screenpipe-app-tauri/lib/app-entitlement.ts
@@ -186,6 +186,26 @@ export function hasAppEntitlement(user: AppUser | null | undefined) {
return isEntitlementFresh(entitlement) && entitlement.active === true;
}
+export function hasConsumerAppSubscription(user: AppUser | null | undefined) {
+ if (!user) return false;
+
+ const entitlement = asEntitlement(user.entitlement);
+ const source = typeof entitlement?.source === "string"
+ ? entitlement.source.toLowerCase()
+ : null;
+
+ if (source === "enterprise") return false;
+ if (source === "subscription" || source === "manual" || source === "lifetime") {
+ return hasAppEntitlement(user);
+ }
+
+ // Legacy users may only have cloud_subscribed/app_entitled persisted locally.
+ // If the account also carries an enterprise-app requirement, that boolean may
+ // be the enterprise org grant, so do not treat it as a separate consumer sub.
+ const enterpriseAccount = getEnterpriseAccount(user);
+ return hasLegacyPaidAccess(user) && enterpriseAccount?.requires_enterprise_app !== true;
+}
+
export function hasCloudEntitlement(user: AppUser | null | undefined) {
return user?.cloud_subscribed === true || hasEntitlementFeature(user, "cloud");
}
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index a4a81661d..b06806865 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -1015,10 +1015,12 @@ async openGoogleCalendarAuthWindow(authUrl: string) : Promise<Result<null, strin
* Windows: system browser + registered deep-link scheme handles the redirect.
* macOS: ASWebAuthenticationSession (system-managed sheet, forwards callback).
* Linux: in-app WebView that intercepts the screenpipe:// redirect.
+ * Pass `freshSession` when switching accounts so the auth sheet/webview does
+ * not reuse the previous browser session.
*/
-async openLoginWindow() : Promise<Result<null, string>> {
+async openLoginWindow(freshSession?: boolean) : Promise<Result<null, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("open_login_window") };
+ return { status: "ok", data: await TAURI_INVOKE("open_login_window", { freshSession }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index 7aca22a7f..67eec9dec 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -1794,9 +1794,17 @@ fn is_login_callback_scheme(scheme: &str) -> bool {
/// Open the screenpipe.com login page.
/// macOS: ASWebAuthenticationSession (system-managed sheet, forwards callback).
/// Windows/Linux: in-app WebView that intercepts the screenpipe:// redirect.
+///
+/// `fresh_session` is used by "use different account": macOS asks
+/// ASWebAuthenticationSession for an ephemeral browser session instead of
+/// reusing Safari cookies, and Windows/Linux use a throwaway webview profile.
#[tauri::command]
#[specta::specta]
-pub async fn open_login_window(app_handle: tauri::AppHandle) -> Result<(), String> {
+pub async fn open_login_window(
+ app_handle: tauri::AppHandle,
+ fresh_session: Option<bool>,
+) -> Result<(), String> {
+ let fresh_session = fresh_session.unwrap_or(false);
#[cfg(target_os = "macos")]
{
// ASWebAuthenticationSession intercepts the redirect itself (no OS
@@ -1806,7 +1814,7 @@ pub async fn open_login_window(app_handle: tauri::AppHandle) -> Result<(), Strin
let callback_url = match crate::auth_session::start_session(
LOGIN_URL.to_string(),
"screenpipe".to_string(),
- false,
+ fresh_session,
)
.await
{
@@ -1830,32 +1838,49 @@ pub async fn open_login_window(app_handle: tauri::AppHandle) -> Result<(), Strin
{
use tauri::{WebviewUrl, WebviewWindowBuilder};
- let label = "login-browser";
+ let label = if fresh_session {
+ let id = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ format!("login-browser-fresh-{id}")
+ } else {
+ "login-browser".to_string()
+ };
- // If already open, just focus it
- if let Some(w) = app_handle.get_webview_window(label) {
+ if fresh_session {
+ if let Some(w) = app_handle.get_webview_window("login-browser") {
+ let _ = w.close();
+ }
+ } else if let Some(w) = app_handle.get_webview_window(&label) {
let _ = w.show();
let _ = w.set_focus();
return Ok(());
}
let app_for_nav = app_handle.clone();
+ let label_for_nav = label.clone();
let login_url = format!("{}?return_scheme={}", LOGIN_URL, deep_link_scheme());
let mut builder = WebviewWindowBuilder::new(
&app_handle,
- label,
+ label.clone(),
WebviewUrl::External(login_url.parse().unwrap()),
)
.title("sign in to screenpipe")
.inner_size(460.0, 700.0)
.focused(true);
+ if fresh_session {
+ let profile_dir = std::env::temp_dir().join(&label);
+ builder = builder.data_directory(profile_dir);
+ }
+
builder = builder.on_navigation(move |url| {
if is_login_callback_scheme(url.scheme()) {
info!("login window intercepted deep link callback");
let _ = app_for_nav.emit("deep-link-received", url.to_string());
- if let Some(w) = app_for_nav.get_webview_window("login-browser") {
+ if let Some(w) = app_for_nav.get_webview_window(&label_for_nav) {
let _ = w.close();
}
false // block navigation to custom scheme
@@ -1867,7 +1892,7 @@ pub async fn open_login_window(app_handle: tauri::AppHandle) -> Result<(), Strin
.build()
.map(crate::window::finalize_webview_window)
.map_err(|e| {
- log_webview_build_failure(label, &login_url, &e);
+ log_webview_build_failure(&label, &login_url, &e);
e.to_string()
})?;
diff --git a/crates/screenpipe-engine/src/routes/meetings.rs b/crates/screenpipe-engine/src/routes/meetings.rs
index 28c8824c9..90da4d511 100644
--- a/crates/screenpipe-engine/src/routes/meetings.rs
+++ b/crates/screenpipe-engine/src/routes/meetings.rs
@@ -101,10 +101,7 @@ where
{
type Rejection = (StatusCode, JsonResponse<Value>);
- async fn from_request(
- req: axum::extract::Request,
- state: &S,
- ) -> Result<Self, Self::Rejection> {
+ async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
let bytes = axum::body::Bytes::from_request(req, state)
.await
.map_err(|_| {