Files
supabase-vercel-tedd[bot]andIvan Vasilov 31f68587f6 feat(studio): track remaining usage on project home (#54143)
## Problem

Project home tracked most interactions, but not which credential people
copy from the "Copy" popover, or how often they use the custom report
and notebooks beyond adding blocks. Opening the Connect sheet from the
popover's "Get Connected" button also reported a stale
`connect_sheet_opened` source, because the popover never set one.

## Solution

Project home gets three new events: `home_project_credential_copied`
(with a `credentialType` enum), `home_custom_report_refresh_clicked`,
and `home_notebook_action_clicked` (`action: 'create' | 'analyze'`).
"Get Connected" in the popover now sets a new `home_popover` Connect
sheet source. The compute and GitHub stats now send
`home_activity_stat_clicked` as well, with two new `stat_type` values.
Every event fires from its click handler with a typed `track()` call,
and none sends the copied value or any user-defined name. This follows
the telemetry standards, so no `data-attr` attributes are added.

## How to verify

1. On a project's home page, open the "Copy" popover and copy each item.
Each copy sends one `home_project_credential_copied` event, with
`credentialType` set to `project_url`, `publishable_key`,
`direct_connection_string`, or `cli_setup`. No event contains the copied
value.
2. In the same popover, click "Get Connected". The Connect sheet opens
and sends `connect_sheet_opened` with `source: 'home_popover'`. Opening
it from the header button afterwards still sends `source:
'header_button'`.
3. Click the "Compute size" stat. It sends `home_activity_stat_clicked`
with `stat_type: 'compute'` and no `stat_value`.
4. Click the "GitHub" stat. It sends `home_activity_stat_clicked` with
`stat_type: 'github'`, and `stat_value` is 1 when a repository is
connected and 0 when none is.
5. With the custom report section shown, click "Refresh report". It
sends one `home_custom_report_refresh_clicked` event.
6. With the Notebooks section shown, click "New notebook" (or "Create
your first notebook" when there are none). It sends
`home_notebook_action_clicked` with `action: 'create'`. Click "Analyze"
on a notebook with cells: it sends `action: 'analyze'`.

## Checks

Ran `tsc --noEmit` in `apps/studio` and `packages/common`, `eslint` and
the type-aware `eslint.type-checks.config.cjs` lint on the changed
Studio files, `oxfmt --check` on every changed file, and `vitest run`
for `ProjectConnectionPopover.platform.test.tsx` and
`ActivityStats.test.tsx`.

## Checklist

- [x] I have read the [Contributing
Guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] I have checked that the change works in the preview deployment

## Feedback for Tedd

To ask Tedd for a change to this PR, reply in Tedd's session on
[FE-5026](https://linear.app/supabase/issue/FE-5026/track-usage-on-project-home-gaps-only).
Tedd doesn't read comments on this PR.

---------

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2026-12-01 11:54:29 +01:00

292 lines
10 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { ArchiveIcon, CpuIcon, DatabaseIcon, GitBranchIcon } from 'lucide-react'
import { useMemo } from 'react'
import { cn, GithubIcon, Skeleton } from 'ui'
import { TimestampInfo } from 'ui-patterns/TimestampInfo'
import { HighAvailabilityBadge } from './HighAvailabilityBadge'
import { ServiceStatus } from './ServiceStatus'
import { getInfrastructurePath } from '@/components/interfaces/Settings/Infrastructure/Infrastructure.utils'
import { ComputeBadgeWrapper } from '@/components/ui/ComputeBadgeWrapper'
import { DisableInteraction } from '@/components/ui/DisableInteraction'
import { SingleStat } from '@/components/ui/SingleStat'
import { branchesQueryOptions } from '@/data/branches/branches-query'
import { useBackupsQuery } from '@/data/database/backups-query'
import { DatabaseMigration, useMigrationsQuery } from '@/data/database/migrations-query'
import { useGitHubConnectionsQuery } from '@/data/integrations/github-connections-query'
import { useHighAvailability } from '@/hooks/misc/useHighAvailability'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { PROJECT_STATUS } from '@/lib/constants'
import { useGrant } from '@/lib/grants'
import { EMPTY_ARR } from '@/lib/void'
interface BranchStatValueProps {
currentBranch?: { created_at?: string }
isDefaultProject: boolean
isError: boolean
isHighAvailability: boolean
isLoading: boolean
latestNonDefaultBranch?: { name?: string }
}
export const BranchStatValue = ({
currentBranch,
isDefaultProject,
isError,
isHighAvailability,
isLoading,
latestNonDefaultBranch,
}: BranchStatValueProps) => {
if (isHighAvailability) {
return <p className="text-foreground-lighter">Unavailable</p>
}
if (isLoading) {
return <Skeleton className="h-6 w-24" />
}
if (isError) {
return <p className="text-foreground-lighter">Unable to load</p>
}
if (isDefaultProject) {
return (
<p
className={cn('truncate min-w-0', !latestNonDefaultBranch && 'text-foreground-lighter')}
title={latestNonDefaultBranch?.name ?? 'No branches'}
>
{latestNonDefaultBranch?.name ?? 'No branches'}
</p>
)
}
if (currentBranch?.created_at) {
return (
<TimestampInfo
className="text-base"
label={dayjs(currentBranch.created_at).fromNow()}
utcTimestamp={currentBranch.created_at}
/>
)
}
return <p className="text-foreground-lighter">Unknown</p>
}
export const ActivityStats = () => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const { isHighAvailability } = useHighAvailability()
const { data: organization } = useSelectedOrganizationQuery()
const parentProjectRef = project?.parent_project_ref ?? project?.ref
const branchesGrant = useGrant('GET /v1/projects/{ref}/branches', {
projectRef: parentProjectRef,
})
const {
data: branchesData,
isPending: isPendingBranches,
isError: isBranchesQueryError,
} = useQuery(
branchesQueryOptions(
{ projectRef: parentProjectRef, grant: branchesGrant.grant },
{ enabled: !isHighAvailability }
)
)
const isLoadingBranches =
branchesGrant.status === 'loading' || (branchesGrant.status === 'granted' && isPendingBranches)
const isBranchesError = isBranchesQueryError || branchesGrant.status === 'error'
const isDefaultProject = project?.parent_project_ref === undefined
const currentBranch = useMemo(
() => (branchesData ?? []).find((b) => b.project_ref === ref),
[branchesData, ref]
)
const latestNonDefaultBranch = useMemo(() => {
const list = (branchesData ?? []).filter((b) => !b.is_default)
if (list.length === 0) return undefined
return list
.slice()
.sort(
(a, b) =>
new Date(b.created_at ?? b.updated_at).valueOf() -
new Date(a.created_at ?? a.updated_at).valueOf()
)[0]
}, [branchesData])
const { data: migrationsData = EMPTY_ARR, isPending: isLoadingMigrations } = useMigrationsQuery({
projectRef: project?.ref,
projectStatus: project?.status,
connectionString: project?.connectionString,
})
const latestMigration = useMemo<DatabaseMigration | undefined>(
() => migrationsData[0],
[migrationsData]
)
const migrationLabelText =
migrationsData.length === 0 ? 'No migrations' : (latestMigration?.name ?? 'Unknown')
const { data: backupsData, isPending: isLoadingBackups } = useBackupsQuery({
projectRef: project?.ref,
projectStatus: project?.status,
})
const latestBackup = useMemo(() => {
const list = backupsData?.backups ?? []
if (list.length === 0) return undefined
return list
.slice()
.sort((a, b) => new Date(b.inserted_at).valueOf() - new Date(a.inserted_at).valueOf())[0]
}, [backupsData])
const {
data: githubConnections,
isPending: isLoadingGithubConnections,
isSuccess: isGithubConnectionsSuccess,
} = useGitHubConnectionsQuery(
{ organizationId: organization?.id },
{ enabled: !!organization?.id }
)
const githubConnection = githubConnections?.find(
(connection) => connection.project.ref === parentProjectRef
)
const isProjectComingUp = [PROJECT_STATUS.COMING_UP, PROJECT_STATUS.UNKNOWN].includes(
project?.status ?? PROJECT_STATUS.UNKNOWN
)
const githubLabelText = githubConnection?.repository.name
? githubConnection.repository.name
: isProjectComingUp
? 'Waiting for project...'
: 'No repository connected'
const integrationsPath = parentProjectRef
? `/project/${parentProjectRef}/settings/integrations`
: undefined
return (
<div className="@container">
<div className="grid grid-cols-1 @md:grid-cols-2 gap-2 @md:gap-6 flex-wrap">
<ServiceStatus />
<SingleStat
href={getInfrastructurePath(ref)}
icon={<CpuIcon size={18} strokeWidth={1.5} className="text-foreground" />}
label={<span>Compute size</span>}
trackingProperties={{ stat_type: 'compute' }}
value={
<div className="flex items-center gap-x-2 gap-y-1 flex-wrap">
{project?.infra_compute_size ? (
<ComputeBadgeWrapper
projectRef={project?.ref}
slug={organization?.slug}
cloudProvider={project?.cloud_provider}
computeSize={project.infra_compute_size}
/>
) : (
<p className="text-foreground-lighter">Unknown</p>
)}
{project?.high_availability && <HighAvailabilityBadge />}
</div>
}
/>
<SingleStat
href={integrationsPath}
icon={<GithubIcon size={18} strokeWidth={1.5} className="text-foreground" />}
label={<span>GitHub</span>}
trackingProperties={
isGithubConnectionsSuccess
? { stat_type: 'github', stat_value: githubConnection ? 1 : 0 }
: undefined
}
value={
isLoadingGithubConnections ? (
<Skeleton className="h-6 w-24" />
) : (
<p
className={cn('truncate min-w-0', !githubConnection && 'text-foreground-lighter')}
title={githubLabelText}
>
{githubLabelText}
</p>
)
}
/>
<DisableInteraction disabled={isHighAvailability} aria-disabled={isHighAvailability}>
<SingleStat
href={isHighAvailability ? undefined : `/project/${ref}/branches`}
icon={<GitBranchIcon size={18} strokeWidth={1.5} className="text-foreground" />}
label={<span>{isDefaultProject ? 'Recent branch' : 'Branch Created'}</span>}
trackingProperties={{
stat_type: 'branches',
stat_value: branchesData?.length ?? 0,
}}
value={
<BranchStatValue
currentBranch={currentBranch}
isDefaultProject={isDefaultProject}
isError={isBranchesError}
isHighAvailability={isHighAvailability}
isLoading={isLoadingBranches}
latestNonDefaultBranch={latestNonDefaultBranch}
/>
}
/>
</DisableInteraction>
<SingleStat
href={`/project/${ref}/database/migrations`}
icon={<DatabaseIcon size={18} strokeWidth={1.5} className="text-foreground" />}
label={<span>Last migration</span>}
trackingProperties={{
stat_type: 'migrations',
stat_value: migrationsData?.length ?? 0,
}}
value={
isLoadingMigrations ? (
<Skeleton className="h-6 w-24" />
) : (
<p
className={cn(
'truncate min-w-0',
!!latestMigration ? 'text-foreground' : 'text-foreground-lighter'
)}
title={migrationLabelText}
>
{migrationLabelText}
</p>
)
}
/>
<SingleStat
href={`/project/${ref}/database/backups/scheduled`}
icon={<ArchiveIcon size={18} strokeWidth={1.5} className="text-foreground" />}
label={<span>Last backup</span>}
trackingProperties={{
stat_type: 'backups',
stat_value: backupsData?.backups?.length ?? 0,
}}
value={
isLoadingBackups ? (
<Skeleton className="h-6 w-24" />
) : backupsData?.pitr_enabled ? (
<p>PITR enabled</p>
) : latestBackup ? (
<TimestampInfo
className="text-base"
displayAs="utc"
label={dayjs(latestBackup.inserted_at).fromNow()}
utcTimestamp={latestBackup.inserted_at}
/>
) : (
<p className="text-foreground-lighter">No backups</p>
)
}
/>
</div>
</div>
)
}