feat(studio): filter organization usage by branch FE-4153 (#49257)

## Summary

Customers could see a branch-driven egress overage in their organization
total but could not select the branch on the Usage page. This adds a
branch filter next to the parent project selector and uses the selected
branch's project ref for usage requests.

- Validate bookmarked branch refs before displaying usage. Show loading
and API errors explicitly, and disclose when an unavailable branch falls
back to its parent.
- Keep the filter, notice, and usage requests on the same project ref.
Allow returning to the parent even when the branches response omits its
main row.
- Find the selected branch's disk usage beyond the first page of
organization projects and explain that deleted branches still contribute
to organization totals.
- Correct the branching and egress documentation to explain separate
branch usage.

## Scope

This is the branch-selector improvement proposed in FE-4153's
discussion. It does not provide the original ticket's reconciled
per-project egress table or historical rows for deleted branches. The
current daily-usage API contract supports a single project filter, but
does not return project-grouped usage. Keep the full reconciliation work
open.

## Validation

All 47 focused Vitest tests pass across six files, including nine MSW
page tests covering usage request refs, direct branch links,
pending/failed lookups, deleted-branch fallback, invalid-project
recovery, and denied subscription permissions. Disk tests cover
selection beyond the first 96 projects and pagination failures.
Deterministic shuffled runs with seeds `4153` and `49257` pass with
retries disabled (`--retry=0`). Four focused production mutants were
killed by behavioral assertions; original source bytes were restored and
verified after every probe.

Studio TypeScript, Prettier on all PR paths, and focused lint checks
pass; inherited `any` warnings remain.

Browser QA on the matching `be17d77` Vercel preview passed parent usage
(0.213 GB), searching for `dev-test`, branch selection, return to main,
invalid-project recovery, stale-branch fallback, and returning to
organization totals. The selected branch showed 0 GB, so nonzero branch
overage was not verified. Browser network traffic was not captured;
request-ref coverage comes from MSW.

Three existing auth/router/platform module-mock scaffolds remain as a
test-harness limitation; strict no-module-mock compliance is not
claimed.

All Studio unit-test and E2E shards passed on be17d77801; CI report jobs
are finishing.

Related: FE-4153


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Filter organization usage by project branch with searchable branch
selection. Usage details reflect the selected branch where available,
including branches found on later project-list pages.
* See whether usage is scoped to a branch, the main branch, or a
project, and switch to organization-wide totals. Billing and quota
totals include all branches, including deleted branches that are no
longer selectable.
* **Documentation**
* Clarified how non-compute usage is recorded per branch, included in
organization totals, and viewed; it isn’t itemized by branch on
invoices.
* Clarified that Preview branch Egress counts toward organization
totals, not the parent project’s usage, and how to view it.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Jordi Enric authored and GitHub committed 2026-10-19 11:30:37 +00:00
1 parent 2b7f5ace51
commit 090e5bceff
13 files changed
+1404 -122

No files matched your search

@@ -19,7 +19,7 @@ Refer to individual [usage items](/docs/guides/platform/manage-your-usage) for d
### Usage on your invoice
Compute incurred by Preview branches is shown as "Branching Compute Hours" on your invoice. Other usage items are not shown separately for branches and are rolled up into the project.
Compute incurred by Preview branches is shown as "Branching Compute Hours" on your invoice. Other usage items are recorded against the branch itself and count toward your organization total, but are not listed separately per branch on your invoice. To see them, select the parent project on the [usage page](/dashboard/org/_/usage), then select the branch from the branch list.
## Pricing
@@ -121,6 +121,8 @@ The organization's Egress usage exceeds the uncached egress quota by 50 GB and t
You can view Egress usage on the [organization's usage page](/dashboard/org/_/usage). The page shows the usage of all projects by default. To view the usage for a specific project, select it from the dropdown. You can also select a different time period.
Each [Preview branch](/docs/guides/deployment/branching) records its own Egress, which counts toward the organization total but is not included in the parent project's usage. To see a branch's Egress, select the parent project, then select the branch from the branch list.
<Image
alt="Usage page navigation bar"
src={{
@@ -0,0 +1,480 @@
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { platformComponents as components } from 'api-types'
import { HttpResponse } from 'msw'
import type { UrlUpdateEvent } from 'nuqs/adapters/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Usage } from './Usage'
import type { Branch } from '@/data/branches/branches-query'
import { createMockOrganizationResponse, createMockProject } from '@/tests/helpers'
import { createTestBranch } from '@/tests/lib/branch-test-utils'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
import { routerMock } from '@/tests/lib/route-mock'
vi.mock('common', async (importOriginal) => ({
...(await importOriginal<typeof import('common')>()),
useIsLoggedIn: () => true,
}))
vi.mock('@/lib/constants', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/constants')>()),
IS_PLATFORM: true,
}))
vi.mock('next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('next/navigation')>()),
usePathname: () => routerMock.pathname,
}))
const parent = createMockProject({ ref: 'parent-ref', name: 'Parent project' })
const branch = createTestBranch({ name: 'Preview branch' })
const main = createTestBranch({ id: 'main-id', project_ref: parent.ref, is_default: true })
const parentDetail: components['schemas']['ProjectDetailResponse_Output'] = {
...parent,
connectionString: null,
db_host: 'db.parent-ref.supabase.co',
high_availability: false,
integration_source: null,
inserted_at: '2026-01-01T00:00:00Z',
is_physical_backups_enabled: false,
restUrl: 'https://parent-ref.supabase.co',
status: 'ACTIVE_HEALTHY',
subscription_id: 'subscription-1',
updated_at: '2026-01-01T00:00:00Z',
}
const branchDetail = {
...parentDetail,
ref: branch.project_ref,
name: branch.name,
parent_project_ref: parent.ref,
}
function renderUsage(branchRef: string | null = branch.project_ref, projectRef = parent.ref) {
const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>()
const searchParams: Record<string, string> = { projectRef }
if (branchRef !== null) searchParams.branchRef = branchRef
routerMock.setCurrentUrl({
pathname: '/org/test-org/usage',
query: { slug: 'test-org', ...searchParams },
})
customRender(<Usage />, {
profileContext: createMockProfileContext(),
nuqs: { searchParams, hasMemory: true, onUrlUpdate },
})
return { onUrlUpdate }
}
function captureUsageRequests() {
const requests: { usage: (string | null)[]; daily: (string | null)[] } = {
usage: [],
daily: [],
}
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/usage',
response: ({ request }) => {
const ref = new URL(request.url).searchParams.get('project_ref')
requests.usage.push(ref)
let usage = 23
if (ref === branch.project_ref) usage = 7
if (ref === parent.ref) usage = 13
return HttpResponse.json<components['schemas']['OrgUsageResponse_Output']>({
usages: [
{
metric: 'EGRESS',
usage,
usage_original: usage * 1e9,
available_in_plan: true,
capped: true,
cost: 0,
pricing_free_units: 5,
pricing_strategy: 'UNIT',
project_allocations: [],
unit_price_desc: 'Egress per GB',
unlimited: false,
},
],
usage_billing_enabled: false,
})
},
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/usage/daily',
response: ({ request }) => {
requests.daily.push(new URL(request.url).searchParams.get('project_ref'))
return HttpResponse.json<components['schemas']['OrgDailyUsageResponse_Output']>({
usages: [],
})
},
})
return requests
}
function expectUsageRefs(
requests: ReturnType<typeof captureUsageRequests>,
refs: (string | null)[]
) {
expect(new Set(requests.usage)).toEqual(new Set(refs))
expect(new Set(requests.daily)).toEqual(new Set(refs))
}
describe('Usage branch URLs', () => {
beforeEach(() => {
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) =>
HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
params.ref === branch.project_ref ? branchDetail : parentDetail
),
})
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () =>
HttpResponse.json<components['schemas']['OrganizationResponse_Output'][]>([
createMockOrganizationResponse({ slug: 'test-org' }),
]),
})
addAPIMock({
method: 'get',
path: '/platform/profile/permissions',
response: () =>
HttpResponse.json<components['schemas']['AccessControlPermission'][]>([
{
actions: ['%'],
resources: ['%'],
organization_id: 1,
organization_slug: 'test-org',
project_ids: [],
project_refs: [],
condition: null,
restrictive: false,
},
]),
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/billing/subscription',
response: () =>
HttpResponse.json<components['schemas']['GetSubscriptionResponse']>({
addons: [],
billing_via_partner: false,
current_period_start: 1767225600,
current_period_end: 1769904000,
next_invoice_at: 1769904000,
payment_method_type: 'card',
plan: { id: 'free', name: 'Free' },
project_addons: [],
usage_billing_enabled: false,
}),
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: () => HttpResponse.json<Branch[]>([main, branch]),
})
})
it('shows the permission notice when subscription access is denied', async () => {
captureUsageRequests()
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: () =>
HttpResponse.json<components['schemas']['OrganizationProjectsResponse_Output']>({
projects: [],
pagination: { count: 0, limit: 96, offset: 0 },
}),
})
addAPIMock({
method: 'get',
path: '/platform/profile/permissions',
response: () => HttpResponse.json<components['schemas']['AccessControlPermission'][]>([]),
})
const subscriptionRequested = vi.fn()
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/billing/subscription',
response: () => {
subscriptionRequested()
return HttpResponse.json<APIErrorBody>({ message: 'Forbidden' }, { status: 403 })
},
})
renderUsage()
expect(
await screen.findByText(/additional permissions to view organization usage/)
).toBeVisible()
expect(screen.queryByRole('button', { name: 'Current billing cycle' })).not.toBeInTheDocument()
expect(subscriptionRequested).not.toHaveBeenCalled()
})
it('requests both usage endpoints with the branch project ref from the URL', async () => {
const requests = captureUsageRequests()
renderUsage()
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name)
expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument()
})
it('resolves a direct branch URL and switches to main and organization totals', async () => {
const user = userEvent.setup()
const requests = captureUsageRequests()
const branchListRefs: string[] = []
const projectRefs: string[] = []
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) => {
projectRefs.push(String(params.ref))
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
params.ref === branch.project_ref ? branchDetail : parentDetail
)
},
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: ({ params }) => {
branchListRefs.push(String(params.ref))
return HttpResponse.json<Branch[]>([main, branch])
},
})
const { onUrlUpdate } = renderUsage(null, branch.project_ref)
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
expect(await screen.findByText('7 GB')).toBeVisible()
expect(new Set(projectRefs)).toEqual(new Set([branch.project_ref, parent.ref]))
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name)
expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent(parent.name)
await user.click(screen.getByLabelText('Filter by branch'))
await user.click(await screen.findByRole('option', { name: main.name }))
expect(await screen.findByText(/Main branch only/)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref, parent.ref])
})
expect(await screen.findByText('13 GB')).toBeVisible()
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(main.name)
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
await user.click(screen.getByLabelText('Filter by branch'))
await user.click(await screen.findByRole('option', { name: branch.name }))
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'View organization total' }))
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref, parent.ref, null])
const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams
expect(searchParams).toBeDefined()
expect(searchParams?.has('projectRef')).toBe(false)
expect(searchParams?.has('branchRef')).toBe(false)
})
expect(await screen.findByText('23 / 5 GB')).toBeVisible()
expect(screen.queryByLabelText('Filter by branch')).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'View organization total' })
).not.toBeInTheDocument()
})
it('waits for direct branch project details before requesting branches or usage', async () => {
const requests = captureUsageRequests()
const response = Promise.withResolvers<void>()
const projectRequested = vi.fn()
const branchListRefs: string[] = []
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: async ({ params }) => {
if (params.ref === branch.project_ref) {
projectRequested()
await response.promise
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
branchDetail
)
}
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
parentDetail
)
},
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: ({ params }) => {
branchListRefs.push(String(params.ref))
return HttpResponse.json<Branch[]>([main, branch])
},
})
renderUsage(null, branch.project_ref)
try {
await waitFor(() => expect(projectRequested).toHaveBeenCalled())
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(branchListRefs).toEqual([])
expect(requests).toEqual({ usage: [], daily: [] })
} finally {
await act(async () => response.resolve())
}
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
})
it('blocks a direct branch link when its parent project lookup fails', async () => {
const requests = captureUsageRequests()
const branchRequested = vi.fn()
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) =>
params.ref === branch.project_ref
? HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(branchDetail)
: HttpResponse.json<APIErrorBody>({ message: 'Parent lookup failed' }, { status: 500 }),
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: () => {
branchRequested()
return HttpResponse.json<Branch[]>([main, branch])
},
})
renderUsage(null, branch.project_ref)
expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(branchRequested).not.toHaveBeenCalled()
expect(requests).toEqual({ usage: [], daily: [] })
})
it('does not request parent usage while the branch list is pending', async () => {
const requests = captureUsageRequests()
const response = Promise.withResolvers<Branch[]>()
const branchRequested = vi.fn()
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: async () => {
branchRequested()
return HttpResponse.json<Branch[]>(await response.promise)
},
})
renderUsage()
try {
await waitFor(() => expect(branchRequested).toHaveBeenCalled())
expect(await screen.findByText('Free Plan')).toBeInTheDocument()
expect(screen.getByRole('status', { name: 'Loading branch usage' })).toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
} finally {
await act(async () => response.resolve([main, branch]))
}
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
})
it('shows a branch error without requesting parent usage when the branch list fails', async () => {
const requests = captureUsageRequests()
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Branch lookup failed' }, { status: 500 }),
})
renderUsage()
expect(await screen.findByText('Failed to retrieve branches')).toBeInTheDocument()
expect(await screen.findByText('Free Plan')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
})
it('shows Branch unavailable and requests parent usage for a deleted branch ref', async () => {
const requests = captureUsageRequests()
renderUsage('deleted-branch-ref')
expect(await screen.findByText('Branch unavailable')).toBeInTheDocument()
expect(screen.getByText(/Main branch only/)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [parent.ref])
})
})
it('keeps filters usable after a project lookup failure and recovers through All projects', async () => {
const user = userEvent.setup()
const requests = captureUsageRequests()
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) =>
params.ref === parent.ref
? HttpResponse.json<APIErrorBody>({ message: 'Project lookup failed' }, { status: 404 })
: HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(branchDetail),
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: () =>
HttpResponse.json<components['schemas']['OrganizationProjectsResponse_Output']>({
projects: [],
pagination: { count: 0, limit: 96, offset: 0 },
}),
})
const { onUrlUpdate } = renderUsage()
expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
await user.click(await screen.findByRole('button', { name: 'Current billing cycle' }))
expect(
await screen.findByRole('menuitemradio', { name: 'Current billing cycle' })
).toBeInTheDocument()
await user.keyboard('{Escape}')
const projectPicker = screen.getByRole('combobox', { name: '' })
expect(projectPicker).toHaveTextContent(parent.ref)
await user.click(projectPicker)
const allProjects = await screen.findByRole('option', { name: 'All projects' })
expect(screen.getByText('Failed to retrieve project')).toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
await user.click(allProjects)
await waitFor(() => {
expectUsageRefs(requests, [null])
const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams
expect(searchParams).toBeDefined()
expect(searchParams?.has('projectRef')).toBe(false)
expect(searchParams?.has('branchRef')).toBe(false)
})
expect(screen.queryByText('Failed to retrieve project')).not.toBeInTheDocument()
expect(screen.getByText('Usage Summary')).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent('All projects')
})
})
@@ -2,8 +2,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { ChartAreaIcon, CheckIcon, ChevronDownIcon } from 'lucide-react'
import Link from 'next/link'
import { useQueryState } from 'nuqs'
import { parseAsString, useQueryStates } from 'nuqs'
import { useMemo, useState } from 'react'
import { Button, cn, CommandGroup, CommandItem } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
@@ -18,6 +17,9 @@ import OrgLogUsage from './OrgLogUsage'
import { Pipelines } from './Pipelines'
import SizeAndCounts from './SizeAndCounts'
import { TotalUsage } from './TotalUsage'
import { getUsageBranchOptions, resolveUsageProjectRef } from './Usage.utils'
import { UsageBranchFilter } from './UsageBranchFilter'
import { UsageFilterNotice } from './UsageFilterNotice'
import {
ScaffoldContainer,
ScaffoldHeader,
@@ -30,6 +32,7 @@ import { HighAvailabilityDisabledEmptyState } from '@/components/ui/HighAvailabi
import { NoPermission } from '@/components/ui/NoPermission'
import { OrganizationProjectSelector } from '@/components/ui/OrganizationProjectSelector'
import { useOrgDailyStatsQuery } from '@/data/analytics/org-daily-stats-query'
import { useBranchesQuery } from '@/data/branches/branches-query'
import { useProjectDetailQuery } from '@/data/projects/project-detail-query'
import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
@@ -41,14 +44,74 @@ export const Usage = () => {
const [dateRange, setDateRange] = useState<any>()
const [selectedProjectRef, setSelectedProjectRef] = useQueryState('projectRef')
const [{ projectRef, branchRef }, setUsageFilter] = useQueryStates({
projectRef: parseAsString,
branchRef: parseAsString,
})
const [openProjectSelector, setOpenProjectSelector] = useState(false)
const { data: selectedProject, isPending: isLoadingSelectedProject } = useProjectDetailQuery({
ref: selectedProjectRef ?? undefined,
const {
data: requestedProject,
isPending: isLoadingRequestedProject,
isError: isErrorRequestedProject,
error: requestedProjectError,
} = useProjectDetailQuery({
ref: projectRef ?? undefined,
})
const parentProjectRef = requestedProject?.parent_project_ref
const {
data: parentProject,
isPending: isLoadingParentProject,
isError: isErrorParentProject,
error: parentProjectError,
} = useProjectDetailQuery({ ref: parentProjectRef ?? undefined })
const selectedProjectRef = parentProjectRef ?? projectRef
const selectedBranchRef = branchRef ?? (parentProjectRef ? projectRef : null)
const selectedProject = parentProjectRef ? parentProject : requestedProject
const isLoadingSelectedProject =
!!projectRef && (isLoadingRequestedProject || (!!parentProjectRef && isLoadingParentProject))
const isErrorSelectedProject =
isErrorRequestedProject || (!!parentProjectRef && isErrorParentProject)
const selectedProjectError = requestedProjectError ?? parentProjectError
const isHighAvailability = resolveHighAvailability(selectedProject)
const canLoadUsage = !selectedProjectRef || (!isLoadingSelectedProject && !isHighAvailability)
const canLoadProjectUsage =
!selectedProjectRef ||
(!isLoadingSelectedProject && !isErrorSelectedProject && !isHighAvailability)
const {
data: branches,
isLoading: isLoadingBranches,
isPending: isPendingBranches,
isError: isErrorBranches,
isSuccess: isSuccessBranches,
error: branchesError,
} = useBranchesQuery(
{
projectRef: selectedProjectRef ?? undefined,
},
{ enabled: !!selectedProject && !isHighAvailability }
)
const branchOptions = useMemo(() => getUsageBranchOptions(branches), [branches])
const usageProjectRef = resolveUsageProjectRef(
selectedProjectRef,
branchOptions,
selectedBranchRef
)
const selectedBranch = branchOptions.find(
(branch) => branch.project_ref === usageProjectRef && branch.project_ref !== selectedProjectRef
)
const isProjectLookupBlocked = !!selectedProjectRef && isErrorSelectedProject
const isResolvingBranch =
!!selectedProjectRef && !!selectedBranchRef && isPendingBranches && !isProjectLookupBlocked
const isBranchLookupBlocked = !!selectedBranchRef && isErrorBranches
const isBranchUnavailable =
!!selectedBranchRef && isSuccessBranches && usageProjectRef !== selectedBranchRef
const canShowUsage =
!isLoadingSelectedProject &&
!isResolvingBranch &&
!isBranchLookupBlocked &&
!isProjectLookupBlocked
const canLoadUsage = canLoadProjectUsage && canShowUsage
const { can: canReadSubscriptions, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(
PermissionAction.BILLING_READ,
@@ -58,10 +121,13 @@ export const Usage = () => {
const {
data: subscription,
error: subscriptionError,
isPending: isLoadingSubscription,
isLoading: isLoadingSubscription,
isError: isErrorSubscription,
isSuccess: isSuccessSubscription,
} = useOrgSubscriptionQuery({ orgSlug: slug }, { enabled: canLoadUsage })
} = useOrgSubscriptionQuery(
{ orgSlug: slug },
{ enabled: canReadSubscriptions && !isHighAvailability }
)
const billingCycleStart = useMemo(() => {
return dayjs.unix(subscription?.current_period_start ?? 0).utc()
@@ -114,7 +180,7 @@ export const Usage = () => {
} = useOrgDailyStatsQuery(
{
orgSlug: slug,
projectRef: selectedProjectRef ?? undefined,
projectRef: usageProjectRef ?? undefined,
startDate,
endDate,
},
@@ -165,7 +231,7 @@ export const Usage = () => {
{isSuccessSubscription && (
<div className="flex lg:items-center items-start gap-3 flex-col lg:flex-row lg:justify-between w-full">
<div className="flex items-center gap-2">
<div className="flex flex-wrap items-center gap-2">
<DateRangePicker
onChange={setDateRange}
value={TIME_PERIODS_BILLING[0].key}
@@ -181,7 +247,7 @@ export const Usage = () => {
setOpen={setOpenProjectSelector}
selectedRef={selectedProjectRef}
onSelect={(project) => {
setSelectedProjectRef(project.ref)
setUsageFilter({ projectRef: project.ref, branchRef: null })
}}
renderTrigger={({ listboxId, open }) => {
return (
@@ -196,7 +262,7 @@ export const Usage = () => {
<ChevronDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
}
>
{!selectedProject ? 'All projects' : selectedProject?.name}
{selectedProject?.name ?? selectedProjectRef ?? 'All projects'}
</Button>
)
}}
@@ -217,11 +283,11 @@ export const Usage = () => {
className="cursor-pointer flex items-center justify-between w-full"
onSelect={() => {
setOpenProjectSelector(false)
setSelectedProjectRef(null)
setUsageFilter({ projectRef: null, branchRef: null })
}}
onClick={() => {
setOpenProjectSelector(false)
setSelectedProjectRef(null)
setUsageFilter({ projectRef: null, branchRef: null })
}}
>
All projects
@@ -230,6 +296,19 @@ export const Usage = () => {
</CommandGroup>
)}
/>
{isLoadingBranches && <ShimmeringLoader className="w-[180px] py-3.5" />}
{!isLoadingBranches && !!selectedProjectRef && (
<UsageBranchFilter
branchOptions={branchOptions}
projectRef={selectedProjectRef}
branchRef={selectedBranch?.project_ref ?? null}
onSelectBranch={(branchRef) =>
setUsageFilter({ projectRef: selectedProjectRef, branchRef })
}
/>
)}
</div>
<div className="flex items-center gap-2">
@@ -274,110 +353,129 @@ export const Usage = () => {
</ScaffoldContainer>
)}
{selectedProject ? (
{isProjectLookupBlocked && (
<ScaffoldContainer className="mt-5">
<AlertError subject="Failed to retrieve project" error={selectedProjectError} />
</ScaffoldContainer>
)}
{isErrorBranches && (
<ScaffoldContainer className="mt-5">
<AlertError subject="Failed to retrieve branches" error={branchesError} />
</ScaffoldContainer>
)}
{isResolvingBranch && (
<ScaffoldContainer className="mt-5">
<div role="status" aria-label="Loading branch usage">
<ShimmeringLoader />
</div>
</ScaffoldContainer>
)}
{isBranchUnavailable && (
<ScaffoldContainer className="mt-5">
<Admonition
type="default"
title="Usage filtered by project"
description={
<div>
You are currently viewing usage for the{' '}
<span className="font-medium text-foreground">
{selectedProject?.name || selectedProjectRef}
</span>{' '}
project. Supabase uses{' '}
<Link
href="/docs/guides/platform/billing-on-supabase#organization-based-billing"
target="_blank"
>
organization-level billing
</Link>{' '}
and quotas. For billing purposes, we sum up usage from all your projects. To view
your usage quota, set the project filter above back to "All Projects".
</div>
}
type="warning"
title="Branch unavailable"
description="The selected branch could not be found for this project. Showing usage for the parent project. Usage from deleted branches still counts toward the organization total."
/>
</ScaffoldContainer>
) : (
<ScaffoldContainer id="restriction" className="mt-5">
<Restriction />
</ScaffoldContainer>
)}
<TotalUsage
orgSlug={slug as string}
projectRef={selectedProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
/>
{canShowUsage && (
<>
{selectedProject ? (
<UsageFilterNotice
branchName={selectedBranch?.name}
hasBranches={branchOptions.length > 0}
onViewOrganizationUsage={() => setUsageFilter({ projectRef: null, branchRef: null })}
/>
) : (
<ScaffoldContainer id="restriction" className="mt-5">
<Restriction />
</ScaffoldContainer>
)}
{subscription?.plan.id !== 'free' && (
<Compute orgDailyStats={orgDailyStats} isLoadingOrgDailyStats={isLoadingOrgDailyStats} />
<TotalUsage
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
/>
{subscription?.plan.id !== 'free' && (
<Compute
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
)}
{subscription?.plan.id === 'platform' && (
<ActiveCompute
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
)}
<Egress
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
startDate={startDate}
endDate={endDate}
/>
<SizeAndCounts
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
startDate={startDate}
endDate={endDate}
/>
<Activity
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
<OrgLogUsage
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats || isLoadingSubscription}
/>
<Pipelines
orgSlug={slug as string}
projectRef={usageProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
</>
)}
{subscription?.plan.id === 'platform' && (
<ActiveCompute
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
)}
<Egress
orgSlug={slug as string}
projectRef={selectedProjectRef}
subscription={subscription}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
startDate={startDate}
endDate={endDate}
/>
<SizeAndCounts
orgSlug={slug as string}
projectRef={selectedProjectRef}
subscription={subscription}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
startDate={startDate}
endDate={endDate}
/>
<Activity
orgSlug={slug as string}
projectRef={selectedProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
<OrgLogUsage
orgSlug={slug as string}
projectRef={selectedProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats || isLoadingSubscription}
/>
<Pipelines
orgSlug={slug as string}
projectRef={selectedProjectRef}
subscription={subscription}
startDate={startDate}
endDate={endDate}
currentBillingCycleSelected={currentBillingCycleSelected}
orgDailyStats={orgDailyStats}
isLoadingOrgDailyStats={isLoadingOrgDailyStats}
/>
</>
)
}
@@ -1,8 +1,13 @@
import { describe, expect, it } from 'vitest'
import { dailyUsageToDataPoints } from './Usage.utils'
import {
dailyUsageToDataPoints,
getUsageBranchOptions,
resolveUsageProjectRef,
} from './Usage.utils'
import { PricingMetric } from '@/data/analytics/org-daily-stats-query'
import type { OrgDailyUsageResponse } from '@/data/analytics/org-daily-stats-query'
import { createTestBranch } from '@/tests/lib/branch-test-utils'
describe('dailyUsageToDataPoints', () => {
it('returns empty array when dailyUsage is undefined', () => {
@@ -249,3 +254,81 @@ describe('dailyUsageToDataPoints', () => {
})
})
})
describe('getUsageBranchOptions', () => {
it('returns no options when there are no branches', () => {
expect(getUsageBranchOptions(undefined)).toEqual([])
expect(getUsageBranchOptions([])).toEqual([])
})
it('returns no options when the project only has a main branch', () => {
const branches = [createTestBranch({ name: 'main', project_ref: 'parent', is_default: true })]
expect(getUsageBranchOptions(branches)).toEqual([])
})
it('puts the main branch first, then the newest branches', () => {
const branches = [
createTestBranch({
name: 'older',
project_ref: 'older-ref',
created_at: '2026-01-01T00:00:00Z',
}),
createTestBranch({ name: 'main', project_ref: 'parent', is_default: true }),
createTestBranch({
name: 'newer',
project_ref: 'newer-ref',
created_at: '2026-02-01T00:00:00Z',
}),
]
expect(getUsageBranchOptions(branches).map((branch) => branch.name)).toEqual([
'main',
'newer',
'older',
])
})
it('returns branches without a main branch', () => {
const branches = [
createTestBranch({ name: 'one', project_ref: 'one-ref' }),
createTestBranch({ name: 'two', project_ref: 'two-ref' }),
]
expect(getUsageBranchOptions(branches).map((branch) => branch.name)).toEqual(['one', 'two'])
})
it('returns a lone branch that is not the main branch', () => {
const branches = [createTestBranch({ name: 'only', project_ref: 'only-ref' })]
expect(getUsageBranchOptions(branches).map((branch) => branch.name)).toEqual(['only'])
})
})
describe('resolveUsageProjectRef', () => {
const branchOptions = [
createTestBranch({ name: 'main', project_ref: 'parent-ref', is_default: true }),
createTestBranch({ name: 'preview', project_ref: 'branch-ref' }),
]
it('returns null when no project is selected', () => {
expect(resolveUsageProjectRef(null, branchOptions, 'branch-ref')).toBe(null)
})
it('returns the selected branch ref', () => {
expect(resolveUsageProjectRef('parent-ref', branchOptions, 'branch-ref')).toBe('branch-ref')
})
it('falls back to the project when the branch ref is not one of its branches', () => {
expect(resolveUsageProjectRef('parent-ref', branchOptions, 'other-org-branch-ref')).toBe(
'parent-ref'
)
})
it('falls back to the project while its branches are still unknown', () => {
expect(resolveUsageProjectRef('parent-ref', [], 'branch-ref')).toBe('parent-ref')
})
it('rejects a matching branch ref belonging to another parent', () => {
expect(resolveUsageProjectRef('other-parent', branchOptions, 'branch-ref')).toBe('other-parent')
})
})
@@ -3,6 +3,7 @@ import { groupBy } from 'lodash'
import { DataPoint } from '@/data/analytics/constants'
import type { OrgDailyUsageResponse, PricingMetric } from '@/data/analytics/org-daily-stats-query'
import type { Branch } from '@/data/branches/branches-query'
import type { OrgSubscription } from '@/data/subscriptions/types'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
@@ -18,6 +19,32 @@ export const generateUsageData = (attribute: string, days: number): DataPoint[]
})
}
export function getUsageBranchOptions(branches: Branch[] | undefined) {
const previewBranches = (branches ?? [])
.filter((branch) => !branch.is_default)
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
if (previewBranches.length === 0) return []
const mainBranch = branches?.find((branch) => branch.is_default)
return mainBranch ? [mainBranch, ...previewBranches] : previewBranches
}
export function resolveUsageProjectRef(
selectedProjectRef: string | null,
branchOptions: Branch[],
selectedBranchRef: string | null
) {
if (!selectedProjectRef) return null
const selectedBranch = branchOptions.find(
(branch) =>
branch.project_ref === selectedBranchRef && branch.parent_project_ref === selectedProjectRef
)
return selectedBranch?.project_ref ?? selectedProjectRef
}
export function useGetUpgradeUrl(slug: string, subscription?: OrgSubscription, source?: string) {
const { billingAll } = useIsFeatureEnabled(['billing:all'])
@@ -0,0 +1,203 @@
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { UsageBranchFilter } from './UsageBranchFilter'
import { createTestBranch } from '@/tests/lib/branch-test-utils'
import { customRender } from '@/tests/lib/custom-render'
const mainBranch = createTestBranch({
id: 'main-id',
name: 'main',
project_ref: 'parent-ref',
is_default: true,
})
const previewBranch = createTestBranch({ name: 'marvo-app-dev', project_ref: 'branch-ref' })
describe('UsageBranchFilter', () => {
it('renders nothing when the project has no branches to filter by', () => {
customRender(
<UsageBranchFilter
branchOptions={[]}
projectRef="parent-ref"
branchRef={null}
onSelectBranch={vi.fn()}
/>
)
expect(screen.queryByLabelText('Filter by branch')).not.toBeInTheDocument()
})
it('selects a branch by its own project ref', async () => {
const onSelectBranch = vi.fn()
customRender(
<UsageBranchFilter
branchOptions={[mainBranch, previewBranch]}
projectRef="parent-ref"
branchRef={null}
onSelectBranch={onSelectBranch}
/>
)
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent('main')
await userEvent.click(screen.getByLabelText('Filter by branch'))
await userEvent.click(await screen.findByRole('option', { name: 'marvo-app-dev' }))
expect(onSelectBranch).toHaveBeenCalledWith('branch-ref')
})
it('clears the branch filter when the main branch is selected', async () => {
const onSelectBranch = vi.fn()
customRender(
<UsageBranchFilter
branchOptions={[mainBranch, previewBranch]}
projectRef="parent-ref"
branchRef="branch-ref"
onSelectBranch={onSelectBranch}
/>
)
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent('marvo-app-dev')
await userEvent.click(screen.getByLabelText('Filter by branch'))
expect(await screen.findAllByRole('option')).toHaveLength(2)
await userEvent.click(await screen.findByRole('option', { name: 'main' }))
expect(onSelectBranch).toHaveBeenCalledWith(null)
})
it.each([
{ branchOptions: [mainBranch, previewBranch], label: 'main' },
{ branchOptions: [previewBranch], label: 'Main branch' },
])('falls back to $label when the selected ref is absent', ({ branchOptions, label }) => {
customRender(
<UsageBranchFilter
branchOptions={branchOptions}
projectRef="parent-ref"
branchRef="deleted-branch-ref"
onSelectBranch={vi.fn()}
/>
)
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(label)
})
it('returns to the parent when the options contain only a preview branch', async () => {
const onSelectBranch = vi.fn()
customRender(
<UsageBranchFilter
branchOptions={[previewBranch]}
projectRef="parent-ref"
branchRef="branch-ref"
onSelectBranch={onSelectBranch}
/>
)
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent('marvo-app-dev')
await userEvent.click(screen.getByLabelText('Filter by branch'))
await userEvent.click(await screen.findByRole('option', { name: 'Main branch' }))
expect(onSelectBranch).toHaveBeenCalledWith(null)
})
it.each(['release-candidate-199', 'preview-ref-199'])(
'finds a branch among 200 options by searching for %s and selects its project ref',
async (search) => {
const user = userEvent.setup()
const onSelectBranch = vi.fn()
const branches = Array.from({ length: 200 }, (_, index) =>
createTestBranch({
id: `branch-id-${index}`,
name: `release-candidate-${index}`,
project_ref: `preview-ref-${index}`,
})
)
customRender(
<UsageBranchFilter
branchOptions={branches}
projectRef="parent-ref"
branchRef={null}
onSelectBranch={onSelectBranch}
/>
)
await user.click(screen.getByLabelText('Filter by branch'))
await user.click(await screen.findByPlaceholderText('Find branch...'))
await user.paste(search)
expect(screen.getAllByRole('option').length).toBeLessThan(200)
expect(screen.getAllByRole('option')[0]).toHaveTextContent('release-candidate-199')
await user.click(screen.getByRole('option', { name: 'release-candidate-199' }))
expect(onSelectBranch).toHaveBeenCalledExactlyOnceWith('preview-ref-199')
expect(screen.queryByPlaceholderText('Find branch...')).not.toBeInTheDocument()
}
)
it('shows an empty state for an unmatched search and restores options when cleared', async () => {
const user = userEvent.setup()
const onSelectBranch = vi.fn()
customRender(
<UsageBranchFilter
branchOptions={[mainBranch, previewBranch]}
projectRef="parent-ref"
branchRef={null}
onSelectBranch={onSelectBranch}
/>
)
await user.click(screen.getByLabelText('Filter by branch'))
const search = await screen.findByPlaceholderText('Find branch...')
await user.type(search, 'nonexistent-branch')
expect(await screen.findByText('No branches found')).toBeInTheDocument()
expect(screen.queryAllByRole('option')).toHaveLength(0)
expect(onSelectBranch).not.toHaveBeenCalled()
await user.clear(search)
expect(screen.getAllByRole('option')).toHaveLength(2)
expect(screen.queryByText('No branches found')).not.toBeInTheDocument()
})
it('supports keyboard selection and Escape clears search before dismissing', async () => {
const user = userEvent.setup()
const onSelectBranch = vi.fn()
customRender(
<UsageBranchFilter
branchOptions={[mainBranch, previewBranch]}
projectRef="parent-ref"
branchRef={null}
onSelectBranch={onSelectBranch}
/>
)
await user.tab()
expect(screen.getByLabelText('Filter by branch')).toHaveFocus()
await user.keyboard('{Enter}')
expect(await screen.findByPlaceholderText('Find branch...')).toHaveFocus()
await user.keyboard('marvo{ArrowDown}{Enter}')
expect(onSelectBranch).toHaveBeenCalledExactlyOnceWith('branch-ref')
expect(screen.queryByPlaceholderText('Find branch...')).not.toBeInTheDocument()
expect(screen.getByLabelText('Filter by branch')).toHaveFocus()
await user.keyboard('{Enter}')
expect(await screen.findByPlaceholderText('Find branch...')).toHaveFocus()
await user.keyboard('main{Escape}')
expect(screen.getByPlaceholderText('Find branch...')).toHaveValue('')
expect(screen.getByPlaceholderText('Find branch...')).toHaveFocus()
expect(screen.getAllByRole('option')).toHaveLength(2)
expect(onSelectBranch).toHaveBeenCalledTimes(1)
await user.keyboard('{Escape}')
expect(screen.queryByPlaceholderText('Find branch...')).not.toBeInTheDocument()
expect(screen.getByLabelText('Filter by branch')).toHaveFocus()
expect(onSelectBranch).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,116 @@
import { CheckIcon, ChevronDownIcon } from 'lucide-react'
import { useId, useState } from 'react'
import {
Button,
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
Popover,
PopoverContent,
PopoverTrigger,
} from 'ui'
import type { Branch } from '@/data/branches/branches-query'
import { onSearchInputEscape } from '@/lib/keyboard'
export interface UsageBranchFilterProps {
branchOptions: Branch[]
projectRef: string
branchRef: string | null
onSelectBranch: (branchRef: string | null) => void
}
export const UsageBranchFilter = ({
branchOptions,
projectRef,
branchRef,
onSelectBranch,
}: UsageBranchFilterProps) => {
const [isOpen, setIsOpen] = useState(false)
const [search, setSearch] = useState('')
const listboxId = useId()
if (branchOptions.length === 0) return null
const mainBranch = branchOptions.find((branch) => branch.project_ref === projectRef)
const selectedRef = branchOptions.some((branch) => branch.project_ref === branchRef)
? branchRef
: projectRef
const options = [
{ project_ref: projectRef, name: mainBranch?.name ?? 'Main branch' },
...branchOptions.filter((branch) => branch.project_ref !== projectRef),
]
const selectedBranch = options.find((branch) => branch.project_ref === selectedRef)
return (
<Popover
open={isOpen}
onOpenChange={(open) => {
setIsOpen(open)
setSearch('')
}}
>
<PopoverTrigger asChild>
<Button
role="combobox"
size="tiny"
className="justify-between w-[180px]"
aria-label="Filter by branch"
aria-expanded={isOpen}
aria-controls={listboxId}
iconRight={<ChevronDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />}
>
<span className="truncate">{selectedBranch?.name}</span>
</Button>
</PopoverTrigger>
<PopoverContent
className="p-0"
side="bottom"
align="start"
onEscapeKeyDown={(event) => {
if (search.length > 0) event.preventDefault()
}}
>
<Command>
<CommandInput
showResetIcon
value={search}
onValueChange={setSearch}
placeholder="Find branch..."
handleReset={() => setSearch('')}
onKeyDown={onSearchInputEscape(search, setSearch)}
className="text-base sm:text-sm"
/>
<CommandList id={listboxId} className="max-h-[300px] overflow-y-auto overflow-x-hidden">
<CommandEmpty>No branches found</CommandEmpty>
<CommandGroup>
{options.map((branch) => (
<CommandItem
key={branch.project_ref}
value={branch.project_ref}
keywords={[branch.name]}
className="cursor-pointer w-full"
onSelect={() => {
onSelectBranch(branch.project_ref === projectRef ? null : branch.project_ref)
setIsOpen(false)
setSearch('')
}}
>
<div className="w-full flex items-center justify-between gap-x-2">
<span className="truncate">{branch.name}</span>
{branch.project_ref === selectedRef && (
<CheckIcon size={16} className="shrink-0" />
)}
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,58 @@
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { UsageFilterNotice } from './UsageFilterNotice'
import { customRender } from '@/tests/lib/custom-render'
describe('UsageFilterNotice', () => {
it.each([
{ branchName: 'dev-test', hasBranches: true, text: 'dev-test branch only.' },
{
branchName: undefined,
hasBranches: true,
text: 'Main branch only. Other branches are tracked separately.',
},
{ branchName: undefined, hasBranches: false, text: 'This project only.' },
])('shows "$text" for the selected scope', ({ branchName, hasBranches, text }) => {
customRender(
<UsageFilterNotice
branchName={branchName}
hasBranches={hasBranches}
onViewOrganizationUsage={vi.fn()}
/>
)
expect(screen.getByText(text)).toBeInTheDocument()
})
it('discloses organization totals on keyboard focus even without live branches', async () => {
const user = userEvent.setup()
customRender(<UsageFilterNotice hasBranches={false} onViewOrganizationUsage={vi.fn()} />)
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()
await user.tab()
await user.tab()
expect(screen.getByRole('button', { name: 'About usage totals' })).toHaveFocus()
expect(await screen.findByRole('tooltip')).toHaveTextContent(
'Billing and quotas use totals from all projects and branches, including deleted branches that are no longer selectable.'
)
})
it('requests organization totals when the action is clicked', async () => {
const user = userEvent.setup()
const onViewOrganizationUsage = vi.fn()
customRender(
<UsageFilterNotice
branchName="dev-test"
hasBranches
onViewOrganizationUsage={onViewOrganizationUsage}
/>
)
await user.click(screen.getByRole('button', { name: 'View organization total' }))
expect(onViewOrganizationUsage).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,48 @@
import { InfoIcon } from 'lucide-react'
import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { ScaffoldContainer } from '@/components/layouts/Scaffold'
export interface UsageFilterNoticeProps {
branchName?: string
hasBranches: boolean
onViewOrganizationUsage: () => void
}
export const UsageFilterNotice = ({
branchName,
hasBranches,
onViewOrganizationUsage,
}: UsageFilterNoticeProps) => {
return (
<ScaffoldContainer className="mt-5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-foreground-light">
<p>
{branchName && `${branchName} branch only.`}
{!branchName && hasBranches && 'Main branch only. Other branches are tracked separately.'}
{!branchName && !hasBranches && 'This project only.'}
</p>
<div className="flex items-center gap-x-2">
<Button variant="text" size="tiny" onClick={onViewOrganizationUsage}>
View organization total
</Button>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="text"
size="tiny"
className="px-1"
aria-label="About usage totals"
icon={<InfoIcon size={14} />}
/>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
Billing and quotas use totals from all projects and branches, including deleted
branches that are no longer selectable.
</TooltipContent>
</Tooltip>
</div>
</div>
</ScaffoldContainer>
)
}
@@ -0,0 +1,140 @@
import { screen } from '@testing-library/react'
import { HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import type { CategoryAttribute } from '../Usage.constants'
import { DiskUsage } from './DiskUsage'
import type { OrgProject, OrgProjectsResponse } from '@/data/projects/org-projects-infinite-query'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
const attribute: CategoryAttribute = {
anchor: 'diskSize',
key: 'diskSize',
attributes: [],
name: 'Disk size',
unit: 'bytes',
description: 'Provisioned disk size',
chartDescription: '',
}
const branch: OrgProject = {
cloud_provider: 'AWS',
databases: [
{
cloud_provider: 'AWS',
disk_volume_size_gb: 8,
identifier: 'branch-ref',
region: 'us-east-1',
status: 'ACTIVE_HEALTHY',
type: 'PRIMARY',
},
],
inserted_at: '2026-01-01T00:00:00Z',
integration_source: null,
is_branch: true,
name: 'Preview branch',
ref: 'branch-ref',
region: 'us-east-1',
status: 'ACTIVE_HEALTHY',
}
const firstPage = Array.from({ length: 96 }, (_, index) => ({
...branch,
ref: `project-${index}`,
name: `Project ${index}`,
is_branch: false,
}))
const renderDiskUsage = (projectRef?: string) =>
customRender(
<DiskUsage
slug="test-org"
projectRef={projectRef}
attribute={attribute}
currentBillingCycleSelected
/>,
{ profileContext: createMockProfileContext() }
)
describe('DiskUsage', () => {
it('finds a selected branch beyond the first page and stops once found', async () => {
const offsets: number[] = []
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: ({ request }) => {
const offset = Number(new URL(request.url).searchParams.get('offset'))
offsets.push(offset)
return HttpResponse.json<OrgProjectsResponse>({
pagination: { count: 250, limit: 96, offset },
projects: offset === 0 ? firstPage : [branch],
})
},
})
renderDiskUsage('branch-ref')
expect(await screen.findByText('Preview branch')).toBeInTheDocument()
expect(screen.getByText('8 GB Disk provisioned')).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Manage Disk' })).toHaveAttribute(
'href',
'/project/branch-ref/settings/infrastructure'
)
expect(screen.queryByText('No active projects')).not.toBeInTheDocument()
expect(offsets).toEqual([0, 96])
})
it.each([undefined, 'project-0'])(
'does not paginate when the filter is %s',
async (projectRef) => {
const offsets: number[] = []
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: ({ request }) => {
const offset = Number(new URL(request.url).searchParams.get('offset'))
offsets.push(offset)
return HttpResponse.json<OrgProjectsResponse>({
pagination: { count: 250, limit: 96, offset },
projects: firstPage,
})
},
})
renderDiskUsage(projectRef)
expect(await screen.findByText('Project 0')).toBeInTheDocument()
expect(offsets).toEqual([0])
}
)
it('shows an error when the next page fails instead of claiming there are no projects', async () => {
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Project not found' }, { status: 404 }),
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: ({ request }) => {
const offset = Number(new URL(request.url).searchParams.get('offset'))
if (offset > 0) {
return HttpResponse.json<APIErrorBody>({ message: 'Page unavailable' }, { status: 500 })
}
return HttpResponse.json<OrgProjectsResponse>({
pagination: { count: 97, limit: 96, offset },
projects: firstPage,
})
},
})
renderDiskUsage('branch-ref')
expect(await screen.findByText('Failed to retrieve usage data')).toBeInTheDocument()
expect(screen.queryByText('No active projects')).not.toBeInTheDocument()
})
})
@@ -1,5 +1,5 @@
import Link from 'next/link'
import { useMemo } from 'react'
import { useEffect, useMemo } from 'react'
import { Alert, AlertDescription, AlertTitle, Button, cn, CriticalIcon } from 'ui'
import { InfoTooltip } from 'ui-patterns/info-tooltip'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
@@ -33,14 +33,22 @@ export const DiskUsage = ({
usage,
currentBillingCycleSelected,
}: DiskUsageProps) => {
const {
data,
isError,
isPending: isLoading,
isSuccess,
error,
} = useOrgProjectsInfiniteQuery({ slug }, { enabled: currentBillingCycleSelected })
const { data, isError, isPending, isFetching, isSuccess, error, hasNextPage, fetchNextPage } =
useOrgProjectsInfiniteQuery({ slug }, { enabled: currentBillingCycleSelected })
const projects = useMemo(() => data?.pages.flatMap((page) => page.projects) || [], [data?.pages])
const shouldFindSelectedProject =
currentBillingCycleSelected &&
!!projectRef &&
!projects.some((project) => project.ref === projectRef) &&
hasNextPage &&
!isError
const isLoading = isPending || shouldFindSelectedProject
useEffect(() => {
if (shouldFindSelectedProject && !isFetching) {
void fetchNextPage()
}
}, [shouldFindSelectedProject, isFetching, fetchNextPage])
const relevantProjects = useMemo(() => {
return isSuccess
@@ -50,12 +58,16 @@ export const DiskUsage = ({
const isBranchExceedingFreeQuota =
project.is_branch && project.databases.some((db) => (db.disk_volume_size_gb ?? 8) > 8)
const isFilteredBranch = project.is_branch && project.ref === projectRef
const isActiveProject = project.status !== PROJECT_STATUS.INACTIVE
const isHostedOnAws = project.databases.every((db) => db.cloud_provider === 'AWS')
return (
(!project.is_branch || isBranchExceedingFreeQuota) && isActiveProject && isHostedOnAws
(!project.is_branch || isBranchExceedingFreeQuota || isFilteredBranch) &&
isActiveProject &&
isHostedOnAws
)
})
.filter((it) => it.ref === projectRef || !projectRef)
@@ -91,7 +103,7 @@ export const DiskUsage = ({
</div>
)}
{isError && <AlertError subject="Failed to retrieve usage data" error={error} />}
{isSuccess && (
{isSuccess && !isLoading && (
<div className="space-y-4">
{currentBillingCycleSelected &&
subscription?.usage_billing_enabled === false &&
@@ -0,0 +1,15 @@
import type { Branch } from '@/data/branches/branches-query'
export const createTestBranch = (overrides: Partial<Branch> = {}): Branch => ({
created_at: '2026-01-01T00:00:00Z',
id: 'branch-id',
is_default: false,
name: 'branch',
parent_project_ref: 'parent-ref',
persistent: false,
project_ref: 'branch-ref',
status: 'MIGRATIONS_PASSED',
updated_at: '2026-01-01T00:00:00Z',
with_data: false,
...overrides,
})