Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## [0.9.1] - 2026-11-10

### Fixed

- **Billing screens stay current without a reload.** The plan picker, the subscription badge, the billing notice and the subscription pages now re-read the plans and the current plan when the tab regains focus (more than 30 seconds after the last read), when the sign-in is renewed, and when a live plan, subscription or payment event arrives. A plan created, changed or removed in Bridge now appears without reloading the page. A background re-read never blanks what is on screen, a failed or empty read is tried once more, and an answer that arrives after signing out is dropped. (TBP-762)

### Changed

- **The agent guides follow "every gate is a flag".** The billing, flags and team guides open with the rule and end with `npx @nebulr-group/bridge-cli check gates`; the billing guide no longer says a paid feature should not be a flag, and no guide shows a role or plan check written into app code. (TBP-705)
- **Seat limits are in the team and billing guides**, with `seatsMetric` on the built-in team page and the setup command. (TBP-763)
- **The guides name the Bridge MCP tools** for plans and flags next to the CLI commands, and no longer tell agents to prefer the CLI. (TBP-576)
- **The live-updates page explains why live updates are off**: the status reasons, whose side each one is on, and a link to the troubleshooting page. (TBP-642, TBP-675)
- **A test now fails when a guide names something the package does not have**: an export, a component, a prop, a billing option or a `bridge.*` path.

These bring the React package level with the Svelte package on billing refresh and the guides.

## [0.9.0] - 2026-11-10

### Changed
Expand Down
2 changes: 1 addition & 1 deletion bridge-react/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nebulr-group/bridge-react",
"version": "0.9.0",
"version": "0.9.1",
"description": "The Bridge for React: sign-in, workspaces and roles, feature flags, Stripe subscriptions and plan limits, with React Router or TanStack Router.",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
Expand Down
15 changes: 4 additions & 11 deletions bridge-react/src/components/subscription/BridgeBillingNotice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
} from '@nebulr-group/bridge-auth-core';
import { getBridgeAuth } from '../../core/bridge-instance';
import { billingRoutes } from '../../core/billing-routes';
import { tokenStaleHandler } from '../../core/bridge-runtime';
import { ensureBillingState } from '../../core/billing-state';
import { useBridgeSnapshot } from '../../hooks/use-bridge-readable';

type Chassis = 'bar' | 'rail' | 'card';
Expand Down Expand Up @@ -80,16 +80,9 @@ export function BridgeBillingNotice({
subscription.setError('Not authenticated');
return;
}
if (!subscription.snapshot().state) {
void subscription.mount({
apiBaseUrl: ctx.apiBaseUrl,
accessToken: ctx.accessToken,
appId: ctx.appId,
// TBP-762 — right after a checkout the sign-in is out of date; renew it
// and retry once instead of showing "Subscription unavailable".
onTokenStale: tokenStaleHandler(),
});
}
// TBP-762 — through the billing store: renews an out-of-date sign-in,
// retries once, and re-reads on the store's refresh rule.
void ensureBillingState();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down
9 changes: 4 additions & 5 deletions bridge-react/src/components/subscription/BridgePaywall.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
*/
import { useEffect, useMemo, type ReactNode } from 'react';
import type { Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core';
import { loadSubscription, useBridgeStore } from '../../core/bridge-instance';
import { ensureSubscription, useBridgeStore } from '../../core/bridge-instance';
import { PlanSelector } from './PlanSelector';

export interface BridgePaywallProps {
Expand All @@ -49,10 +49,9 @@ export function BridgePaywall({
const { status, loading } = subscription;

useEffect(() => {
if (!status && !loading) {
void loadSubscription();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
// TBP-762 — read unless a read younger than 30 s exists; the billing
// store's refresh rule keeps it current from then on.
void ensureSubscription();
}, []);

// Show paywall only once the subscription status is known and the tenant has
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
*
* Reactive translation (§5.1): svelte `$state(useBridge().subscription.snapshot())`
* + `onMount(() => subscription.subscribe(...))` → `useBridgeSnapshot(subscribe,
* getSnapshot)`. The one-shot `mount()` fetch stays in a `useEffect`.
* getSnapshot)`. The read on mount (`ensureBillingState()`) stays in a `useEffect`.
*
* No live push in v1 — fetches once on mount (the realtime wiring lands with the
* provider's `attachToRealtimeClient`).
* Live: auth-core patches the store on billing pushes, and the billing store's
* refresh rule (TBP-762) re-reads it on sign-in renewal, live billing events
* and tab focus.
*/
import { useEffect } from 'react';
import { useBridge } from '@nebulr-group/bridge-auth-core';
import { getBridgeAuth } from '../../core/bridge-instance';
import { tokenStaleHandler } from '../../core/bridge-runtime';
import { ensureBillingState } from '../../core/billing-state';
import { useBridgeSnapshot } from '../../hooks/use-bridge-readable';

export interface BridgeSubscriptionStatusProps {
Expand All @@ -37,21 +37,10 @@ export function BridgeSubscriptionStatus({
);

useEffect(() => {
const ctx = getBridgeAuth().getApiContext();
if (!ctx.accessToken) {
subscription.setError('Not authenticated');
return;
}
void subscription.mount({
apiBaseUrl: ctx.apiBaseUrl,
accessToken: ctx.accessToken,
appId: ctx.appId,
// TBP-762 — right after a checkout the sign-in is out of date; renew it
// and retry once instead of showing "Subscription unavailable".
onTokenStale: tokenStaleHandler(),
});
// subscription is the auth-core singleton — stable across renders.
// eslint-disable-next-line react-hooks/exhaustive-deps
// TBP-762 — through the billing store: read unless a read younger than
// 30 s exists, renew an out-of-date sign-in, retry once, and stay current
// on the refresh rule (sign-in renewal, live billing events, tab focus).
void ensureBillingState();
}, []);

return (
Expand Down
176 changes: 158 additions & 18 deletions bridge-react/src/core/billing-refresh.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,165 @@
// TBP-743 — re-read everything billing after something changed the plan (a
// plan pick, a checkout). Mirrors bridge-svelte's `refreshBilling()`: the plan
// list and current plan (the subscription slice `<PlanSelector>` reads) and
// the billing state (`<BridgeSubscriptionStatus>`, `<BridgeBillingNotice>`).
// Never throws: each read reports its own failure through its store.
// TBP-762 — the billing screens' refresh rule. Ported from bridge-svelte's
// `core/billing-store.ts`.
//
// The plan list and current plan (the store slice `<PlanSelector>`,
// `<BridgePaywall>` and the subscription page read) and the canonical billing
// state (`<BridgeSubscriptionStatus>`, `<BridgeBillingNotice>`) are re-read
// together, on one rule:
//
// - when the sign-in is renewed (a new access token: refresh, sign-in, the
// re-mint a plan change causes);
// - on a live billing event (plan change, subscription or payment lifecycle);
// - when the tab regains focus and the last read is older than 30 seconds —
// how a plan created, changed or removed in Bridge reaches an open page;
// - one retry when a read fails.
//
// Screens call `ensureSubscription()` / `ensureBillingState()` on mount and
// read the stores. Only what some screen has asked for is re-read, so an app
// that never shows billing makes no extra calls.
//
// Before 0.9.1 nothing re-read the plan list after the first load: a plan added
// in Bridge did not appear until a reload.

import { useBridge as useBillingBridge } from '@nebulr-group/bridge-auth-core';
import { getBridgeAuth, loadSubscription } from './bridge-instance';
import { tokenStaleHandler } from './bridge-runtime';
import {
ensureSubscription,
getBridgeAuth,
loadSubscription,
subscriptionWanted,
useBridgeStore,
} from './bridge-instance';
import {
BILLING_STALE_AFTER_MS,
billingStateReadToken,
billingStateWanted,
ensureBillingState,
refreshBillingState,
} from './billing-state';
import { readEntitlements } from './startup-reads';
import { logger } from '../utils/logger';

export async function refreshBilling(): Promise<void> {
await loadSubscription().catch(() => {});
export { BILLING_STALE_AFTER_MS, ensureBillingState, refreshBillingState } from './billing-state';

function stateInStore(): boolean {
try {
const ctx = getBridgeAuth().getApiContext();
if (!ctx.accessToken) return;
await useBillingBridge().subscription.mount({
apiBaseUrl: ctx.apiBaseUrl,
accessToken: ctx.accessToken,
appId: ctx.appId,
onTokenStale: tokenStaleHandler(),
});
return useBillingBridge().subscription.snapshot().state !== null;
} catch {
/* the badge re-reads on its own next mount */
return false;
}
}

/**
* Re-read everything billing after something changed the plan (a plan pick, a
* checkout, a live billing event): the plan list and current plan when a
* screen has asked for them, the billing state, and the plan's features (what
* `bridge:billing.entitlement.*` flag rules read; Bridge does not always push
* `entitlements.changed` for a plan change). Never rejects.
*/
export async function refreshBilling(): Promise<void> {
try {
const reads: Promise<void>[] = [];
if (subscriptionWanted()) reads.push(loadSubscription());
if (billingStateWanted() || stateInStore()) reads.push(refreshBillingState());
reads.push(readEntitlements());
await Promise.all(reads);
} catch (err) {
// Bridge not initialised (tests): nothing to re-read.
logger.debug('[bridge-billing] refresh skipped:', err);
}
}

/** On mount: read what has not been read, or was read more than 30 s ago. */
export async function ensureBilling(maxAgeMs = BILLING_STALE_AFTER_MS): Promise<void> {
try {
await Promise.all([ensureSubscription(maxAgeMs), ensureBillingState(maxAgeMs)]);
} catch (err) {
logger.debug('[bridge-billing] ensure skipped:', err);
}
}

/** Live events after which the billing stores are re-read. */
export const BILLING_REFRESH_EVENTS: ReadonlySet<string> = new Set([
'subscription.plan_changed',
'subscription.created',
'subscription.updated',
'subscription.canceled',
'subscription.reactivated',
'subscription.trial_started',
'subscription.trial_converted',
'subscription.trial_expired',
'payment.succeeded',
'payment.failed',
'dunning.recovered',
'dunning.exhausted',
]);

/** The runtime calls this for every realtime billing event. Never throws. */
export function billingEventReceived(kind: string): void {
if (!BILLING_REFRESH_EVENTS.has(kind)) return;
void refreshBilling();
}

/**
* A renewed sign-in: re-read what the screens asked for. The runtime has
* already re-read the billing state and the plan's features for a token that
* changes the session or the plan (TBP-941); a read that started with this
* token is not repeated.
*/
function signInRenewed(token: string): void {
const reads: Promise<void>[] = [];
if (subscriptionWanted()) reads.push(loadSubscription());
if ((billingStateWanted() || stateInStore()) && billingStateReadToken() !== token) {
reads.push(refreshBillingState());
}
void Promise.all(reads);
}

let _stop: (() => void) | null = null;

/**
* Install the sign-in-renewal and tab-focus triggers. Browser only; returns
* the stop function. Idempotent: a second call replaces the first.
* `<BridgeProvider>` calls it on mount.
*/
export function startBillingRefresh(): () => void {
_stop?.();
let lastToken = useBridgeStore.getState().tokens?.accessToken ?? null;
const offToken = useBridgeStore.subscribe((state) => {
const token = state.tokens?.accessToken ?? null;
if (token === lastToken) return;
lastToken = token;
if (token) signInRenewed(token);
});

const onFocus = () => {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
try {
if (!getBridgeAuth().getApiContext().accessToken) return;
} catch {
return;
}
const reads: Promise<void>[] = [];
if (subscriptionWanted()) reads.push(ensureSubscription(BILLING_STALE_AFTER_MS));
if (billingStateWanted() || stateInStore()) reads.push(ensureBillingState(BILLING_STALE_AFTER_MS));
void Promise.all(reads);
};
const win = typeof window !== 'undefined' && typeof window.addEventListener === 'function' ? window : null;
const doc = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : null;
win?.addEventListener('focus', onFocus);
doc?.addEventListener('visibilitychange', onFocus);

const stop = () => {
offToken();
win?.removeEventListener('focus', onFocus);
doc?.removeEventListener('visibilitychange', onFocus);
if (_stop === stop) _stop = null;
};
_stop = stop;
return stop;
}

/** Test-only. */
export function __resetBillingRefreshForTests(): void {
_stop?.();
_stop = null;
}
Loading
Loading