import { useQuery } from '@tanstack/react-query' import { createFileRoute, Link, useNavigate } from '@tanstack/react-router' import { useParams } from 'common' import { AlertTriangleIcon, GitBranchIcon, GitMergeIcon, XIcon } from 'lucide-react' import { useCallback, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { BreadcrumbItem, BreadcrumbLink, BreadcrumbList, Button, cn, NavMenu, NavMenuItem, } from 'ui' import { Admonition } from 'ui-patterns/Admonition' import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal' import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational' import { PageBreadcrumbs } from 'ui-patterns/PageBreadcrumbs' import { PageContainer } from 'ui-patterns/PageContainer' import { PageHeader, PageHeaderAside, PageHeaderDescription, PageHeaderMeta, PageHeaderSummary, PageHeaderTitle, } from 'ui-patterns/PageHeader' import { PageNav } from 'ui-patterns/PageNav' import { PageSection } from 'ui-patterns/PageSection' import { useIsPgDeltaDiffEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext' import { MergeActions, MergeSubtitle, MergeTitle, } from '@/components/interfaces/Branching/MergeRequest' import { DatabaseDiffPanel } from '@/components/interfaces/BranchManagement/DatabaseDiffPanel' import { EdgeFunctionsDiffPanel } from '@/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel' import { OutOfDateNotice } from '@/components/interfaces/BranchManagement/OutOfDateNotice' import { WorkflowLogsCard } from '@/components/interfaces/BranchManagement/WorkflowLogsCard' import { ProjectLayoutWithAuth } from '@/components/layouts/ProjectLayout' import { AlertError } from '@/components/ui/AlertError' import { InlineLink } from '@/components/ui/InlineLink' import { NoPermission } from '@/components/ui/NoPermission' import { useBranchDeleteMutation } from '@/data/branches/branch-delete-mutation' import { useBranchMergeMutation } from '@/data/branches/branch-merge-mutation' import { useBranchPushMutation } from '@/data/branches/branch-push-mutation' import { useBranchUpdateMutation } from '@/data/branches/branch-update-mutation' import { branchesQueryOptions } from '@/data/branches/branches-query' import { useProjectGitHubConnectionQuery } from '@/data/integrations/github-connections-query' import { useProjectDetailQuery } from '@/data/projects/project-detail-query' import { useBranchGrant } from '@/hooks/branches/useBranchGrant' import { useBranchMergeDiff } from '@/hooks/branches/useBranchMergeDiff' import { useWorkflowManagement } from '@/hooks/branches/useWorkflowManagement' import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' import { useGrant } from '@/lib/grants' import { useTrack } from '@/lib/telemetry/track' const LAYOUT_SIZE = 'default' export const Route = createFileRoute('/project/$ref/merge')({ component: ProjectMergeRoute, }) function ProjectMergeRoute() { return ( ) } function MergePage() { const navigate = useNavigate() const { ref } = Route.useParams() const { workflow_run_id: currentWorkflowRunId, tab: tabParam } = useParams() const { data: project } = useSelectedProjectQuery() const pgDeltaDiffEnabled = useIsPgDeltaDiffEnabled() const [isSubmitting, setIsSubmitting] = useState(false) const [workflowFinalStatus, setWorkflowFinalStatus] = useState<'SUCCESS' | 'FAILED' | null>(null) const [showConfirmDialog, setShowConfirmDialog] = useState(false) const parentProjectRef = project?.parent_project_ref const isBranch = parentProjectRef !== undefined const { data: parentProject } = useProjectDetailQuery({ ref: parentProjectRef, }) const { data: ghConnection } = useProjectGitHubConnectionQuery({ ref: parentProjectRef, }) const branchesGrant = useGrant('GET /v1/projects/{ref}/branches', { projectRef: parentProjectRef, }) const { data: branches } = useQuery( branchesQueryOptions( { projectRef: parentProjectRef, grant: branchesGrant.grant }, { refetchOnMount: 'always', refetchOnWindowFocus: true, staleTime: 0 } ) ) const currentBranch = branches?.find((branch) => branch.project_ref === ref) const mainBranch = branches?.find((branch) => branch.is_default) const updateBranchGrant = useBranchGrant('PATCH /v1/branches/{branch_id_or_ref}', { projectRef: parentProjectRef, isDefault: currentBranch?.is_default, }) const pushBranchGrant = useBranchGrant('POST /v1/branches/{branch_id_or_ref}/push', { projectRef: parentProjectRef, isDefault: currentBranch?.is_default, }) const deleteBranchGrant = useBranchGrant('DELETE /v1/branches/{branch_id_or_ref}', { projectRef: parentProjectRef, isDefault: currentBranch?.is_default, }) const mergeBranchGrant = useGrant('POST /v1/branches/{branch_id_or_ref}/merge', { projectRef: parentProjectRef, }) const diffGrant = useBranchGrant('GET /v1/branches/{branch_id_or_ref}/diff', { projectRef: parentProjectRef, isDefault: currentBranch?.is_default, }) const { diffContent, isDatabaseDiffLoading, isDatabaseDiffRefetching, databaseDiffError: diffError, refetchDatabaseDiff: refetchDiff, edgeFunctionsDiff, isBranchOutOfDateMigrations, hasEdgeFunctionModifications, missingFunctionsCount, hasMissingFunctions, outOfDateFunctionsCount, hasOutOfDateFunctions, isBranchOutOfDateOverall, missingMigrationsCount, modifiedFunctionsCount, } = useBranchMergeDiff({ currentBranchRef: ref, isCurrentBranchDefault: currentBranch?.is_default, parentProjectRef, currentBranchConnectionString: project?.connectionString || undefined, parentBranchConnectionString: parentProject?.connectionString || undefined, currentBranchCreatedAt: currentBranch?.created_at, }) const { mutate: updateBranch } = useBranchUpdateMutation({ onError: (error) => { toast.error(`Failed to update branch: ${error.message}`) }, }) const clearDiffsOptimistically = edgeFunctionsDiff.clearDiffsOptimistically const handleCurrentBranchWorkflowComplete = useCallback( (status: 'SUCCESS' | 'FAILED') => { setWorkflowFinalStatus(status) refetchDiff() clearDiffsOptimistically() }, [refetchDiff, clearDiffsOptimistically] ) const handleParentBranchWorkflowComplete = useCallback( (status: 'SUCCESS' | 'FAILED') => { setWorkflowFinalStatus(status) refetchDiff() clearDiffsOptimistically() if ( ref && parentProjectRef && currentBranch?.review_requested_at && updateBranchGrant.status === 'granted' ) { updateBranch( { grant: updateBranchGrant.grant, branchRef: ref, projectRef: parentProjectRef, requestReview: false, }, { onSuccess: () => toast.success('Branch updated successfully'), } ) } }, [ refetchDiff, clearDiffsOptimistically, parentProjectRef, ref, updateBranch, updateBranchGrant, currentBranch?.review_requested_at, ] ) const { run: currentBranchWorkflow, logs: currentBranchLogs } = useWorkflowManagement({ workflowRunId: currentWorkflowRunId, projectRef: ref, onWorkflowComplete: handleCurrentBranchWorkflowComplete, }) const { run: parentBranchWorkflow, logs: parentBranchLogs } = useWorkflowManagement({ workflowRunId: currentWorkflowRunId, projectRef: parentProjectRef, onWorkflowComplete: handleParentBranchWorkflowComplete, }) const currentWorkflowRun = currentBranchWorkflow || parentBranchWorkflow const workflowRunLogs = currentBranchLogs || parentBranchLogs const hasCurrentWorkflowFailed = workflowFinalStatus === 'FAILED' const hasCurrentWorkflowCompleted = workflowFinalStatus === 'SUCCESS' const isWorkflowRunning = currentWorkflowRun?.status === 'RUNNING' const addWorkflowRun = useCallback( (workflowRunId: string) => { void navigate({ to: '/project/$ref/merge', params: { ref }, search: (prev) => ({ ...prev, workflow_run_id: workflowRunId }), }) }, [navigate, ref] ) const clearWorkflowRun = useCallback(() => { void navigate({ to: '/project/$ref/merge', params: { ref }, search: (prev) => ({ ...prev, workflow_run_id: undefined }), }) }, [navigate, ref]) const { mutate: pushBranch, isPending: isPushing } = useBranchPushMutation({ onSuccess: (data) => { toast.success('Branch update initiated!') if (data?.workflow_run_id) { addWorkflowRun(data.workflow_run_id) } track('branch_updated', { source: 'merge_page' }, { project: parentProjectRef }) }, onError: (error) => { toast.error(`Failed to update branch: ${error.message}`) }, }) const track = useTrack() const { mutate: mergeBranch, isPending: isMerging } = useBranchMergeMutation({ onSuccess: (data) => { setIsSubmitting(false) if (data.workflowRunId) { toast.success('Branch merge initiated!') addWorkflowRun(data.workflowRunId) track( 'branch_merge_completed', { branchType: currentBranch?.persistent ? 'persistent' : 'preview' }, { project: parentProjectRef } ) } else { toast.info('No changes to merge') } }, onError: (error) => { setIsSubmitting(false) toast.error(`Failed to merge branch: ${error.message}`) track( 'branch_merge_failed', { branchType: currentBranch?.persistent ? 'persistent' : 'preview', error: error.message, }, { project: parentProjectRef } ) }, }) const { mutate: deleteBranch, isPending: isDeleting } = useBranchDeleteMutation({ onSuccess: () => { toast.success('Branch closed successfully') if (parentProjectRef) { void navigate({ to: '/project/$ref/branches', params: { ref: parentProjectRef } }) } track('branch_delete_button_clicked', { origin: 'merge_page' }, { project: parentProjectRef }) }, onError: (error) => { toast.error(`Failed to close branch: ${error.message}`) }, }) const handlePush = () => { if (!ref || !parentProjectRef || pushBranchGrant.status !== 'granted') return pushBranch({ grant: pushBranchGrant.grant, branchRef: ref, projectRef: parentProjectRef, }) } const handleCloseBranch = () => { if (!ref || !parentProjectRef || deleteBranchGrant.status !== 'granted') return deleteBranch({ grant: deleteBranchGrant.grant, branchRef: ref, projectRef: parentProjectRef, }) } const handleMerge = () => { if ( !ref || !parentProjectRef || mergeBranchGrant.status !== 'granted' || diffGrant.status !== 'granted' ) { return } setIsSubmitting(true) track('branch_merge_submitted', undefined, { project: parentProjectRef }) mergeBranch({ grant: mergeBranchGrant.grant, diffGrant: diffGrant.grant, branchProjectRef: ref, baseProjectRef: parentProjectRef, migration_version: undefined, pgdelta: pgDeltaDiffEnabled, }) } const currentTab = tabParam || 'database' const navigationItems = useMemo(() => { const buildSearch = (tab: string) => { const query: Record = { tab } if (currentWorkflowRunId) query.workflow_run_id = currentWorkflowRunId return query } return [ { label: 'Database', search: buildSearch('database'), active: currentTab === 'database', }, { label: 'Edge Functions', search: buildSearch('edge-functions'), active: currentTab === 'edge-functions', }, ] }, [currentWorkflowRunId, currentTab]) useEffect(() => { setWorkflowFinalStatus(null) }, [currentWorkflowRunId]) if (branchesGrant.status === 'denied') { return ( ) } if (branchesGrant.status === 'error') { return ( ) } // If not on a preview branch or branch info unavailable, show notice if (!isBranch || !currentBranch) { return ( ) } const hasGHProductionDeployEnabled = !!ghConnection && Boolean(mainBranch?.git_branch) return (
Merge requests setShowConfirmDialog(true)} /> {hasGHProductionDeployEnabled ? (

Branches should be managed via GitHub to prevent drifts in migrations from your repository's state. You may either move your schema changes to a GitHub pull request, or disable "Deploy to production" in the{' '} GitHub integration settings .

) : isBranchOutOfDateOverall && !currentWorkflowRunId ? ( ) : currentWorkflowRunId ? (
) : undefined } overrideAction={ hasCurrentWorkflowFailed ? ( ) : hasCurrentWorkflowCompleted ? ( ) : undefined } />
) : null}
{navigationItems.map((item) => ( {item.label} ))}
{currentTab === 'database' ? ( ) : ( )}
{ setShowConfirmDialog(false) handleMerge() }} onCancel={() => setShowConfirmDialog(false)} loading={isMerging || isSubmitting} />
) }