Skip to content

feat(desktop): implement session refetch subscription and update billing success URLs - #1525

Closed
Ipriyankrajai wants to merge 5 commits into
ParadevAI:mainfrom
Ipriyankrajai:pri/ss-5-update-side-bar-task-state
Closed

Ipriyankrajai wants to merge 5 commits into
ParadevAI:mainfrom
Ipriyankrajai:pri/ss-5-update-side-bar-task-state

Conversation

@Ipriyankrajai

@Ipriyankrajai Ipriyankrajai commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor
  • Added a new subscription for session refetch requests in the auth router to handle session updates after specific events, such as Stripe checkout.
  • Emitted a session refetch event upon successful billing deep link navigation.
  • Updated success URLs in billing components to use a protocol scheme constant for consistency and improved link handling.
  • Refactored the usePaywall hook to simplify user plan determination based on session data.

Summary by CodeRabbit

  • New Features
    • Added a session-refetch subscription so the app can refresh session data in response to external events.
  • Improvements
    • Billing success deep links now trigger an immediate session refresh, reflecting subscription and account updates without manual refresh.
    • Billing upgrade redirects use the app protocol scheme for more reliable in-app navigation.

…ser plan determination

Refactor the usePaywall hook to incorporate active subscription data using useLiveQuery and useCollections. This change ensures that the user's plan is accurately derived from their active subscription status, improving access control for gated features.
@coderabbitai

coderabbitai Bot commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉


📝 Walkthrough

Walkthrough

Adds a session-refetch event flow: a new TRPC subscription (onSessionRefetch), main process emission on billing-success deep links, and an AuthProvider subscription that triggers session refetch when events arrive.

Changes

Cohort / File(s) Summary
Session Refetch Subscription Infrastructure
apps/desktop/src/lib/trpc/routers/auth/index.ts
Added onSessionRefetch publicProcedure.subscription returning an observable that emits true on "session-refetch" events; registers and cleans up handler on subscribe/unsubscribe.
Session Refetch Event Emission (Main)
apps/desktop/src/main/index.ts
Imported authEvents and emits "session-refetch" when non-auth deep links to /settings/billing contain success=true.
Session Refetch Event Consumption (Renderer)
apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx
Subscribed to onSessionRefetch and calls refetchSession when event data is received; runs alongside existing token-change subscription.
Billing Deep-link URL changes
apps/desktop/src/renderer/routes/_authenticated/settings/billing/components/BillingOverview/BillingOverview.tsx, apps/desktop/src/renderer/routes/_authenticated/settings/billing/plans/page.tsx
Replaced environment-based absolute success URLs with protocol-driven URLs using PROTOCOL_SCHEME (e.g., protocol://settings/billing?success=true) for deep-link handling.

Sequence Diagram

sequenceDiagram
    participant User
    participant Billing
    participant Main
    participant AuthEvents
    participant TRPCAuthRouter
    participant AuthProvider

    User->>Billing: Complete upgrade payment
    Billing->>User: Redirect to success URL
    User->>Main: Open deep link (protocol://settings/billing?success=true)
    Main->>AuthEvents: Emit "session-refetch"
    AuthEvents->>TRPCAuthRouter: Observable emits true
    TRPCAuthRouter-->>AuthProvider: Subscription push (onSessionRefetch)
    AuthProvider->>AuthProvider: Call refetchSession()
    AuthProvider-->>User: Session updated
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • Kitenite

Poem

🐰 I hopped a little event today,

When billing says "success", I softly say,
"Refetch the session, keep things right" —
Subscriptions listen through day and night,
Hoppity-hop, the app feels bright! 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description lacks required template sections like Related Issues, Type of Change, and Testing details that are specified in the repository's description template. Add missing sections from the template: Related Issues (with GitHub keywords like 'closes' or 'fixes'), mark the Type of Change checkboxes, and describe testing steps for the new subscription and URL changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: implementing a session refetch subscription and updating billing success URLs to use protocol schemes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apps/desktop/src/renderer/components/Paywall/usePaywall.ts`:
- Around line 17-20: The code unsafely casts activeSubscription?.plan to
UserPlan; change this to runtime-validate the plan value before assigning
userPlan and handle multiple active subscriptions deterministically: inspect
subscriptionsData to (a) choose the correct active subscription (e.g., sort by
createdAt or status priority instead of using find) and (b) check that
activeSubscription.plan is one of the known UserPlan string literals (e.g.,
"free", "pro", "premium") before using it; if it isn't, fall back to "free" (or
a safe default) and ensure hasAccess uses this validated userPlan. Use the
symbols activeSubscription, subscriptionsData, userPlan, and hasAccess to locate
and update the logic.

Update the logic in the usePaywall hook to derive the user plan based on the active subscription's plan value. This change ensures that users are correctly assigned either a "pro" or "free" plan, enhancing the accuracy of access control for gated features.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apps/desktop/src/renderer/components/Paywall/usePaywall.ts`:
- Around line 13-16: The useLiveQuery call depends on the unstable collections
object causing unnecessary re-runs; extract a stable reference like const
subscriptions = collections.subscriptions (or obtain subscriptions directly from
useCollections) and update the query and dependency array to use that stable
reference instead of collections (i.e., pass (q) => q.from({ subscriptions })
and [subscriptions] as the dependency). This change should be applied where
useLiveQuery and the collections variable are used (look for useLiveQuery and
collections.subscriptions in the file) to prevent re-execution on every render.

@Kitenite

Copy link
Copy Markdown
Member

I've pushed the fix for the unstable collections dependency to origin/pri/ss-5-update-side-bar-task-state. The change extracts collections.subscriptions into a stable local reference so useLiveQuery doesn't re-execute on every render:

 	const collections = useCollections();
+	const subscriptions = collections.subscriptions;

 	const { data: subscriptionsData } = useLiveQuery(
-		(q) => q.from({ subscriptions: collections.subscriptions }),
-		[collections],
+		(q) => q.from({ subscriptions }),
+		[subscriptions],
 	);

You can cherry-pick the commit: ba1f113ec

…y dep

Extract collections.subscriptions to a local variable so useLiveQuery
depends on the stable collection reference instead of the reconstructed
collections object, preventing unnecessary re-executions on every render.
@Kitenite

Copy link
Copy Markdown
Member

we should probably refetch the state session instead of using sessions imo. probably when we come back from stripe with deeplink we should just refetch the session state.

real-time collections can be flaky atm

…ing success URLs

- Added a new subscription for session refetch requests in the auth router to handle session updates after specific events, such as Stripe checkout.
- Emitted a session refetch event upon successful billing deep link navigation.
- Updated success URLs in billing components to use a protocol scheme constant for consistency and improved link handling.
- Refactored the usePaywall hook to simplify user plan determination based on session data.
@Ipriyankrajai Ipriyankrajai changed the title fix(desktop): update usePaywall to utilize active subscriptions for user plan determination feat(desktop): implement session refetch subscription and update billing success URLs Feb 17, 2026
@Ipriyankrajai

Copy link
Copy Markdown
Contributor Author

@Kitenite Made the changes and used deeplink approach

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/desktop/src/renderer/routes/_authenticated/settings/billing/components/BillingOverview/BillingOverview.tsx (1)

34-52: ⚠️ Potential issue | 🟠 Major

Same unstable collections dependency issue — extract stable references.

Same problem as in plans/page.tsx. Extract collections.subscriptions and collections.members into local variables before passing to useLiveQuery.

♻️ Proposed fix
+	const subscriptions = collections.subscriptions;
+	const members = collections.members;
+
 	// Get subscription from Electric (preloaded, instant)
 	const { data: subscriptionsData } = useLiveQuery(
-		(q) => q.from({ subscriptions: collections.subscriptions }),
-		[collections],
+		(q) => q.from({ subscriptions }),
+		[subscriptions],
 	);
...
 	// Get member count from Electric
 	const { data: membersData } = useLiveQuery(
 		(q) =>
 			q
-				.from({ members: collections.members })
+				.from({ members })
 				.select(({ members }) => ({ id: members.id })),
-		[collections],
+		[members],
 	);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/routes/_authenticated/settings/billing/components/BillingOverview/BillingOverview.tsx`
around lines 34 - 52, The useLiveQuery hooks are depending directly on the
unstable collections object (collections.subscriptions and collections.members);
extract stable local references (e.g., const subscriptionsColl =
collections.subscriptions and const membersColl = collections.members) and use
those variables inside the query functions and in the dependency arrays for
useLiveQuery (replace collections with subscriptionsColl/membersColl) so
subscriptionsData, membersData, subscriptionData and derived plan remain stable
and avoid unnecessary re-renders; update both useLiveQuery calls (the one that
queries subscriptions and the one that selects members.id) accordingly.
apps/desktop/src/renderer/routes/_authenticated/settings/billing/plans/page.tsx (1)

208-225: ⚠️ Potential issue | 🟠 Major

Unstable collections reference in useLiveQuery dependency arrays causes unnecessary re-execution.

collections is a new object each render, so [collections] triggers useLiveQuery continuously. Extract the specific collection references into stable local variables, as the reviewer Kitenite already suggested.

♻️ Proposed fix
+	const subscriptions = collections.subscriptions;
+	const members = collections.members;
+
 	// Get subscription from Electric (preloaded, instant)
 	const { data: subscriptionsData } = useLiveQuery(
-		(q) => q.from({ subscriptions: collections.subscriptions }),
-		[collections],
+		(q) => q.from({ subscriptions }),
+		[subscriptions],
 	);
 	const subscriptionData = subscriptionsData?.find(
 		(s) => s.status === "active",
 	);
 
 	const currentPlan: PlanTier = (subscriptionData?.plan as PlanTier) ?? "free";
 	const cancelAt = subscriptionData?.cancelAt;
 
 	const { data: membersData } = useLiveQuery(
 		(q) =>
 			q
-				.from({ members: collections.members })
+				.from({ members })
 				.select(({ members }) => ({ id: members.id })),
-		[collections],
+		[members],
 	);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/desktop/src/renderer/routes/_authenticated/settings/billing/plans/page.tsx`
around lines 208 - 225, The useLiveQuery calls pass the entire unstable
collections object in their dependency arrays causing repeated re-runs; extract
the specific collection references into stable local constants (e.g., const
subscriptions = collections.subscriptions and const members =
collections.members) and update the queries to reference these constants
(useLiveQuery((q) => q.from({ subscriptions }), [subscriptions]) and similarly
for members), ensuring subscriptionData, subscriptionsData, membersData and the
existing selects still work but depend only on the stable collection references.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx`:
- Around line 30-34: The subscription callback in
electronTrpc.auth.onSessionRefetch.useSubscription calls refetchSession() and
currently discards its return value, allowing unhandled promise rejections;
change the onData handler to call refetchSession() and attach rejection handling
(e.g., refetchSession().catch(err => { /* log or ignore */ })) so all errors are
handled consistently with the other refetch usage; update the onData
implementation in the useSubscription callback to explicitly handle promise
rejections for refetchSession.

---

Outside diff comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/settings/billing/components/BillingOverview/BillingOverview.tsx`:
- Around line 34-52: The useLiveQuery hooks are depending directly on the
unstable collections object (collections.subscriptions and collections.members);
extract stable local references (e.g., const subscriptionsColl =
collections.subscriptions and const membersColl = collections.members) and use
those variables inside the query functions and in the dependency arrays for
useLiveQuery (replace collections with subscriptionsColl/membersColl) so
subscriptionsData, membersData, subscriptionData and derived plan remain stable
and avoid unnecessary re-renders; update both useLiveQuery calls (the one that
queries subscriptions and the one that selects members.id) accordingly.

In
`@apps/desktop/src/renderer/routes/_authenticated/settings/billing/plans/page.tsx`:
- Around line 208-225: The useLiveQuery calls pass the entire unstable
collections object in their dependency arrays causing repeated re-runs; extract
the specific collection references into stable local constants (e.g., const
subscriptions = collections.subscriptions and const members =
collections.members) and update the queries to reference these constants
(useLiveQuery((q) => q.from({ subscriptions }), [subscriptions]) and similarly
for members), ensuring subscriptionData, subscriptionsData, membersData and the
existing selects still work but depend only on the stable collection references.

Updated the session refetch subscription in AuthProvider to catch and handle potential errors during the refetch process, ensuring smoother user experience and preventing unhandled promise rejections.
annual,
seats: memberCount,
successUrl: `${env.NEXT_PUBLIC_WEB_URL}/settings/billing?success=true`,
successUrl: `${PROTOCOL_SCHEME}://settings/billing?success=true`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason we're changing this?

@Ipriyankrajai Ipriyankrajai Feb 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want it to redirect it to our app instead of the web

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where we will referch the session

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants