ronantakizawa/codereview-bench huggingface dataset:
Repository: supabase/supabase
File: apps/studio/data/platform/incident-status-utils.ts (TypeScript)

Code before:
import dayjs from 'dayjs'

import type { IncidentInfo } from './incident-status-query'

/**
 * Status priority order: higher priority = more urgent
 * Used to determine which incident's status should be displayed
 */
const STATUS_PRIORITY: Record<string, number> = {
  investigating: 4,
  identified: 3,
  monitoring: 2,
  resolved: 1,
}

/**
 * Determines the most representative status when multiple incidents exist.
 * Returns the highest priority status (most urgent) among all incidents.
 *
 * @param incidents Array of incidents to analyze
 * @returns The highest priority status string
 */
export function getOverallStatus(incidents: Array<{ status: string }>): string {
  if (incidents.length === 0) return 'investigating'
  if (incidents.length === 1) return incidents[0].status

  // Find the highest priority status among all incidents
  const statuses = incidents.map((inc) => inc.status)
  const sortedByPriority = statuses.sort(
    (a, b) => (STATUS_PRIORITY[b] || 0) - (STATUS_PRIORITY[a] || 0)
  )

  return sortedByPriority[0] || 'investigating'
}

/**
 * Gets the most recent incident (by active_since) for display purposes.
 * This is used for the title/name, not for status determination.
 *

Review comment (suggestion):
Please confirm this is the correct order of priority and full list, with `4` being the highest priority.

Code after:
import type { IncidentInfo } from 'lib/api/incident-status'

export type IncidentImpact = 'critical' | 'major' | 'maintenance' | 'minor' | 'none'

/**
 * Impact priority order: higher priority = more severe
 */
const IMPACT_PRIORITY: Record<IncidentImpact, number> = {
  critical: 4,
  major: 3,
  maintenance: 2,
  minor: 1,
  none: 0,
}

const isIncidentImpact = (impact: string): impact is IncidentImpact => {
  return Object.keys(IMPACT_PRIORITY).includes(impact)
}

export type IncidentStatus = 'investigating' | 'identified' | 'monitoring' | 'resolved'

/**
 * Status priority order: higher priority = more urgent
 */
const STATUS_PRIORITY: Record<IncidentStatus, number> = {
  investigating: 4,
  identified: 3,
  monitoring: 2,
  resolved: 1,
}

const isIncidentStatus = (status: string): status is IncidentStatus => {
  return Object.keys(STATUS_PRIORITY).includes(status)
}

/**
 * Sorts incidents by priority: first by impact, then by date, then by status.
 *
 * @param incidents Array of incidents to sort
Repository: supabase/supabase
File: apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx (TypeScript)

Code before:

  const [isExpanded, setIsExpanded] = useState(false)

  const handleExplainQuery = () => {
    if (!selectedRow?.query) return

    const { query, prompt } = buildQueryExplanationPrompt(selectedRow)

    openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
    aiSnap.newChat({
      sqlSnippets: [
        {
          label: 'Query',
          content: query,
        },
      ],
      initialMessage: prompt,
    })

    sendEvent({
      action: 'query_performance_ai_explanation_clicked',
      groups: {
        project: ref ?? 'Unknown',
        organization: org?.slug ?? 'Unknown',
      },
    })

    // Close the query detail panel since we need to see the AI assistant panel
    onClose?.()
  }

  return (
    <QueryPanelContainer>
      <QueryPanelSection className="pt-2 border-b relative">
        <div className="flex items-center justify-between mb-4">
          <h4>Query pattern</h4>
          <Button
            type="default"
            size="tiny"
            icon={<AiIconAnimation size={14} />}
            onClick={handleExplainQuery}
          >
            Explain with AI
          </Button>
        </div>
        <div
          className={cn(
            'overflow-hidden pb-0 z-0 relative transition-all duration-300',
            isExpanded ? 'h-[348px]' : 'h-[120px]'
          )}
        >

Review comment (performance):
Recommend using `useTrack()` here instead. It passes project and org groups and falls back to `undefined` instead of `"Unknown"` which is what we're trying to move toward.


```suggestion
    const track = useTrack()
    track('query_performance_ai_explanation_clicked')
```

Code after:

  const handleExplainQuery = () => {
    if (!selectedRow?.query) return

    const { query, prompt } = buildQueryExplanationPrompt(selectedRow)

    openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
    aiSnap.newChat({
      sqlSnippets: [
        {
          label: 'Query',
          content: query,
        },
      ],
      initialMessage: prompt,
    })

    track('query_performance_explain_with_ai_button_clicked')

    // Close the query detail panel since we need to see the AI assistant panel
    onClose?.()
  }

  return (
    <QueryPanelContainer>
      <QueryPanelSection className="pt-2 border-b relative">
        <div className="flex items-center justify-between mb-4">
          <h4>Query pattern</h4>
          {showExplainWithAiInQueryPerformance && (
            <Button
              type="default"
              size="tiny"
              icon={<AiIconAnimation size={14} />}
              onClick={handleExplainQuery}
            >
              Explain with AI
            </Button>
          )}
        </div>
        <div
          className={cn(
            'overflow-hidden pb-0 z-0 relative transition-all duration-300',
            isExpanded ? 'h-[348px]' : 'h-[120px]'
          )}
        >
          <SqlMonacoBlock
            value={query}
            height={322}
            lineNumbers="off"
            wrapperClassName={cn('pl-3 bg-surface-100', !isExpanded && 'pointer-events-none')}
          />
Repository: supabase/supabase
File: packages/common/telemetry-constants.ts (TypeScript)

Code before:
     */
    advisorCategory?: AdvisorCategory
    /**
     * Specific advisor type/name
     */
    advisorType?: string
    /**
     * Severity level of the advisor (only for lints)
     */
    advisorLevel?: AdvisorLevel
    /**
     * Number of issues found (only included when origin is 'homepage')
     */
    issuesCount?: number
  }
  groups: TelemetryGroups
}

/**
 * User clicked on "Explain with AI" button in Query Performance detail panel
 *
 * @group Events
 * @source studio
 * @page /dashboard/project/{ref}/observability/query-performance
 */
export interface QueryPerformanceAIExplanationClickedEvent {
  action: 'query_performance_ai_explanation_clicked'
  groups: TelemetryGroups
}

/**
 * User opened the request upgrade modal (for users without billing permissions).
 *
 * @group Events
 * @source studio
 */
export interface RequestUpgradeModalOpenedEvent {
  action: 'request_upgrade_modal_opened'
  properties: {
    /** Target plan being requested */
    requestedPlan: 'Pro' | 'Team' | 'Enterprise'
    /** Addon being requested, if applicable */
    addon?: 'pitr' | 'customDomain' | 'spendCap' | 'computeSize'
    /** Current organization plan */
    currentPlan?: string
    /** Feature context driving the upgrade request */
    featureProposition?: string
  }
  groups: Omit<TelemetryGroups, 'project'>
}


Review comment (performance):
Nit but I'd recommend naming this something like `query_performance_explain_with_ai_button_clicked` to align with the `*_button_clicked` convention we have going in similar events.

Code after:
     */
    advisorCategory?: AdvisorCategory
    /**
     * Specific advisor type/name
     */
    advisorType?: string
    /**
     * Severity level of the advisor (only for lints)
     */
    advisorLevel?: AdvisorLevel
    /**
     * Number of issues found (only included when origin is 'homepage')
     */
    issuesCount?: number
  }
  groups: TelemetryGroups
}

/**
 * User clicked on "Explain with AI" button in Query Performance detail panel
 *
 * @group Events
 * @source studio
 * @page /dashboard/project/{ref}/observability/query-performance
 */
export interface QueryPerformanceAIExplanationButtonClickedEvent {
  action: 'query_performance_explain_with_ai_button_clicked'
  groups: TelemetryGroups
}

/**
 * User opened the request upgrade modal (for users without billing permissions).
 *
 * @group Events
 * @source studio
 */
export interface RequestUpgradeModalOpenedEvent {
  action: 'request_upgrade_modal_opened'
  properties: {
    /** Target plan being requested */
    requestedPlan: 'Pro' | 'Team' | 'Enterprise'
    /** Addon being requested, if applicable */
    addon?: 'pitr' | 'customDomain' | 'spendCap' | 'computeSize'
    /** Current organization plan */
    currentPlan?: string
    /** Feature context driving the upgrade request */
    featureProposition?: string
  }
  groups: Omit<TelemetryGroups, 'project'>
}
Repository: supabase/supabase
File: apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts (TypeScript)

Code before:
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'

import { configKeys } from 'data/config/keys'
import { databaseKeys } from 'data/database/keys'
import { handleError, patch } from 'data/fetchers'
import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError, UseCustomMutationOptions } from 'types'

export type CreateAndExposeAPISchemaVariables = {
  projectRef: string
  connectionString?: string | null
  existingPostgrestConfig: {
    db_pool: number | null
    max_rows: number
    db_extra_search_path: string
    db_schema: string
  }
}

export async function createAndExposeApiSchema({
  projectRef,
  connectionString,
  existingPostgrestConfig,
}: CreateAndExposeAPISchemaVariables) {
  const sql = `
create schema if not exists api;
grant usage on schema api to anon, authenticated;
  `.trim()

  await executeSql({ projectRef, connectionString, sql })

  const { db_extra_search_path, db_pool, db_schema, max_rows } = existingPostgrestConfig

  const body: { max_rows: number; db_extra_search_path: string; db_schema: string; db_pool?: number } = {
    max_rows,
    db_extra_search_path,
    db_schema: `api, ${db_schema}`,
  }

Review comment (suggestion):
Maybe we should follow the same type def as `connectionString` ?
like:
```ts
db_pool?: number | null // with '?'
```

Code after:
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'

import { components } from 'api-types'
import { configKeys } from 'data/config/keys'
import { databaseKeys } from 'data/database/keys'
import { handleError, patch } from 'data/fetchers'
import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError, UseCustomMutationOptions } from 'types'

export type CreateAndExposeAPISchemaVariables = {
  projectRef: string
  connectionString?: string | null
  existingPostgrestConfig: {
    db_pool?: number | null
    max_rows: number
    db_extra_search_path: string
    db_schema: string
  }
}

type UpdatePostgrestConfigBody = components['schemas']['UpdatePostgrestConfigBody']

export async function createAndExposeApiSchema({
  projectRef,
  connectionString,
  existingPostgrestConfig,
}: CreateAndExposeAPISchemaVariables) {
  const sql = `
create schema if not exists api;
grant usage on schema api to anon, authenticated;
  `.trim()

  await executeSql({ projectRef, connectionString, sql })

  const { db_extra_search_path, db_pool, db_schema, max_rows } = existingPostgrestConfig

  const body: UpdatePostgrestConfigBody = {
    max_rows,
Repository: supabase/supabase
File: apps/studio/components/ui/UpgradeToPro.tsx (TypeScript)

Code before:
  buttonVariant?: 'default' | 'primary'
  className?: string
}

export const UpgradeToPro = ({
  icon,
  primaryText,
  secondaryText,
  plan: planToUpgrade = 'Pro',
  addon,
  featureProposition,
  buttonText,
  source = 'upgrade',
  disabled = false,
  fullWidth = false,
  layout = 'horizontal',
  buttonVariant = 'primary',
  className,
}: UpgradeToProProps) => {
  return (
    <Admonition
      type="default"
      icon={icon}
      layout={layout}
      title={primaryText}
      description={secondaryText}
      className={cn(
        'mb-0',
        fullWidth &&
          'border-0 rounded-none border-b px-6 [&>svg]:left-6 [&>div>button]:w-min [&>div>button]:mt-3 [&>div>a]:w-min [&>div>a]:mt-3',
        className
      )}
      actions={
        <UpgradePlanButton
          plan={planToUpgrade}
          addon={addon}
          source={source}
          featureProposition={featureProposition}
          disabled={disabled}
          type={buttonVariant}
        >
          {buttonText}
        </UpgradePlanButton>
      }
    />
  )
}


Review comment (suggestion):
Removed this `bg` override. It should be set on any children that specifically need it.

I did a brief check against other `UpgradeToPro` instances, with nothing looking out of place. I’ll do another sweep in a second and make any per-child changes as needed.

Code after:
  variant?: 'default' | 'primary'
  className?: string
}

export const UpgradeToPro = ({
  icon,
  primaryText,
  secondaryText,
  plan: planToUpgrade = 'Pro',
  addon,
  featureProposition,
  buttonText,
  source = 'upgrade',
  disabled = false,
  fullWidth = false,
  layout = 'horizontal',
  variant = 'primary',
  className,
}: UpgradeToProProps) => {
  return (
    <Admonition
      type="default"
      icon={icon}
      layout={layout}
      title={primaryText}
      description={secondaryText}
      className={cn(fullWidth && 'border-0 rounded-none border-b', className)}
      actions={
        <UpgradePlanButton
          plan={planToUpgrade}
          addon={addon}
          source={source}
          featureProposition={featureProposition}
          disabled={disabled}
          variant={variant}
        >
          {buttonText}
        </UpgradePlanButton>
      }
    />
  )
}
Repository: supabase/supabase
File: apps/studio/components/interfaces/Storage/FilesBuckets/useSelectedBucket.ts (TypeScript)

Code before:
import { useParams } from 'common'
import { usePaginatedBucketsQuery } from 'data/storage/buckets-query'

export const useSelectedBucket = () => {
  const { ref, bucketName } = useParams()

  const query = usePaginatedBucketsQuery(
    {
      projectRef: ref,
      search: bucketName,
      limit: 1,
    },
    {
      enabled: !!bucketName,
    }
  )

  // With server-side search by exact bucket name and limit 1,
  // we only need to check the first result of the first page
  const firstResult = query.data?.pages[0]?.[0]
  // Do an equality check in case server-side search is fuzzy
  const bucket = firstResult?.name === bucketName ? firstResult : undefined

  return {
    ...query,
    data: bucket,
  }
}


Review comment (suggestion):
```suggestion
      // Search extra and sort by name in case of fuzzy search, prefixes, etc
      limit: 10,
      sortColumn: 'name'
```

Code after:
import { useParams } from 'common'
import { useBucketQuery } from 'data/storage/buckets-query'

export const useSelectedBucket = () => {
  const { ref, bucketId } = useParams()

  const query = useBucketQuery(
    {
      projectRef: ref,
      bucketId,
    },
    {
      enabled: !!bucketId,
    }
  )

  return query
}
Repository: supabase/supabase
File: apps/www/lib/redirects.js (JavaScript)

Code before:
  },
  {
    permanent: false,
    source: '/docs/guides/platform/org-based-billing#multiple-projects-in-a-pro-plan-organization',
    destination: '/docs/guides/platform/billing-on-supabase',
  },
  {
    permanent: false,
    source: '/docs/guides/platform/spend-cap',
    destination: '/docs/guides/platform/cost-control#spend-cap',
  },
  {
    permanent: true,
    source: '/docs/guides/project-management/api',
    destination: '/docs/reference/api/introduction',
  },
  {
    permanent: false,
    source: '/mcp',
    destination: '/docs/guides/getting-started/mcp',
  },
  {
    permanent: true,
    source: '/design-system',
    destination: '/design',
  },

  // marketing

  {
    permanent: true,
    source: '/changelogpod',
    destination: 'https://forms.supabase.com/changelog-podcast-sponsorship',
  },

  // features
  {
    permanent: true,
    source: '/features/ai-query-assistance',
    destination: '/features/ai-assistant',
  },
  {
    permanent: true,
    source: '/features/fly-postgres',
    destination: '/features/postgres-database',
  },
  {
    permanent: true,
    source: '/docs/guides/platform/fly-postgres',
    destination: '/docs/guides/database/overview',
  },

Review comment (suggestion):
Figured it would be nice to have:

https://supabase.com/design-system


...redirect to:

https://supabase.com/design

...which is the main URL for our design-system moving forward.

We could do the opposite but I figured:
- Shorter is nicer
- We already follow this pattern for ui-library → https://supabase.com/ui

Code after:
  },
  {
    permanent: false,
    source: '/docs/guides/platform/org-based-billing#multiple-projects-in-a-pro-plan-organization',
    destination: '/docs/guides/platform/billing-on-supabase',
  },
  {
    permanent: false,
    source: '/docs/guides/platform/spend-cap',
    destination: '/docs/guides/platform/cost-control#spend-cap',
  },
  {
    permanent: true,
    source: '/docs/guides/project-management/api',
    destination: '/docs/reference/api/introduction',
  },
  {
    permanent: false,
    source: '/mcp',
    destination: '/docs/guides/getting-started/mcp',
  },
  {
    permanent: true,
    source: '/design',
    destination: '/design-system',
  },

  // marketing

  {
    permanent: true,
    source: '/changelogpod',
    destination: 'https://forms.supabase.com/changelog-podcast-sponsorship',
  },

  // features
  {
    permanent: true,
    source: '/features/ai-query-assistance',
    destination: '/features/ai-assistant',
  },
  {
    permanent: true,
    source: '/features/fly-postgres',
    destination: '/features/postgres-database',
  },
  {
    permanent: true,
    source: '/docs/guides/platform/fly-postgres',
    destination: '/docs/guides/database/overview',
  },
Repository: supabase/supabase
File: packages/common/telemetry-constants.ts (TypeScript)

Code before:
    /**
     * Number of steps completed when dismissed
     */
    steps_completed: number
    /**
     * Total number of steps in the workflow
     */
    total_steps: number
  }
  groups: TelemetryGroups
}

/**
 * Getting Started section was shown to the user in HomeV2.
 *
 * @group Events
 * @source studio
 * @page /project/{ref}
 */
export interface HomeGettingStartedSectionExposedEvent {
  action: 'home_getting_started_section_exposed'
  properties: {
    /**
     * The current workflow shown (null if choosing workflow)
     */
    workflow: 'code' | 'no_code' | null
  }
  groups: TelemetryGroups
}

/**
 * User was exposed to the HomeV2 experiment (shown the new home page).
 *
 * @group Events
 * @source studio
 * @page /project/{ref}
 */
export interface HomeNewExperimentExposedEvent {
  action: 'home_new_experiment_exposed'
  properties: {
    /**
     * The experiment variant shown to the user
     */
    variant: string
  }
  groups: TelemetryGroups
}

/**
 * User reordered sections in HomeV2 using drag and drop.
 *

Review comment (suggestion):
Probably out of scope for this PR, but just a thought: it could be interesting to add click events for the list items (with a property for which one was clicked), and maybe also track dismissals and the different CTAs in each section.

Code after:
  action: 'home_getting_started_closed'
  properties: {
    /**
     * The current workflow when dismissed
     */
    workflow: 'code' | 'no_code'
    /**
     * Number of steps completed when dismissed
     */
    steps_completed: number
    /**
     * Total number of steps in the workflow
     */
    total_steps: number
  }
  groups: TelemetryGroups
}

/**
 * Getting Started section was shown to the user in HomeV2.
 *
 * @group Events
 * @source studio
 * @page /project/{ref}
 */
export interface HomeGettingStartedSectionExposedEvent {
  action: 'home_getting_started_section_exposed'
  properties: {
    /**
     * The current workflow shown (null if choosing workflow)
     */
    workflow: 'code' | 'no_code' | null
  }
  groups: TelemetryGroups
}

/**
 * User was exposed to the HomeV2 experiment (shown the new home page).
 *
 * @group Events
 * @source studio
 * @page /project/{ref}
 */
export interface HomeNewExperimentExposedEvent {
  action: 'home_new_experiment_exposed'
  properties: {
    /**
     * The experiment variant shown to the user
     */
    variant: string
  }
Repository: supabase/supabase
File: apps/studio/components/interfaces/Home/ProjectList/ProjectListSort.utils.ts (TypeScript)

Code before:
export const PROJECT_LIST_SORT_VALUES = [
  'name_asc',
  'name_desc',
  'created_desc',
  'created_asc',
] as const

export type ProjectListSort = (typeof PROJECT_LIST_SORT_VALUES)[number]
export type ProjectListSortableColumn = 'name' | 'created'

export const PROJECT_LIST_SORT_LABELS: Record<ProjectListSort, string> = {
  name_asc: 'Project name (A–Z)',
  name_desc: 'Project name (Z–A)',
  created_desc: 'Creation date (Newest first)',
  created_asc: 'Creation date (Oldest first)',
}

export const getProjectListSortButtonLabel = (value: ProjectListSort) => {
  if (value.startsWith('created')) return 'creation date'
  return 'name'
}

export const toTableHeadSortValue = (sort: ProjectListSort) => sort.replace('_', ':')

export const getNextProjectListSortForColumn = (
  currentSort: ProjectListSort,
  column: ProjectListSortableColumn
): ProjectListSort => {
  if (column === 'name') {
    if (currentSort === 'name_asc') return 'name_desc'
    if (currentSort === 'name_desc') return 'name_asc'
    return 'name_asc'
  }

  if (currentSort === 'created_desc') return 'created_asc'
  if (currentSort === 'created_asc') return 'created_desc'
  return 'created_desc'
}

export const getProjectListAriaSort = (

Review comment (security):
Just a nit but these feel pretty verbose imo - wondering if we should do a nested dropdown for sort? we've got this for auth users
<img width="343" height="246" alt="Image" src="https://github.com/user-attachments/assets/69806962-c3fb-492b-85a5-47ade2e1feeb" />

we should also probably standardise our sort dropdowns too - e.g for storage explorer we've got it like this
<img width="349" height="140" alt="Image" src="https://github.com/user-attachments/assets/5cbb5fde-e147-4578-81d4-816752ab6852" />

Code after:
export const PROJECT_LIST_SORT_VALUES = [
  'name_asc',
  'name_desc',
  'created_desc',
  'created_asc',
] as const

export type ProjectListSort = (typeof PROJECT_LIST_SORT_VALUES)[number]

export const toTableHeadSortValue = (sort: ProjectListSort) => sort.replace('_', ':')

export const getNextProjectListSortForColumn = (currentSort: ProjectListSort): ProjectListSort => {
  if (currentSort.includes('asc')) return currentSort.replace('asc', 'desc') as ProjectListSort
  if (currentSort.includes('desc')) return currentSort.replace('desc', 'asc') as ProjectListSort
  return 'name_asc'
}

export const getProjectListAriaSort = (
  currentSort: ProjectListSort
): 'ascending' | 'descending' | 'none' => {
  if (currentSort.includes('asc')) return 'ascending'
  if (currentSort.includes('desc')) return 'descending'
  return 'none'
}