fix(desktop): reconnect billing account via oauth flow
This commit is contained in:
parent
546537e678
commit
2fc88583a9
|
|
@ -1,5 +1,5 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
|
@ -31,6 +31,11 @@ const apiMocks = vi.hoisted(() => ({
|
|||
updateAutoReload: vi.fn()
|
||||
}))
|
||||
|
||||
const oauthMocks = vi.hoisted(() => ({
|
||||
pollOAuthSession: vi.fn(),
|
||||
startOAuthLogin: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./api', () => ({
|
||||
// Pass-through provider — the mocked useBillingApi ignores any override anyway.
|
||||
BillingApiProvider: ({ children }: { children: ReactNode }) => children,
|
||||
|
|
@ -47,6 +52,11 @@ vi.mock('./api', () => ({
|
|||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/hermes', () => ({
|
||||
pollOAuthSession: oauthMocks.pollOAuthSession,
|
||||
startOAuthLogin: oauthMocks.startOAuthLogin
|
||||
}))
|
||||
|
||||
function renderBilling(initialEntries: string[] = ['/settings?tab=billing']) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
|
||||
|
|
@ -64,6 +74,12 @@ function renderBilling(initialEntries: string[] = ['/settings?tab=billing']) {
|
|||
beforeEach(() => {
|
||||
apiMocks.fetchBillingState.mockResolvedValue(okBilling(todayBillingState))
|
||||
apiMocks.fetchSubscriptionState.mockResolvedValue(okSubscription(todaySubscriptionState))
|
||||
oauthMocks.startOAuthLogin.mockResolvedValue({
|
||||
flow: 'device_code',
|
||||
session_id: 'oauth-session-1',
|
||||
verification_url: 'https://portal.nousresearch.com/device'
|
||||
})
|
||||
oauthMocks.pollOAuthSession.mockResolvedValue({ status: 'approved' })
|
||||
Object.defineProperty(window, 'hermesDesktop', {
|
||||
configurable: true,
|
||||
value: {
|
||||
|
|
@ -73,6 +89,7 @@ beforeEach(() => {
|
|||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
|
@ -100,6 +117,34 @@ describe('BillingSettings', () => {
|
|||
expect(screen.getByText('Default ceiling')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('reconnects the billing identity through the Desktop Nous OAuth flow', async () => {
|
||||
const client = renderBilling()
|
||||
const invalidate = vi.spyOn(client, 'invalidateQueries')
|
||||
const reconnect = await screen.findByRole('button', { name: /Reconnect \/ switch account/ })
|
||||
|
||||
vi.useFakeTimers()
|
||||
fireEvent.click(reconnect)
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
expect(oauthMocks.startOAuthLogin).toHaveBeenCalledWith('nous')
|
||||
expect(apiMocks.openExternal).toHaveBeenCalledWith('https://portal.nousresearch.com/device')
|
||||
expect(screen.getByRole('button', { name: /Waiting for approval/ })).toBeTruthy()
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
})
|
||||
|
||||
expect(oauthMocks.pollOAuthSession).toHaveBeenCalledWith('nous', 'oauth-session-1')
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: ['billing', 'state'] })
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: ['billing', 'subscription'] })
|
||||
})
|
||||
|
||||
it('renders the post-train payload with enabled buy controls and card provenance', async () => {
|
||||
apiMocks.fetchBillingState.mockResolvedValue(okBilling(postTrainBillingState))
|
||||
apiMocks.fetchSubscriptionState.mockResolvedValue(okSubscription(postTrainSubscriptionState))
|
||||
|
|
|
|||
|
|
@ -7,8 +7,10 @@ import { Progress } from '@/components/ui/progress'
|
|||
import { SegmentedControl } from '@/components/ui/segmented-control'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { pollOAuthSession, startOAuthLogin } from '@/hermes'
|
||||
import { BarChart3, CreditCard, ExternalLink, Package, Users, Wrench } from '@/lib/icons'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { notify, notifyError } from '@/store/notifications'
|
||||
|
||||
import { useRouteEnumParam } from '../../hooks/use-route-enum-param'
|
||||
import {
|
||||
|
|
@ -48,7 +50,9 @@ const BILLING_VIEWS = ['overview', 'plans'] as const
|
|||
type BillingSubView = (typeof BILLING_VIEWS)[number]
|
||||
|
||||
const FEATURE_BILLING_INVOICES = false
|
||||
const FALLBACK_PORTAL_URL = 'https://portal.nousresearch.com/billing'
|
||||
const NOUS_OAUTH_PROVIDER_ID = 'nous'
|
||||
const NOUS_OAUTH_POLL_INTERVAL_MS = 5000
|
||||
const NOUS_OAUTH_MAX_POLLS = 120
|
||||
|
||||
const BILLING_DEV_FIXTURE_NAMES = import.meta.env.DEV
|
||||
? (Object.keys(billingDevFixtures) as BillingDevFixtureName[])
|
||||
|
|
@ -104,7 +108,15 @@ function NoticeCard({ notice }: { notice: BillingNoticeView }) {
|
|||
)
|
||||
}
|
||||
|
||||
function BillingIdentityCard({ billing }: { billing?: BillingStateResponse }) {
|
||||
function BillingIdentityCard({
|
||||
billing,
|
||||
onReconnect,
|
||||
reconnecting
|
||||
}: {
|
||||
billing?: BillingStateResponse
|
||||
onReconnect: () => void
|
||||
reconnecting: boolean
|
||||
}) {
|
||||
if (!billing?.logged_in) {
|
||||
return null
|
||||
}
|
||||
|
|
@ -126,12 +138,13 @@ function BillingIdentityCard({ billing }: { billing?: BillingStateResponse }) {
|
|||
<ListRow
|
||||
action={
|
||||
<Button
|
||||
onClick={() => openExternal(billing.portal_url ?? FALLBACK_PORTAL_URL)}
|
||||
disabled={reconnecting}
|
||||
onClick={onReconnect}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
Reconnect / switch account
|
||||
{reconnecting ? 'Waiting for approval…' : 'Reconnect / switch account'}
|
||||
<ExternalLink className="size-3.5" />
|
||||
</Button>
|
||||
}
|
||||
|
|
@ -496,6 +509,64 @@ function BillingSettingsContent({
|
|||
onFixtureChange?: (value: BillingFixtureSelection) => void
|
||||
}) {
|
||||
const [subView, setSubView] = useRouteEnumParam<BillingSubView>('bview', BILLING_VIEWS, 'overview')
|
||||
const queryClient = useQueryClient()
|
||||
const [reconnectingAccount, setReconnectingAccount] = useState(false)
|
||||
|
||||
const refreshBillingQueries = async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['billing', 'state'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['billing', 'subscription'] })
|
||||
])
|
||||
}
|
||||
|
||||
const reconnectBillingAccount = async () => {
|
||||
if (reconnectingAccount) {
|
||||
return
|
||||
}
|
||||
|
||||
setReconnectingAccount(true)
|
||||
|
||||
try {
|
||||
const start = await startOAuthLogin(NOUS_OAUTH_PROVIDER_ID)
|
||||
|
||||
if (start.flow !== 'device_code') {
|
||||
notifyError(new Error(`unexpected flow: ${start.flow}`), 'Could not start Nous sign-in')
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
await openExternal(start.verification_url)
|
||||
|
||||
for (let attempt = 0; attempt < NOUS_OAUTH_MAX_POLLS; attempt += 1) {
|
||||
await new Promise(resolve => window.setTimeout(resolve, NOUS_OAUTH_POLL_INTERVAL_MS))
|
||||
|
||||
const polled = await pollOAuthSession(NOUS_OAUTH_PROVIDER_ID, start.session_id)
|
||||
|
||||
if (polled.status === 'approved') {
|
||||
notify({
|
||||
kind: 'success',
|
||||
title: 'Nous account connected',
|
||||
message: 'Billing account details are refreshing.'
|
||||
})
|
||||
await refreshBillingQueries()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (polled.status !== 'pending') {
|
||||
notifyError(new Error(polled.error_message || `Sign-in ${polled.status}`), 'Nous sign-in failed')
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
notifyError(new Error('Timed out waiting for OAuth approval'), 'Nous sign-in timed out')
|
||||
} catch (err) {
|
||||
notifyError(err, 'Nous sign-in failed')
|
||||
} finally {
|
||||
setReconnectingAccount(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Fixture mode flows through the SAME query path — the simulated api (supplied by
|
||||
// BillingApiProvider in the DEV wrapper) backs these fetches — so there is no
|
||||
|
|
@ -554,7 +625,11 @@ function BillingSettingsContent({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<BillingIdentityCard billing={billing} />
|
||||
<BillingIdentityCard
|
||||
billing={billing}
|
||||
onReconnect={() => void reconnectBillingAccount()}
|
||||
reconnecting={reconnectingAccount}
|
||||
/>
|
||||
|
||||
{view.plan && (
|
||||
<SettingsSection icon={Package} title="Plan">
|
||||
|
|
|
|||
Loading…
Reference in New Issue