The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Remove enable branching modal (#36458)
Saxon Fletcher3f3ed433fc27
diff --git a/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx b/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsxindex 4c15961ef16..c68ecf3f6d2 100644--- a/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx+++ b/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx@@ -1,12 +1,12 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { partition } from 'lodash'-import { ExternalLink, Github, MessageCircle } from 'lucide-react'-import Link from 'next/link'+import { MessageCircle } from 'lucide-react'import { useRouter } from 'next/router'import { useState } from 'react'import { toast } from 'sonner'import { useParams } from 'common'+import { GitHubStatus } from 'components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus'import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'import { ButtonTooltip } from 'components/ui/ButtonTooltip'@@ -21,17 +21,13 @@ import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { useSelectedProject } from 'hooks/misc/useSelectedProject'import { useFlag } from 'hooks/ui/useFlag'import { useUrlState } from 'hooks/ui/useUrlState'+import { useAppStateSnapshot } from 'state/app-state'import { Button } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'import { BranchLoader, BranchManagementSection, BranchRow } from './BranchPanels'-import { CreateBranchModal } from './CreateBranchModal'-import {- BranchingEmptyState,- PreviewBranchesEmptyState,- PullRequestsEmptyState,-} from './EmptyStates'-import Overview from './Overview'+import { PreviewBranchesEmptyState, PullRequestsEmptyState } from './EmptyStates'+import { Overview } from './Overview'type Tab = 'overview' | 'prs' | 'branches'@@ -52,7 +48,8 @@ const BranchManagement = () => {const tab = urlParams.tab ?? 'overview'const setTab = (tab: Tab) => setParams({ tab })- const [showCreateBranch, setShowCreateBranch] = useState(false)+ const snap = useAppStateSnapshot()+const [showDisableBranching, setShowDisableBranching] = useState(false)const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()@@ -60,9 +57,6 @@ const BranchManagement = () => {const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {resource: { is_default: false },})- const canDisableBranching = useCheckPermissions(PermissionAction.DELETE, 'preview_branches', {- resource: { is_default: true },- })const {data: connections,@@ -135,8 +129,6 @@ const BranchManagement = () => {disableBranching({ projectRef, branchIds: previewBranches?.map((branch) => branch.id) })}- if (!hasBranchEnabled) return <BranchingEmptyState />-return (<><ScaffoldContainer>@@ -193,7 +185,7 @@ const BranchManagement = () => {<ButtonTooltiptype="primary"disabled={!canCreateBranches}- onClick={() => setShowCreateBranch(true)}+ onClick={() => snap.setShowCreateBranchModal(true)}tooltip={{content: {side: 'bottom',@@ -219,51 +211,7 @@ const BranchManagement = () => {/>)}- {isSuccessConnections && !gitlessBranching && (- <div className="border rounded-lg px-6 py-2 flex items-center justify-between">- <div className="flex items-center gap-x-4">- <div className="w-8 h-8 bg-scale-300 border rounded-md flex items-center justify-center">- <Github size={18} strokeWidth={2} />- </div>- <p className="text-sm">GitHub branch workflow</p>- <Button asChild type="default" iconRight={<ExternalLink size={14} />}>- <Link passHref href={`/project/${ref}/settings/integrations`}>- Settings- </Link>- </Button>- <Button- type="text"- size="small"- className="text-light hover:text py-1 px-1.5"- iconRight={<ExternalLink size={14} strokeWidth={1.5} />}- >- <Link- passHref- target="_blank"- rel="noreferrer"- href={`https://github.com/${repo}`}- >- {repo}- </Link>- </Button>- </div>- <ButtonTooltip- type="default"- disabled={!canDisableBranching}- onClick={() => setShowDisableBranching(true)}- tooltip={{- content: {- side: 'bottom',- text: !canDisableBranching- ? 'You need additional permissions to disable branching'- : undefined,- },- }}- >- Disable branching- </ButtonTooltip>- </div>- )}+ {isSuccessConnections && hasBranchEnabled && <GitHubStatus />}{isErrorBranches && tab === 'overview' && (<AlertError@@ -282,9 +230,10 @@ const BranchManagement = () => {mainBranch={mainBranch}previewBranches={previewBranches}onViewAllBranches={() => setTab('branches')}- onSelectCreateBranch={() => setShowCreateBranch(true)}+ onSelectCreateBranch={() => snap.setShowCreateBranchModal(true)}onSelectDeleteBranch={setSelectedBranchToDelete}generateCreatePullRequestURL={generateCreatePullRequestURL}+ showProductionBranch={hasBranchEnabled}/>)}{tab === 'prs' && (@@ -326,7 +275,7 @@ const BranchManagement = () => {)}{isSuccessBranches && previewBranches.length === 0 && (<PreviewBranchesEmptyState- onSelectCreateBranch={() => setShowCreateBranch(true)}+ onSelectCreateBranch={() => snap.setShowCreateBranchModal(true)}/>)}{isSuccessBranches &&@@ -395,8 +344,6 @@ const BranchManagement = () => {</li></ul></ConfirmationModal>-- <CreateBranchModal visible={showCreateBranch} onClose={() => setShowCreateBranch(false)} /></>)}diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsxindex 86dd533b9e2..4d5c1f5dc30 100644--- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx+++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx@@ -1,24 +1,28 @@import { zodResolver } from '@hookform/resolvers/zod'+import { useQueryClient } from '@tanstack/react-query'import { useParams } from 'common'-import { Check, DollarSign, Github, Loader2 } from 'lucide-react'+import { DollarSign, Github, GitMerge, Loader2 } from 'lucide-react'import Image from 'next/image'import Link from 'next/link'-import { useEffect, useState } from 'react'+import { useEffect } from 'react'import { useForm } from 'react-hook-form'import { toast } from 'sonner'import * as z from 'zod'+import { BranchingPITRNotice } from 'components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice'import AlertError from 'components/ui/AlertError'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useBranchCreateMutation } from 'data/branches/branch-create-mutation'import { useBranchesQuery } from 'data/branches/branches-query'import { useCheckGithubBranchValidity } from 'data/integrations/github-branch-check-query'import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'+import { projectKeys } from 'data/projects/keys'+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { useSelectedProject } from 'hooks/misc/useSelectedProject'import { useFlag } from 'hooks/ui/useFlag'import { BASE_PATH } from 'lib/constants'-import { sidePanelsState } from 'state/side-panels'+import { useAppStateSnapshot } from 'state/app-state'import {Badge,Button,@@ -31,7 +35,6 @@ import {DialogTitle,FormControl_Shadcn_,FormField_Shadcn_,- FormItem_Shadcn_,FormMessage_Shadcn_,Form_Shadcn_,Input_Shadcn_,@@ -39,19 +42,16 @@ import {cn,} from 'ui'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { useRouter } from 'next/router'-interface CreateBranchModalProps {- visible: boolean- onClose: () => void-}--export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps) => {+export const CreateBranchModal = () => {const { ref } = useParams()+ const router = useRouter()+ const queryClient = useQueryClient()const projectDetails = useSelectedProject()const selectedOrg = useSelectedOrganization()const gitlessBranching = useFlag('gitlessBranching')-- const [isGitBranchValid, setIsGitBranchValid] = useState(false)+ const { showCreateBranchModal, setShowCreateBranchModal } = useAppStateSnapshot()const isBranch = projectDetails?.parent_project_ref !== undefinedconst projectRef =@@ -68,15 +68,21 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)})const { data: branches } = useBranchesQuery({ projectRef })+ const { data: addons } = useProjectAddonsQuery({ projectRef })+ const hasPitrEnabled =+ (addons?.selected_addons ?? []).find((addon) => addon.type === 'pitr') !== undefinedconst { mutateAsync: checkGithubBranchValidity, isLoading: isChecking } =useCheckGithubBranchValidity({onError: () => {},})const { mutate: createBranch, isLoading: isCreating } = useBranchCreateMutation({- onSuccess: (data) => {+ onSuccess: async (data) => {toast.success(`Successfully created preview branch "${data.name}"`)- onClose()+ if (projectRef) {+ await Promise.all([queryClient.invalidateQueries(projectKeys.detail(projectRef))])+ }+ setShowCreateBranchModal(false)},onError: (error) => {toast.error(`Failed to create branch: ${error.message}`)@@ -84,9 +90,11 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)})const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)- const [repoOwner, repoName] = githubConnection?.repository.name.split('/') ?? []- const isBranchingEnabled = gitlessBranching || !!githubConnection+ // Fetch production/default branch to inspect git_branch linkage+ const prodBranch = branches?.find((branch) => branch.is_default)++ const [repoOwner, repoName] = githubConnection?.repository.name.split('/') ?? []const formId = 'create-branch-form'const FormSchema = z@@ -105,71 +113,59 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)gitBranchName: z.string().refine(- (val) => !githubConnection?.id || (val && val.length > 0),- 'Git branch name is required when Git is connected'+ (val) => gitlessBranching || !githubConnection || (val && val.length > 0),+ 'Git branch name is required when GitHub is connected'),}).superRefine(async (val, ctx) => {- if (val.gitBranchName && val.gitBranchName.length > 0 && githubConnection?.id) {+ if (val.gitBranchName && val.gitBranchName.length > 0 && githubConnection?.repository.id) {try {await checkGithubBranchValidity({- connectionId: githubConnection.id,+ repositoryId: githubConnection.repository.id,branchName: val.gitBranchName,})- setIsGitBranchValid(true)+ // valid – no issues added} catch (error) {- setIsGitBranchValid(false)ctx.addIssue({code: z.ZodIssueCode.custom,message: `Unable to find branch "${val.gitBranchName}" in ${repoOwner}/${repoName}`,path: ['gitBranchName'],})}- } else {- setIsGitBranchValid(!val.gitBranchName || val.gitBranchName.length === 0)}})const form = useForm<z.infer<typeof FormSchema>>({- mode: 'onBlur',- reValidateMode: 'onChange',+ mode: 'onSubmit',+ reValidateMode: 'onBlur',resolver: zodResolver(FormSchema),defaultValues: { branchName: '', gitBranchName: '' },})- const isFormValid =- form.formState.isValid && (!form.getValues('gitBranchName') || isGitBranchValid)- const canSubmit = isFormValid && !isCreating && !isChecking && isBranchingEnabled+ const canSubmit = !isCreating && !isCheckingconst onSubmit = (data: z.infer<typeof FormSchema>) => {if (!projectRef) return console.error('Project ref is required')createBranch({projectRef,branchName: data.branchName,- ...(data.gitBranchName && isGitBranchValid ? { gitBranch: data.gitBranchName } : {}),+ ...(data.gitBranchName ? { gitBranch: data.gitBranchName } : {}),})}+ const handleGitHubClick = () => {+ setShowCreateBranchModal(false)+ router.push(`/project/${projectRef}/settings/integrations`)+ }+useEffect(() => {- if (form && visible) {- setIsGitBranchValid(false)+ if (form && showCreateBranchModal) {form.reset()}- }, [form, visible])-- useEffect(() => {- setIsGitBranchValid(- !form.getValues('gitBranchName') || form.getValues('gitBranchName')?.length === 0- )- }, [githubConnection?.id, form.getValues('gitBranchName')])-- const openLinkerPanel = () => {- onClose()- sidePanelsState.setGithubConnectionsOpen(true)- }+ }, [form, showCreateBranchModal])return (- <Dialog open={visible} onOpenChange={(open) => !open && onClose()}>+ <Dialog open={showCreateBranchModal} onOpenChange={(open) => setShowCreateBranchModal(open)}><DialogContent size="large" hideClose><DialogHeader padding="small"><DialogTitle>Create a new preview branch</DialogTitle>@@ -190,6 +186,7 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)autoComplete="off"/></FormControl_Shadcn_>+ <FormMessage_Shadcn_ /></FormItemLayout>)}/>@@ -199,28 +196,34 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)control={form.control}name="gitBranchName"render={({ field }) => (- <FormItem_Shadcn_>- <div className="flex items-center justify-between mb-2">- <Label>Link to Git Branch {gitlessBranching ? '(Optional)' : ''}</Label>- <div className="flex items-center gap-2 text-sm">- <Image- className={cn('dark:invert')}- src={`${BASE_PATH}/img/icons/github-icon.svg`}- width={16}- height={16}- alt={`GitHub icon`}- />- <Link- href={`https://github.com/${repoOwner}/${repoName}`}- target="_blank"- rel="noreferrer"- className="text-foreground hover:underline"- >- {repoOwner}/{repoName}- </Link>+ <FormItemLayout+ label={+ <div className="flex items-center justify-between w-full gap-4">+ <span className="flex-1">+ Sync with Git branch {gitlessBranching ? '(optional)' : ''}+ </span>+ <div className="flex items-center gap-2 text-sm">+ <Image+ className={cn('dark:invert')}+ src={`${BASE_PATH}/img/icons/github-icon.svg`}+ width={16}+ height={16}+ alt={`GitHub icon`}+ />+ <Link+ href={`https://github.com/${repoOwner}/${repoName}`}+ target="_blank"+ rel="noreferrer"+ className="text-foreground hover:underline"+ >+ {repoOwner}/{repoName}+ </Link>+ </div></div>- </div>- <div className="relative">+ }+ description="Automatically deploy changes on every commit"+ >+ <div className="relative w-full"><FormControl_Shadcn_><Input_Shadcn_{...field}@@ -228,18 +231,11 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)autoComplete="off"/></FormControl_Shadcn_>- <div className="absolute top-2 right-3 flex items-center gap-2">+ <div className="absolute top-2.5 right-3 flex items-center gap-2">{isChecking && <Loader2 size={14} className="animate-spin" />}- {field.value && !isChecking && isGitBranchValid && (- <Check size={14} className="text-brand" strokeWidth={2} />- )}</div></div>- <p className="text-sm text-foreground-light mt-2">- If linked, migrations from this Git branch will be automatically deployed.- </p>- <FormMessage_Shadcn_ />- </FormItem_Shadcn_>+ </FormItemLayout>)}/>)}@@ -254,9 +250,9 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps)<>{!githubConnection && (<div className="flex items-center gap-2 justify-between">- <div>- <div className="flex items-center gap-2 mb-2">- <Label>GitHub Repository</Label>+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <Label>Sync with a GitHub branch</Label>{!gitlessBranching && (<Badge variant="warning" size="small">Required@@ -264,13 +260,11 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps))}</div><p className="text-sm text-foreground-light">- {gitlessBranching- ? 'Optionally connect to a GitHub repository to manage migrations automatically for this branch.'- : 'Connect to a GitHub repository to enable branch creation. This allows you to manage migrations automatically for this branch.'}+ Keep this preview branch in sync with a chosen GitHub branch</p></div>- <Button type="default" icon={<Github />} onClick={openLinkerPanel}>- Connect to GitHub+ <Button type="default" icon={<Github />} onClick={handleGitHubClick}>+ Configure</Button></div>)}@@ -278,25 +272,84 @@ export const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps))}</DialogSection>- <DialogFooter className="sm:justify-between gap-2" padding="medium">- <p className="flex items-center gap-2 text-sm text-foreground">- <DollarSign size={16} strokeWidth={1.5} />- Each preview branch costs $0.01344 per hour- </p>- <div className="flex items-center gap-2">- <Button disabled={isCreating} type="default" onClick={onClose}>- Cancel- </Button>- <Button- form={formId}- disabled={!isSuccessConnections || isCreating || !canSubmit || isChecking}- loading={isCreating}- type="primary"- htmlType="submit"- >- Create branch- </Button>+ <DialogSectionSeparator />++ <DialogSection padding="medium" className="flex flex-col gap-4">+ {githubConnection && (+ <div className="flex flex-row gap-4">+ <div>+ <figure className="w-10 h-10 rounded-md bg-info-200 border border-info-400 flex items-center justify-center">+ <GitMerge className="text-info" size={20} strokeWidth={2} />+ </figure>+ </div>+ <div className="flex flex-col gap-y-1">+ <p className="text-sm text-foreground">+ {prodBranch?.git_branch+ ? 'Merging to production enabled'+ : 'Merging to production disabled'}+ </p>+ <p className="text-sm text-foreground-light">+ {prodBranch?.git_branch ? (+ <>+ When this branch is merged to{' '}+ <code className="text-xs font-mono">{prodBranch.git_branch}</code>,+ migrations will be deployed to production. Otherwise, migrations only run+ on preview branches.+ </>+ ) : (+ <>+ Merging this branch to production will not deploy migrations. To enable+ production deployment, enable "Deploy to production" in project+ integration settings.+ </>+ )}+ </p>+ </div>+ </div>+ )}++ <div className="flex flex-row gap-4">+ <div>+ <figure className="w-10 h-10 rounded-md bg-info-200 border border-info-400 flex items-center justify-center">+ <DollarSign className="text-info" size={20} strokeWidth={2} />+ </figure>+ </div>+ <div className="flex flex-col gap-y-1">+ <p className="text-sm text-foreground">+ Preview branches are billed $0.01344 per hour+ </p>+ <p className="text-sm text-foreground-light">+ This cost will continue for as long as the branch has not been removed.+ </p>+ </div></div>++ {!hasPitrEnabled && <BranchingPITRNotice />}+ </DialogSection>++ <DialogFooter className="justify-end gap-2" padding="medium">+ <Button+ disabled={isCreating}+ type="default"+ onClick={() => setShowCreateBranchModal(false)}+ >+ Cancel+ </Button>+ <Button+ form={formId}+ disabled={+ !isSuccessConnections ||+ isCreating ||+ !canSubmit ||+ isChecking ||+ (!gitlessBranching && !githubConnection)+ }+ loading={isCreating}+ type="primary"+ htmlType="submit"+ >+ Create branch+ </Button></DialogFooter></form></Form_Shadcn_>diff --git a/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsxindex 1f058c0ee99..388cd63928b 100644--- a/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx+++ b/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx@@ -106,7 +106,7 @@ export const EditBranchModal = ({ branch, visible, onClose }: EditBranchModalProif (val.gitBranchName && val.gitBranchName.length > 0 && githubConnection?.id) {try {await checkGithubBranchValidity({- connectionId: githubConnection.id,+ repositoryId: githubConnection.id,branchName: val.gitBranchName,})setIsGitBranchValid(true)diff --git a/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx b/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsxindex 329ebaeeb70..0020b560bdc 100644--- a/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx+++ b/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx@@ -12,31 +12,31 @@ import { Button } from 'ui'export const BranchingEmptyState = () => {const snap = useAppStateSnapshot()- const canEnableBranching = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {- resource: { is_default: true },+ const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {+ resource: { is_default: false },})return (<ProductEmptyState title="Database Branching"><p className="text-sm text-light">- Create preview branches to experiment changes to your database schema in a safe,- non-destructible environment.+ Create preview branches to experiment with changes to your database schema in a safe,+ non-destructive environment.</p><div className="flex items-center space-x-2 !mt-4"><ButtonTooltip- disabled={!canEnableBranching}+ disabled={!canCreateBranches}icon={<GitBranch strokeWidth={1.5} />}- onClick={() => snap.setShowEnableBranchingModal(true)}+ onClick={() => snap.setShowCreateBranchModal(true)}tooltip={{content: {side: 'bottom',- text: !canEnableBranching- ? 'You need additional permissions to enable branching'+ text: !canCreateBranches+ ? 'You need additional permissions to create branches': undefined,},}}>- Enable branching+ Create branch</ButtonTooltip><Button type="default" icon={<ExternalLink strokeWidth={1.5} />} asChild>diff --git a/apps/studio/components/interfaces/BranchManagement/Overview.tsx b/apps/studio/components/interfaces/BranchManagement/Overview.tsxindex c01db388056..487ad934292 100644--- a/apps/studio/components/interfaces/BranchManagement/Overview.tsx+++ b/apps/studio/components/interfaces/BranchManagement/Overview.tsx@@ -2,9 +2,9 @@ import { noop } from 'lodash'import { Button } from 'ui'import type { Branch } from 'data/branches/branches-query'+import { ChevronRight } from 'lucide-react'import { BranchLoader, BranchManagementSection, BranchRow, BranchRowLoader } from './BranchPanels'import { PreviewBranchesEmptyState } from './EmptyStates'-import { ChevronRight } from 'lucide-react'const MAX_BRANCHES_OVERVIEW = 10@@ -18,9 +18,10 @@ interface OverviewProps {onSelectCreateBranch: () => voidonSelectDeleteBranch: (branch: Branch) => voidgenerateCreatePullRequestURL: (branchName?: string) => string+ showProductionBranch?: boolean}-const Overview = ({+export const Overview = ({isLoading,isSuccess,repo,@@ -30,15 +31,18 @@ const Overview = ({onSelectCreateBranch,onSelectDeleteBranch,generateCreatePullRequestURL,+ showProductionBranch = true,}: OverviewProps) => {return (<>- <BranchManagementSection header="Production branch">- {isLoading && <BranchRowLoader />}- {isSuccess && mainBranch !== undefined && (- <BranchRow isMain branch={mainBranch} repo={repo} onSelectDeleteBranch={noop} />- )}- </BranchManagementSection>+ {showProductionBranch && (+ <BranchManagementSection header="Production branch">+ {isLoading && <BranchRowLoader />}+ {isSuccess && mainBranch !== undefined && (+ <BranchRow isMain branch={mainBranch} repo={repo} onSelectDeleteBranch={noop} />+ )}+ </BranchManagementSection>+ )}<BranchManagementSectionheader="Preview branches"@@ -72,5 +76,3 @@ const Overview = ({</>)}--export default Overviewdiff --git a/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx b/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsxindex f631d52c94b..a412150f120 100644--- a/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx+++ b/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx@@ -1,10 +1,10 @@+import dayjs from 'dayjs'+import { ArrowLeft, ArrowRight } from 'lucide-react'import { useState } from 'react'import AlertError from 'components/ui/AlertError'import { useWorkflowRunLogsQuery } from 'data/workflow-runs/workflow-run-logs-query'import { useWorkflowRunsQuery } from 'data/workflow-runs/workflow-runs-query'-import dayjs from 'dayjs'-import { ArrowLeft, ArrowRight } from 'lucide-react'import {Button,cn,@@ -77,13 +77,17 @@ const WorkflowLogs = ({ projectRef }: WorkflowLogsProps) => {<DialogSection className={cn('px-0', isWorkflowRunLogsSuccess ? 'py-0 pt-2' : '!py-0')}>{selectedWorkflowRunId === undefined ? (<>- {isWorkflowRunsLoading && <GenericSkeletonLoader className="py-2 px-5" />}- {isWorkflowRunsError && <AlertError error={workflowRunsError} />}+ {isWorkflowRunsLoading && <GenericSkeletonLoader className="py-4" />}+ {isWorkflowRunsError && (+ <div className="py-4">+ <AlertError error={workflowRunsError} />+ </div>+ )}{isWorkflowRunsSuccess &&(workflowRuns.length > 0 ? (<ul className="divide-y">{workflowRuns.map((workflowRun) => (- <li key={workflowRun.id} className="py-3 px-5">+ <li key={workflowRun.id} className="py-3"><buttontype="button"onClick={() => setSelectedWorkflowRunId(workflowRun.id)}@@ -112,21 +116,23 @@ const WorkflowLogs = ({ projectRef }: WorkflowLogsProps) => {onClick={() => setSelectedWorkflowRunId(undefined)}type="text"icon={<ArrowLeft />}- className="self-start mx-5"+ className="self-start">Back to workflow runs</Button>- {isWorkflowRunLogsLoading && <GenericSkeletonLoader className="py-2 px-5" />}+ {isWorkflowRunLogsLoading && <GenericSkeletonLoader className="py-2" />}{isWorkflowRunLogsError && (- <AlertError- className="rounded-none"- subject="Failed to retrieve workflow logs"- error={workflowRunLogsError}- />+ <div className="py-2">+ <AlertError+ className="rounded-none"+ subject="Failed to retrieve workflow logs"+ error={workflowRunLogsError}+ />+ </div>)}{isWorkflowRunLogsSuccess && (- <pre className="whitespace-pre max-h-[500px] overflow-scroll px-5 pb-5">+ <pre className="whitespace-pre max-h-[500px] overflow-scroll pb-5 text-sm">{workflowRunLogs}</pre>)}diff --git a/apps/studio/components/interfaces/Integrations/VercelGithub/IntegrationPanels.tsx b/apps/studio/components/interfaces/Integrations/VercelGithub/IntegrationPanels.tsxindex 2d350fad2af..7cff4c2b66c 100644--- a/apps/studio/components/interfaces/Integrations/VercelGithub/IntegrationPanels.tsx+++ b/apps/studio/components/interfaces/Integrations/VercelGithub/IntegrationPanels.tsx@@ -1,5 +1,7 @@import dayjs from 'dayjs'+import { ArrowRight, ExternalLink, Github } from 'lucide-react'import Image from 'next/legacy/image'+import Link from 'next/link'import { forwardRef, HTMLAttributes, ReactNode, RefAttributes } from 'react'import { Markdown } from 'components/interfaces/Markdown'@@ -11,8 +13,6 @@ import type {import { useProjectsQuery } from 'data/projects/projects-query'import { BASE_PATH } from 'lib/constants'import { getIntegrationConfigurationUrl } from 'lib/integration-utils'-import { ArrowRight, ExternalLink, Github } from 'lucide-react'-import Link from 'next/link'import { Badge, Button, cn } from 'ui'const ICON_STROKE_WIDTH = 2diff --git a/apps/studio/components/interfaces/Integrations/VercelGithub/ProjectLinker.tsx b/apps/studio/components/interfaces/Integrations/VercelGithub/ProjectLinker.tsxindex d19b85a2dc1..01fac072c7e 100644--- a/apps/studio/components/interfaces/Integrations/VercelGithub/ProjectLinker.tsx+++ b/apps/studio/components/interfaces/Integrations/VercelGithub/ProjectLinker.tsx@@ -164,8 +164,8 @@ const ProjectLinker = ({const oppositeMissingEntity = noSupabaseProjects ? mode : 'Supabase'return (- <div className="flex flex-col gap-4">- <div className="relative border rounded-lg p-12 bg shadow">+ <div className="flex flex-col bg border shadow rounded-lg overflow-hidden">+ <div className="relative p-12 border-b border-muted"><divclassName="absolute inset-0 bg-grid-black/5 [mask-image:linear-gradient(0deg,#fff,rgba(255,255,255,0.6))] dark:bg-grid-white/5 dark:[mask-image:linear-gradient(0deg,rgba(255,255,255,0.1),rgba(255,255,255,0.5))]"style={{ backgroundPosition: '10px 10px' }}@@ -374,7 +374,7 @@ const ProjectLinker = ({)}</div>- <div className="flex w-full justify-end gap-2">+ <div className="flex w-full justify-end gap-2 p-4 bg-surface-75">{onSkip !== undefined && (<Buttonsize="medium"diff --git a/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx b/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsxindex c9c1859e950..20c6cb31224 100644--- a/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx+++ b/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx@@ -30,6 +30,7 @@ import { useSidePanelsStateSnapshot } from 'state/side-panels'import { IntegrationConnectionItem } from '../../Integrations/VercelGithub/IntegrationConnection'import SidePanelGitHubRepoLinker from './SidePanelGitHubRepoLinker'import SidePanelVercelProjectLinker from './SidePanelVercelProjectLinker'+import { useRouter } from 'next/router'const IntegrationImageHandler = ({ title }: { title: 'vercel' | 'github' }) => {return (@@ -43,6 +44,7 @@ const IntegrationImageHandler = ({ title }: { title: 'vercel' | 'github' }) => {const IntegrationSettings = () => {const org = useSelectedOrganization()+ const router = useRouter()const canReadGithubConnection = useCheckPermissions(PermissionAction.READ,@@ -69,7 +71,7 @@ const IntegrationSettings = () => {const sidePanelsStateSnapshot = useSidePanelsStateSnapshot()const onAddGitHubConnection = useCallback(() => {- sidePanelsStateSnapshot.setGithubConnectionsOpen(true)+ router.push('/project/_/settings/integrations')}, [sidePanelsStateSnapshot])const onDeleteGitHubConnection = useCallback(diff --git a/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker.tsx b/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker.tsxindex 574ba32dbaa..609931bd89b 100644--- a/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker.tsx+++ b/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker.tsx@@ -1,20 +1,57 @@-import { useMemo } from 'react'+import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { ChevronDown, Loader2, PlusIcon } from 'lucide-react'+import { useCallback, useEffect, useMemo, useState } from 'react'+import { useForm } from 'react-hook-form'import { toast } from 'sonner'+import * as z from 'zod'-import ProjectLinker from 'components/interfaces/Integrations/VercelGithub/ProjectLinker'import { Markdown } from 'components/interfaces/Markdown'+import { useBranchCreateMutation } from 'data/branches/branch-create-mutation'+import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'+import { useBranchesQuery } from 'data/branches/branches-query'+import { useCheckGithubBranchValidity } from 'data/integrations/github-branch-check-query'import { useGitHubAuthorizationQuery } from 'data/integrations/github-authorization-query'import { useGitHubConnectionCreateMutation } from 'data/integrations/github-connection-create-mutation'import { useGitHubConnectionDeleteMutation } from 'data/integrations/github-connection-delete-mutation'+import { useGitHubConnectionUpdateMutation } from 'data/integrations/github-connection-update-mutation'import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'import { useGitHubRepositoriesQuery } from 'data/integrations/github-repositories-query'-import type { IntegrationConnectionsCreateVariables } from 'data/integrations/integrations.types'+import type { GitHubConnection } from 'data/integrations/integrations.types'import { useProjectsQuery } from 'data/projects/projects-query'+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'import { openInstallGitHubIntegrationWindow } from 'lib/github'import { EMPTY_ARR } from 'lib/void'import { useSidePanelsStateSnapshot } from 'state/side-panels'-import { Button, SidePanel } from 'ui'+import {+ Button,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandInput_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ CommandSeparator_Shadcn_,+ Command_Shadcn_,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Popover_Shadcn_,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Switch,+ cn,+} from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'const GITHUB_ICON = (<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 96" className="w-6">@@ -32,34 +69,47 @@ export type SidePanelGitHubRepoLinkerProps = {}const SidePanelGitHubRepoLinker = ({ projectRef }: SidePanelGitHubRepoLinkerProps) => {+ const selectedProject = useSelectedProject()const selectedOrganization = useSelectedOrganization()const sidePanelStateSnapshot = useSidePanelsStateSnapshot()+ const [isConfirmingBranchChange, setIsConfirmingBranchChange] = useState(false)+ const [isConfirmingRepoChange, setIsConfirmingRepoChange] = useState(false)+ const [selectedRepositoryId, setSelectedRepositoryId] = useState<string | undefined>()+ const [repoComboBoxOpen, setRepoComboboxOpen] = useState(false)+const visible = sidePanelStateSnapshot.githubConnectionsOpen+ const canUpdateGitHubConnection = useCheckPermissions(+ PermissionAction.UPDATE,+ 'integrations.github_connections'+ )+ const canCreateGitHubConnection = useCheckPermissions(+ PermissionAction.CREATE,+ 'integrations.github_connections'+ )+const { data: gitHubAuthorization, isLoading: isLoadingGitHubAuthorization } =useGitHubAuthorizationQuery({ enabled: visible })- // [Alaister]: temp override with <any> until the typegen is fixedconst { data: githubReposData, isLoading: isLoadingGitHubRepos } = useGitHubRepositoriesQuery<any[]>({enabled: visible && Boolean(gitHubAuthorization),})- /**- * Supabase projects available- */- const { data: supabaseProjectsData, isLoading: isLoadingSupabaseProjects } = useProjectsQuery({- enabled: visible,- })+ const { data: connections } = useGitHubConnectionsQuery(+ {+ organizationId: selectedOrganization?.id,+ },+ {+ enabled: visible,+ }+ )- const supabaseProjects = useMemo(- () =>- supabaseProjectsData- ?.filter((project) => project.organization_id === selectedOrganization?.id)- .map((project) => ({ name: project.name, ref: project.ref })) ?? EMPTY_ARR,- [selectedOrganization?.id, supabaseProjectsData]+ const { data: existingBranches } = useBranchesQuery(+ { projectRef: selectedProject?.ref },+ { enabled: !!selectedProject?.ref })const githubRepos = useMemo(@@ -72,108 +122,620 @@ const SidePanelGitHubRepoLinker = ({ projectRef }: SidePanelGitHubRepoLinkerProp[githubReposData])- const { data: connections } = useGitHubConnectionsQuery(- {- organizationId: selectedOrganization?.id,- },- {- enabled: visible,- }+ const existingConnection = useMemo(+ () => connections?.find((c) => c.project.ref === projectRef),+ [connections, projectRef])+ const prodBranch = existingBranches?.find((branch) => branch.is_default)++ // Mutations+ const { mutate: createBranch } = useBranchCreateMutation({+ onError: (error) => {+ console.error('Failed to enable branching:', error)+ },+ })++ const { mutate: updateBranch } = useBranchUpdateMutation()++ const { mutateAsync: checkGithubBranchValidity, isLoading: isCheckingBranch } =+ useCheckGithubBranchValidity({ onError: () => {} })+const { mutate: createConnection, isLoading: isCreatingConnection } =useGitHubConnectionCreateMutation({- onSuccess() {+ onSuccess: (data, variables) => {+ // Enable branching if not already enabled+ if (selectedProject && !selectedProject.is_branch_enabled) {+ createBranch({+ projectRef: variables.connection.project_ref,+ branchName: 'main',+ gitBranch: '',+ })+ }toast.success('Successfully linked project to repository!')- sidePanelStateSnapshot.setGithubConnectionsOpen(false)},})const { mutateAsync: deleteConnection } = useGitHubConnectionDeleteMutation()- const createGithubConnection = async (variables: IntegrationConnectionsCreateVariables) => {- if (!selectedOrganization?.id) {- throw new Error('No organization id')+ const { mutate: updateConnectionSettings, isLoading: isUpdatingConnection } =+ useGitHubConnectionUpdateMutation()++ // Form schema with validation+ const GitHubSettingsSchema = z+ .object({+ repositoryId: z.string().min(1, 'Please select a repository'),+ enableProductionSync: z.boolean().default(false),+ branchName: z.string(),+ new_branch_per_pr: z.boolean().default(false),+ supabaseDirectory: z.string().default('.'),+ supabaseChangesOnly: z.boolean().default(false),+ branchLimit: z.string().default('50'),+ })+ .superRefine(async (val, ctx) => {+ if (+ val.enableProductionSync &&+ val.branchName &&+ val.branchName.length > 0 &&+ val.repositoryId+ ) {+ try {+ await checkGithubBranchValidity({+ repositoryId: Number(val.repositoryId),+ branchName: val.branchName,+ })+ } catch (error) {+ const selectedRepo = githubRepos.find((repo) => repo.id === val.repositoryId)+ const repoName = selectedRepo?.name || 'selected repository'+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Branch "${val.branchName}" not found in ${repoName}`,+ path: ['branchName'],+ })+ }+ }+ })++ const githubSettingsForm = useForm<z.infer<typeof GitHubSettingsSchema>>({+ resolver: zodResolver(GitHubSettingsSchema),+ mode: 'onSubmit',+ reValidateMode: 'onBlur',+ defaultValues: {+ repositoryId: '',+ enableProductionSync: false,+ branchName: '',+ new_branch_per_pr: false,+ supabaseDirectory: '',+ supabaseChangesOnly: false,+ branchLimit: '50',+ },+ })++ const enableProductionSync = githubSettingsForm.watch('enableProductionSync')+ const newBranchPerPr = githubSettingsForm.watch('new_branch_per_pr')+ const currentRepositoryId = githubSettingsForm.watch('repositoryId')++ // Calculate selected repository based on current form value+ const selectedRepository = githubRepos.find(+ (repo) => repo.id === (currentRepositoryId || selectedRepositoryId)+ )++ // Initialize form when existing connection is loaded+ useEffect(() => {+ if (existingConnection) {+ const hasGitBranch = Boolean(prodBranch?.git_branch?.trim())+ const formValues = {+ repositoryId: existingConnection.repository.id.toString(),+ enableProductionSync: hasGitBranch,+ branchName: prodBranch?.git_branch || 'main',+ new_branch_per_pr: existingConnection.new_branch_per_pr,+ supabaseDirectory: existingConnection.workdir || '',+ supabaseChangesOnly: existingConnection.supabase_changes_only,+ branchLimit: String(existingConnection.branch_limit),+ }++ // Only reset if the form hasn't been modified or if the connection has actually changed+ if (+ !githubSettingsForm.formState.isDirty ||+ githubSettingsForm.getValues().repositoryId !== formValues.repositoryId+ ) {+ githubSettingsForm.reset(formValues)+ setSelectedRepositoryId(existingConnection.repository.id.toString())+ }}- if (!variables.new) {- throw new Error('No new connection')+ }, [existingConnection?.id, prodBranch?.git_branch, prodBranch?.id])++ // Handle clearing branch name when production sync is disabled+ useEffect(() => {+ if (!enableProductionSync) {+ githubSettingsForm.setValue('branchName', '')+ } else if (enableProductionSync && !githubSettingsForm.getValues().branchName) {+ githubSettingsForm.setValue('branchName', 'main')}+ }, [enableProductionSync, githubSettingsForm])- const existingConnection = connections?.find(- (connection) => connection.project.ref === projectRef- )+ const handleCreateOrUpdateConnection = async (data: z.infer<typeof GitHubSettingsSchema>) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return- if (existingConnection) {- // remove existing connection so we can recreate it or update it- try {- await deleteConnection({- organizationId: selectedOrganization.id,- connectionId: existingConnection.id,- })- } catch (error) {- // ignore the error to let createConnection handle it+ const selectedRepo = githubRepos.find((repo) => repo.id === data.repositoryId)+ if (!selectedRepo) {+ toast.error('Please select a repository')+ return+ }++ try {+ if (existingConnection) {+ // Check if repository is being changed+ const isRepoChanged = existingConnection.repository.id.toString() !== data.repositoryId+ if (isRepoChanged) {+ setIsConfirmingRepoChange(true)+ return+ }+ // Update existing connection+ await handleUpdateConnection(data, existingConnection)+ } else {+ // Create new connection+ await handleCreateConnection(data, selectedRepo)}+ } catch (error) {+ console.error('Error managing connection:', error)}+ }++ const handleCreateConnection = async (+ data: z.infer<typeof GitHubSettingsSchema>,+ selectedRepo: { id: string; installation_id: number }+ ) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return+ // Create the connectioncreateConnection({organizationId: selectedOrganization.id,- connection: variables.new,+ connection: {+ installation_id: selectedRepo.installation_id,+ project_ref: selectedProject.ref,+ repository_id: Number(selectedRepo.id),+ workdir: data.supabaseDirectory,+ supabase_changes_only: data.supabaseChangesOnly,+ branch_limit: Number(data.branchLimit),+ new_branch_per_pr: data.new_branch_per_pr,+ },})++ // Handle branch creation/update for production sync+ if (data.enableProductionSync && data.branchName) {+ if (prodBranch?.id) {+ updateBranch({+ id: prodBranch.id,+ projectRef: selectedProject.ref,+ gitBranch: data.branchName,+ })+ } else {+ // Create new branch if none exists+ createBranch({+ projectRef: selectedProject.ref,+ branchName: 'main',+ gitBranch: data.branchName,+ })+ }+ }++ toast.success('GitHub connection created successfully')+ sidePanelStateSnapshot.setGithubConnectionsOpen(false)+ }++ const handleUpdateConnection = async (+ data: z.infer<typeof GitHubSettingsSchema>,+ connection: GitHubConnection+ ) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return++ const originalBranchName = prodBranch?.git_branch++ if (originalBranchName && data.branchName !== originalBranchName && data.enableProductionSync) {+ setIsConfirmingBranchChange(true)+ return+ }++ await executeUpdate(data, connection)+ }++ const executeUpdate = async (+ data: z.infer<typeof GitHubSettingsSchema>,+ connection: GitHubConnection+ ) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return++ // Update connection settings+ updateConnectionSettings({+ connectionId: connection.id,+ organizationId: selectedOrganization.id,+ connection: {+ workdir: data.supabaseDirectory,+ supabase_changes_only: data.supabaseChangesOnly,+ branch_limit: Number(data.branchLimit),+ new_branch_per_pr: data.new_branch_per_pr,+ },+ })++ // Handle branch update+ if (prodBranch?.id) {+ updateBranch({+ id: prodBranch.id,+ projectRef: selectedProject.ref,+ gitBranch: data.enableProductionSync ? data.branchName : '',+ })+ }++ toast.success('GitHub integration updated successfully')+ setIsConfirmingBranchChange(false)+ sidePanelStateSnapshot.setGithubConnectionsOpen(false)+ }++ const onConfirmBranchChange = async () => {+ if (existingConnection) {+ await executeUpdate(githubSettingsForm.getValues(), existingConnection)+ }+ }++ const onConfirmRepoChange = async () => {+ const data = githubSettingsForm.getValues()+ const selectedRepo = githubRepos.find((repo) => repo.id === data.repositoryId)++ if (!selectedRepo || !existingConnection) return++ try {+ // Delete the existing connection+ await deleteConnection({+ organizationId: selectedOrganization!.id,+ connectionId: existingConnection.id,+ })++ // Create new connection with the new repository+ await handleCreateConnection(data, selectedRepo)++ setIsConfirmingRepoChange(false)+ } catch (error) {+ console.error('Error changing repository:', error)+ toast.error('Failed to change repository')+ }}+ const isConnected = Boolean(existingConnection)+ const isLoading = isCreatingConnection || isUpdatingConnection+return (- <SidePanel- header={'Add GitHub repository'}- size="large"- visible={visible}- hideFooter- onCancel={() => sidePanelStateSnapshot.setGithubConnectionsOpen(false)}- >- <div className="py-10 flex flex-col gap-6 bg-studio h-full">- <SidePanel.Content className="flex flex-col gap-4">- <Markdown- content={`-### Choose repository to connect to--Your access to repositories depends on your GitHub x Supabase integration setup. You can access repositories that you own, those where you're a collaborator, and those available through organizations you're a member of. Access is determined by both your personal installation and any installations made by the organizations you belong to.- `}- />-- {gitHubAuthorization === null ? (- <div className="flex flex-col items-center justify-center mt-8 relative border rounded-lg p-12 bg shadow px-20s">- <p className="text-sm text-center">- Connect your Supabase projects with your GitHub repositories- </p>- <p className="text-sm text-center text-foreground-light">- Authorize with GitHub to retrieve your GitHub repositories- </p>- <Button- className="w-min mt-3"- onClick={() => {- openInstallGitHubIntegrationWindow('authorize')- }}- >- Authorize GitHub- </Button>- </div>- ) : (- <ProjectLinker- defaultSupabaseProjectRef={projectRef}- foreignProjects={githubRepos}- supabaseProjects={supabaseProjects}- onCreateConnections={createGithubConnection}- isLoading={isCreatingConnection}- loadingForeignProjects={isLoadingGitHubRepos}- loadingSupabaseProjects={isLoadingSupabaseProjects}- integrationIcon={GITHUB_ICON}- choosePrompt="Choose GitHub Repo"- showNoEntitiesState={false}- mode="GitHub"- />- )}- </SidePanel.Content>- </div>- </SidePanel>+ <>+ <Sheet+ open={visible}+ onOpenChange={(open) => !open && sidePanelStateSnapshot.setGithubConnectionsOpen(false)}+ >+ <SheetContent size="lg" className="flex flex-col">+ <SheetHeader>+ <SheetTitle>GitHub Integration</SheetTitle>+ <SheetDescription>+ {isConnected+ ? 'Update your GitHub integration settings below.'+ : 'Connect your Supabase project to a GitHub repository to enable automatic deployments and preview branches.'}+ </SheetDescription>+ </SheetHeader>++ <div className="flex-1 overflow-y-auto px-5">+ {gitHubAuthorization === null ? (+ <div className="flex flex-col items-center justify-center mt-2 relative border rounded-lg p-12 bg shadow">+ <p className="text-sm text-center">Authorize with GitHub</p>+ <p className="text-sm text-center text-foreground-light">+ Connect your GitHub account to access and select repositories for integration.+ </p>+ <Button+ className="w-min mt-3"+ onClick={() => {+ openInstallGitHubIntegrationWindow('authorize')+ }}+ >+ Authorize GitHub+ </Button>+ </div>+ ) : (+ <Form_Shadcn_ {...githubSettingsForm}>+ <form+ onSubmit={githubSettingsForm.handleSubmit(handleCreateOrUpdateConnection)}+ className="space-y-6"+ >+ {/* Repository Selection */}+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="repositoryId"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="GitHub Repository"+ description="Select the repository to connect to your project"+ >+ <Popover_Shadcn_ open={repoComboBoxOpen} onOpenChange={setRepoComboboxOpen}>+ <PopoverTrigger_Shadcn_ asChild>+ <FormControl_Shadcn_>+ <Button+ type="default"+ className="justify-start h-[34px] w-full"+ disabled={isLoadingGitHubRepos}+ loading={isLoadingGitHubRepos}+ icon={+ <div className="bg-black shadow rounded p-1 w-6 h-6 flex justify-center items-center">+ {GITHUB_ICON}+ </div>+ }+ iconRight={+ <span className="grow flex justify-end">+ <ChevronDown />+ </span>+ }+ >+ {selectedRepository+ ? selectedRepository.name+ : 'Choose GitHub Repository'}+ </Button>+ </FormControl_Shadcn_>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0 w-80" side="bottom" align="start">+ <Command_Shadcn_>+ <CommandInput_Shadcn_ placeholder="Search repositories..." />+ <CommandList_Shadcn_ className="!max-h-[200px]">+ <CommandEmpty_Shadcn_>No repositories found.</CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ {githubRepos.map((repo, i) => (+ <CommandItem_Shadcn_+ key={repo.id}+ value={`${repo.name.replaceAll('"', '')}-${i}`}+ className="flex gap-2 items-center"+ onSelect={() => {+ setSelectedRepositoryId(repo.id)+ field.onChange(repo.id)+ setRepoComboboxOpen(false)+ }}+ >+ <div className="bg-black shadow rounded p-1 w-5 h-5 flex justify-center items-center">+ {GITHUB_ICON}+ </div>+ <span className="truncate" title={repo.name}>+ {repo.name}+ </span>+ </CommandItem_Shadcn_>+ ))}+ </CommandGroup_Shadcn_>+ <CommandSeparator_Shadcn_ />+ <CommandGroup_Shadcn_>+ <CommandItem_Shadcn_+ className="flex gap-2 items-center cursor-pointer"+ onSelect={() => openInstallGitHubIntegrationWindow('install')}+ >+ <PlusIcon size={16} />+ Add GitHub Repositories+ </CommandItem_Shadcn_>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ </FormItemLayout>+ )}+ />++ {/* Supabase Directory */}+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="supabaseDirectory"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Supabase directory"+ description="Relative path to your supabase folder"+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ placeholder="supabase"+ autoComplete="off"+ disabled={!canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ {/* Production Branch Sync Section */}+ <div className="space-y-4">+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="enableProductionSync"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Deploy to production"+ description="Deploy changes to production on push including PR merges"+ >+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={!canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <div+ className={cn(+ 'space-y-4 pl-6 border-l',+ !enableProductionSync && 'opacity-25 pointer-events-none'+ )}+ >+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="branchName"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Production branch name"+ description="The GitHub branch to sync with your production database (e.g., main, master)"+ >+ <div className="relative w-full">+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ autoComplete="off"+ disabled={!canUpdateGitHubConnection || !enableProductionSync}+ />+ </FormControl_Shadcn_>+ <div className="absolute top-2.5 right-3 flex items-center gap-2">+ {isCheckingBranch && <Loader2 size={14} className="animate-spin" />}+ </div>+ </div>+ </FormItemLayout>+ )}+ />+ </div>+ </div>++ {/* Automatic Branching Section */}+ <div className="space-y-4">+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="new_branch_per_pr"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Automatic branching"+ description="Create preview branches for every pull request"+ >+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={!canCreateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <div+ className={cn(+ 'space-y-4 pl-6 border-l',+ !newBranchPerPr && 'opacity-25 pointer-events-none'+ )}+ >+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="branchLimit"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Branch limit"+ description="Maximum number of preview branches"+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ type="number"+ autoComplete="off"+ disabled={!newBranchPerPr || !canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="supabaseChangesOnly"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Supabase changes only"+ description="Only create branches when Supabase files change"+ >+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={(val) => field.onChange(val)}+ disabled={!newBranchPerPr || !canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </div>+ </div>+ </form>+ </Form_Shadcn_>+ )}+ </div>++ <SheetFooter>+ <Button+ type="default"+ onClick={() => sidePanelStateSnapshot.setGithubConnectionsOpen(false)}+ >+ Cancel+ </Button>+ <Button+ type="primary"+ onClick={githubSettingsForm.handleSubmit(handleCreateOrUpdateConnection)}+ disabled={+ !canUpdateGitHubConnection ||+ isCheckingBranch ||+ isLoading ||+ !githubSettingsForm.formState.isDirty ||+ gitHubAuthorization === null+ }+ loading={isCheckingBranch || isLoading}+ >+ {isConnected ? 'Update integration' : 'Enable integration'}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>++ <ConfirmationModal+ variant="warning"+ visible={isConfirmingBranchChange}+ title="Changing production git branch"+ confirmLabel="Confirm"+ size="medium"+ onCancel={() => setIsConfirmingBranchChange(false)}+ onConfirm={onConfirmBranchChange}+ loading={isUpdatingConnection}+ >+ <p className="text-sm text-foreground-light">+ Open pull requests will only update your Supabase project on merge if the git base branch+ matches this new production git branch.+ </p>+ </ConfirmationModal>++ <ConfirmationModal+ variant="warning"+ visible={isConfirmingRepoChange}+ title="Changing GitHub repository"+ confirmLabel="Change repository"+ size="medium"+ onCancel={() => setIsConfirmingRepoChange(false)}+ onConfirm={onConfirmRepoChange}+ loading={isLoading}+ >+ <div className="space-y-3">+ <p className="text-sm text-foreground-light">+ This will disconnect your current repository and create a new connection with the+ selected repository.+ </p>+ <p className="text-sm text-foreground-light">+ Your existing branch settings will be preserved, but make sure the new repository+ contains the specified branches.+ </p>+ </div>+ </ConfirmationModal>+ </>)}diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsxindex fd7295905f6..2d217b8d23d 100644--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx@@ -1,375 +1,731 @@import { zodResolver } from '@hookform/resolvers/zod'-import { Check, ChevronDown, GitBranch, RotateCcw, Shield } from 'lucide-react'-import { useRef, useState } from 'react'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { ChevronDown, Loader2, PlusIcon } from 'lucide-react'+import { useCallback, useEffect, useState, useMemo } from 'react'import { useForm } from 'react-hook-form'import { toast } from 'sonner'import * as z from 'zod'-import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useBranchCreateMutation } from 'data/branches/branch-create-mutation'import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'import { useBranchesQuery } from 'data/branches/branches-query'-import { useGitHubBranchesQuery } from 'data/integrations/github-branches-query'+import { useCheckGithubBranchValidity } from 'data/integrations/github-branch-check-query'+import { useGitHubAuthorizationQuery } from 'data/integrations/github-authorization-query'+import { useGitHubConnectionCreateMutation } from 'data/integrations/github-connection-create-mutation'+import { useGitHubConnectionDeleteMutation } from 'data/integrations/github-connection-delete-mutation'import { useGitHubConnectionUpdateMutation } from 'data/integrations/github-connection-update-mutation'-import type { IntegrationProjectConnection } from 'data/integrations/integrations.types'+import { useGitHubRepositoriesQuery } from 'data/integrations/github-repositories-query'+import type { GitHubConnection } from 'data/integrations/integrations.types'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { openInstallGitHubIntegrationWindow } from 'lib/github'+import { EMPTY_ARR } from 'lib/void'import {- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,Button,+ Card,+ CardContent,+ CardFooter,+ cn,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Switch,CommandEmpty_Shadcn_,CommandGroup_Shadcn_,CommandInput_Shadcn_,CommandItem_Shadcn_,CommandList_Shadcn_,Command_Shadcn_,- FormControl_Shadcn_,- FormDescription_Shadcn_,- FormField_Shadcn_,- FormItem_Shadcn_,- FormLabel_Shadcn_,- Form_Shadcn_,- Input_Shadcn_,- Label_Shadcn_,PopoverContent_Shadcn_,PopoverTrigger_Shadcn_,Popover_Shadcn_,- Switch,- WarningIcon,- cn,} from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++const GITHUB_ICON = (+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 96" className="w-6">+ <path+ fill="#ffffff"+ fillRule="evenodd"+ d="M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z"+ clipRule="evenodd"+ />+ </svg>+)interface GitHubIntegrationConnectionFormProps {disabled?: boolean- connection: IntegrationProjectConnection+ connection?: GitHubConnection}const GitHubIntegrationConnectionForm = ({- disabled,+ disabled = false,connection,}: GitHubIntegrationConnectionFormProps) => {- const org = useSelectedOrganization()- const project = useSelectedProject()- const [open, setOpen] = useState(false)- const comboBoxRef = useRef<HTMLButtonElement>(null)- const isBranchingEnabled =- project?.is_branch_enabled === true || project?.parent_project_ref !== undefined+ const selectedProject = useSelectedProject()+ const selectedOrganization = useSelectedOrganization()+ const [isConfirmingBranchChange, setIsConfirmingBranchChange] = useState(false)+ const [isConfirmingRepoChange, setIsConfirmingRepoChange] = useState(false)+ const [repoComboBoxOpen, setRepoComboboxOpen] = useState(false)+ const isParentProject = !Boolean(selectedProject?.parent_project_ref)const canUpdateGitHubConnection = useCheckPermissions(PermissionAction.UPDATE,'integrations.github_connections')+ const canCreateGitHubConnection = useCheckPermissions(+ PermissionAction.CREATE,+ 'integrations.github_connections'+ )- const { data: githubBranches, isLoading: isLoadingBranches } = useGitHubBranchesQuery(- {- connectionId: Number(connection.id),+ const { data: gitHubAuthorization, isLoading: isLoadingGitHubAuthorization } =+ useGitHubAuthorizationQuery()++ const { data: githubReposData, isLoading: isLoadingGitHubRepos } = useGitHubRepositoriesQuery<+ any[]+ >({+ enabled: Boolean(gitHubAuthorization),+ })++ const { mutate: updateBranch } = useBranchUpdateMutation()+ const { mutate: createBranch } = useBranchCreateMutation({+ onError: (error) => {+ console.error('Failed to enable branching:', error)},- { enabled: isBranchingEnabled }+ })++ const { data: existingBranches } = useBranchesQuery(+ { projectRef: selectedProject?.ref },+ { enabled: !!selectedProject?.ref })- const { mutate: updateConnection, isLoading: isUpdatingConnection } =- useGitHubConnectionUpdateMutation({- onSuccess: () => toast.success('Successfully updated connection settings'),+ const { mutateAsync: checkGithubBranchValidity, isLoading: isCheckingBranch } =+ useCheckGithubBranchValidity({ onError: () => {} })++ const { mutate: createConnection, isLoading: isCreatingConnection } =+ useGitHubConnectionCreateMutation()++ const { mutateAsync: deleteConnection, isLoading: isDeletingConnection } =+ useGitHubConnectionDeleteMutation({+ onSuccess: () => {+ toast.success('Successfully removed GitHub integration')+ },})- const { mutate: updateBranch, isLoading: isUpdatingProdBranch } = useBranchUpdateMutation({- onSuccess: (data) => {- toast.success(`Successfully updated production branch to ${data.git_branch}`)- setOpen(false)- },- })+ const { mutate: updateConnectionSettings, isLoading: isUpdatingConnection } =+ useGitHubConnectionUpdateMutation()- const { data: previewBranches } = useBranchesQuery(- { projectRef: project?.parentRef },- { enabled: project !== undefined }+ const githubRepos = useMemo(+ () =>+ githubReposData?.map((repo: any) => ({+ id: repo.id.toString(),+ name: repo.name,+ installation_id: repo.installation_id,+ default_branch: repo.default_branch || 'main',+ })) ?? EMPTY_ARR,+ [githubReposData])- const productionPreviewBranch = previewBranches?.find((branch) => branch.is_default)+ const prodBranch = existingBranches?.find((branch) => branch.is_default)- function onUpdateProductionBranch(branchName: string) {- if (!project?.parentRef) return- if (!productionPreviewBranch) return- updateBranch({- id: productionPreviewBranch.id,- projectRef: project.parentRef,- branchName: branchName,- gitBranch: branchName,+ // Combined GitHub Settings Form+ const GitHubSettingsSchema = z+ .object({+ repositoryId: z.string().min(1, 'Please select a repository'),+ enableProductionSync: z.boolean().default(true),+ branchName: z.string().default('main'),+ new_branch_per_pr: z.boolean().default(true),+ supabaseDirectory: z.string().default('.'),+ supabaseChangesOnly: z.boolean().default(true),+ branchLimit: z.string().default('50'),+ })+ .superRefine(async (val, ctx) => {+ if (val.enableProductionSync && val.branchName && val.branchName.length > 0) {+ const repositoryId = val.repositoryId || connection?.repository.id.toString()+ if (repositoryId) {+ try {+ await checkGithubBranchValidity({+ repositoryId: Number(repositoryId),+ branchName: val.branchName,+ })+ } catch (error) {+ const selectedRepo = githubRepos.find((repo) => repo.id === repositoryId)+ const repoName =+ selectedRepo?.name || connection?.repository.name || 'selected repository'+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Branch "${val.branchName}" not found in ${repoName}`,+ path: ['branchName'],+ })+ }+ }+ }})- }- const FormSchema = z.object({- supabaseDirectory: z- .string()- .default(connection.metadata?.supabaseConfig?.supabaseDirectory ?? ''),- supabaseChangesOnly: z- .boolean()- .default(connection.metadata?.supabaseConfig?.supabaseChangesOnly ?? false),- branchLimit: z.string().default(String(connection.metadata?.supabaseConfig?.branchLimit ?? 50)),- })- const form = useForm<z.infer<typeof FormSchema>>({- resolver: zodResolver(FormSchema),+ const githubSettingsForm = useForm<z.infer<typeof GitHubSettingsSchema>>({+ resolver: zodResolver(GitHubSettingsSchema),+ mode: 'onSubmit',+ reValidateMode: 'onBlur',defaultValues: {- supabaseDirectory: connection?.metadata?.supabaseConfig?.supabaseDirectory,- supabaseChangesOnly: connection?.metadata?.supabaseConfig?.supabaseChangesOnly,- branchLimit: String(connection?.metadata?.supabaseConfig?.branchLimit),+ repositoryId: connection?.repository.id.toString() || '',+ enableProductionSync: true,+ branchName: 'main',+ new_branch_per_pr: true,+ supabaseDirectory: '.',+ supabaseChangesOnly: true,+ branchLimit: '50',},})- function onSubmit(data: z.infer<typeof FormSchema>) {- if (org?.id === undefined) return console.error('Org ID is required')- updateConnection({- connectionId: connection.id,- organizationId: org?.id,- workdir: data.supabaseDirectory,- supabaseChangesOnly: data.supabaseChangesOnly,- branchLimit: Number(data.branchLimit),+ const enableProductionSync = githubSettingsForm.watch('enableProductionSync')+ const newBranchPerPr = githubSettingsForm.watch('new_branch_per_pr')+ const currentRepositoryId = githubSettingsForm.watch('repositoryId')++ // Calculate selected repository based on current form value+ const selectedRepository = githubRepos.find((repo) => repo.id === currentRepositoryId)++ const handleCreateOrUpdateConnection = async (data: z.infer<typeof GitHubSettingsSchema>) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return++ try {+ if (connection) {+ // Check if repository is being changed+ if (connection.repository.id.toString() !== data.repositoryId) {+ setIsConfirmingRepoChange(true)+ return+ }+ // Update existing connection+ await handleUpdateConnection(data, connection)+ } else {+ // Create new connection+ const selectedRepo = githubRepos.find((repo) => repo.id === data.repositoryId)+ if (!selectedRepo) {+ toast.error('Please select a repository')+ return+ }+ await handleCreateConnection(data, selectedRepo)+ }+ } catch (error) {+ console.error('Error managing connection:', error)+ }+ }++ const handleCreateConnection = async (+ data: z.infer<typeof GitHubSettingsSchema>,+ selectedRepo: { id: string; installation_id: number }+ ) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return++ createConnection({+ organizationId: selectedOrganization.id,+ connection: {+ installation_id: selectedRepo.installation_id,+ project_ref: selectedProject.ref,+ repository_id: Number(selectedRepo.id),+ workdir: data.supabaseDirectory,+ supabase_changes_only: data.supabaseChangesOnly,+ branch_limit: Number(data.branchLimit),+ new_branch_per_pr: data.new_branch_per_pr,+ },})++ if (!prodBranch?.id) {+ createBranch({+ projectRef: selectedProject.ref,+ branchName: 'main',+ gitBranch: data.branchName,+ is_default: true,+ })+ } else {+ updateBranch({+ id: prodBranch.id,+ projectRef: selectedProject.ref,+ gitBranch: data.branchName,+ })+ }+ toast.success('GitHub integration successfully updated')}- return (- <div className="flex flex-col gap-6 px-6 py-4">- {isBranchingEnabled ? (- <div>- <Label_Shadcn_ className="text-foreground">Production branch</Label_Shadcn_>- <p className="text-xs text-foreground-light mb-3">- All other branches will be treated as Preview branches+ const handleUpdateConnection = async (+ data: z.infer<typeof GitHubSettingsSchema>,+ currentConnection: GitHubConnection+ ) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return++ const originalBranchName = prodBranch?.git_branch++ if (originalBranchName && data.branchName !== originalBranchName && data.enableProductionSync) {+ setIsConfirmingBranchChange(true)+ return+ }++ await executeUpdate(data, currentConnection)+ }++ const executeUpdate = async (+ data: z.infer<typeof GitHubSettingsSchema>,+ currentConnection: GitHubConnection+ ) => {+ if (!selectedProject?.ref || !selectedOrganization?.id) return++ updateConnectionSettings({+ connectionId: currentConnection.id,+ organizationId: selectedOrganization.id,+ connection: {+ workdir: data.supabaseDirectory,+ supabase_changes_only: data.supabaseChangesOnly,+ branch_limit: Number(data.branchLimit),+ new_branch_per_pr: data.new_branch_per_pr,+ },+ })++ if (prodBranch?.id) {+ updateBranch({+ id: prodBranch.id,+ projectRef: selectedProject.ref,+ gitBranch: data.enableProductionSync ? data.branchName : '',+ })+ }++ toast.success('GitHub integration successfully updated')+ setIsConfirmingBranchChange(false)+ }++ const onConfirmBranchChange = async () => {+ if (connection) {+ await executeUpdate(githubSettingsForm.getValues(), connection)+ }+ }++ const handleRemoveIntegration = async () => {+ if (!connection || !selectedOrganization?.id) return++ try {+ await deleteConnection({+ organizationId: selectedOrganization.id,+ connectionId: connection.id,+ })++ githubSettingsForm.reset({+ repositoryId: '',+ enableProductionSync: true,+ branchName: 'main',+ new_branch_per_pr: true,+ supabaseDirectory: '.',+ supabaseChangesOnly: true,+ branchLimit: '50',+ })+ } catch (error) {+ console.error('Error removing integration:', error)+ toast.error('Failed to remove integration')+ }+ }++ const onConfirmRepoChange = async () => {+ const data = githubSettingsForm.getValues()+ const selectedRepo = githubRepos.find((repo) => repo.id === data.repositoryId)++ if (!selectedRepo || !connection) return++ try {+ await deleteConnection({+ organizationId: selectedOrganization!.id,+ connectionId: connection.id,+ })++ await handleCreateConnection(data, selectedRepo)++ setIsConfirmingRepoChange(false)+ } catch (error) {+ console.error('Error changing repository:', error)+ toast.error('Failed to change repository')+ }+ }++ useEffect(() => {+ if (selectedRepository) {+ githubSettingsForm.setValue(+ 'branchName',+ githubRepos.find((repo) => repo.id === selectedRepository.id)?.default_branch || 'main'+ )+ }+ }, [selectedRepository])++ useEffect(() => {+ if (connection) {+ const hasGitBranch = Boolean(prodBranch?.git_branch?.trim())++ githubSettingsForm.reset({+ repositoryId: connection.repository.id.toString(),+ enableProductionSync: hasGitBranch,+ branchName: prodBranch?.git_branch || 'main',+ new_branch_per_pr: connection.new_branch_per_pr,+ supabaseDirectory: connection.workdir || '',+ supabaseChangesOnly: connection.supabase_changes_only,+ branchLimit: String(connection.branch_limit),+ })+ }+ }, [connection, prodBranch, githubSettingsForm])++ // Handle clearing branch name when production sync is disabled+ useEffect(() => {+ if (!enableProductionSync) {+ githubSettingsForm.setValue('branchName', '')+ } else if (enableProductionSync && !githubSettingsForm.getValues().branchName) {+ githubSettingsForm.setValue('branchName', 'main')+ }+ }, [enableProductionSync, githubSettingsForm])++ // Show authorization prompt if not authorized+ if (gitHubAuthorization === null) {+ return (+ <Card>+ <CardContent className="flex flex-col items-center justify-center py-12">+ <p className="text-sm text-center">Authorize with GitHub</p>+ <p className="text-sm text-center text-foreground-light mb-4">+ Connect your GitHub account to access and select repositories for integration.</p>+ <Button+ onClick={() => {+ openInstallGitHubIntegrationWindow('authorize')+ }}+ >+ Authorize GitHub+ </Button>+ </CardContent>+ </Card>+ )+ }++ const isLoading = isCreatingConnection || isUpdatingConnection || isDeletingConnection- <Alert_Shadcn_>- <AlertTitle_Shadcn_ className="text-sm">- Changing Git branch for Production Branch coming soon- </AlertTitle_Shadcn_>- <AlertDescription_Shadcn_ className="text-xs">- If you wish to change the Git branch that is used for the Production Branch you will- need to disable Branching and opt back in.- </AlertDescription_Shadcn_>- </Alert_Shadcn_>-- {/* <pre>! This should only work if branching is turned on !</pre> */}-- <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>- <PopoverTrigger_Shadcn_ asChild name="branch-selector">- <Button- disabled- type="default"- size="medium"- ref={comboBoxRef}- className={cn(- 'justify-start w-80 mt-4',- productionPreviewBranch?.git_branch === undefined- ? 'text-foreground-light'- : 'text'+ return (+ <>+ <Form_Shadcn_ {...githubSettingsForm}>+ <form+ onSubmit={githubSettingsForm.handleSubmit(handleCreateOrUpdateConnection)}+ className={cn(!isParentProject && 'opacity-25 pointer-events-none')}+ >+ <Card>+ <CardContent className="space-y-6">+ {/* Repository Selection */}+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="repositoryId"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="GitHub Repository"+ description={+ connection+ ? 'Change the connected repository'+ : 'Select the repository to connect to your project'+ }+ >+ <Popover_Shadcn_ open={repoComboBoxOpen} onOpenChange={setRepoComboboxOpen}>+ <PopoverTrigger_Shadcn_ asChild>+ <FormControl_Shadcn_>+ <Button+ type="default"+ className="justify-start h-[34px] w-full"+ disabled={isLoadingGitHubRepos}+ loading={isLoadingGitHubRepos}+ icon={+ <div className="bg-black shadow rounded p-1 w-6 h-6 flex justify-center items-center">+ {GITHUB_ICON}+ </div>+ }+ iconRight={+ <span className="grow flex justify-end">+ <ChevronDown />+ </span>+ }+ >+ {selectedRepository || connection+ ? selectedRepository?.name || connection?.repository.name+ : 'Choose GitHub Repository'}+ </Button>+ </FormControl_Shadcn_>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0 w-80" side="bottom" align="start">+ <Command_Shadcn_>+ <CommandInput_Shadcn_ placeholder="Search repositories..." />+ <CommandList_Shadcn_ className="!max-h-[200px]">+ <CommandEmpty_Shadcn_>No repositories found.</CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ {githubRepos.map((repo, i) => (+ <CommandItem_Shadcn_+ key={repo.id}+ value={`${repo.name.replaceAll('"', '')}-${i}`}+ className="flex gap-2 items-center"+ onSelect={() => {+ field.onChange(repo.id)+ setRepoComboboxOpen(false)+ }}+ >+ <div className="bg-black shadow rounded p-1 w-5 h-5 flex justify-center items-center">+ {GITHUB_ICON}+ </div>+ <span className="truncate" title={repo.name}>+ {repo.name}+ </span>+ </CommandItem_Shadcn_>+ ))}+ </CommandGroup_Shadcn_>+ <CommandGroup_Shadcn_>+ <CommandItem_Shadcn_+ className="flex gap-2 items-center cursor-pointer"+ onSelect={() => openInstallGitHubIntegrationWindow('install')}+ >+ <PlusIcon size={16} />+ Add GitHub Repositories+ </CommandItem_Shadcn_>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ </FormItemLayout>)}- icon={- productionPreviewBranch?.git_branch && (- <Shield className="w-4 h-4 text-warning" strokeWidth={1} />- )- }- loading={isUpdatingProdBranch || isLoadingBranches}- iconRight={- <span className="grow flex justify-end">- <ChevronDown size={14} />- </span>- }- >- {productionPreviewBranch?.git_branch || 'Select a branch'}- </Button>- </PopoverTrigger_Shadcn_>- <PopoverContent_Shadcn_- className="p-0"- side="bottom"- align="start"- style={{ width: comboBoxRef.current?.offsetWidth }}- >- <Command_Shadcn_>- <CommandInput_Shadcn_ placeholder="Find branch..." />- <CommandList_Shadcn_>- <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>- <CommandGroup_Shadcn_>- {githubBranches?.map((branch) => {- const active = branch.name === productionPreviewBranch?.git_branch- return (- <CommandItem_Shadcn_- key={branch.name}- value={(branch.name as string).replaceAll('"', '')}- className="cursor-pointer w-full flex items-center justify-between"- onSelect={() => {- setOpen(false)- onUpdateProductionBranch(branch.name)- }}- >- <div className="flex items-center gap-2">- {active ? (- <Shield className="w-4 h-4 text-warning" strokeWidth={1} />- ) : (- <GitBranch className="w-4 h-4" strokeWidth={1} />- )}- {branch.name}- </div>- {branch.name === productionPreviewBranch?.git_branch && <Check />}- </CommandItem_Shadcn_>- )- })}- </CommandGroup_Shadcn_>- </CommandList_Shadcn_>- </Command_Shadcn_>- </PopoverContent_Shadcn_>- </Popover_Shadcn_>- </div>- ) : (- <Alert_Shadcn_ className="w-full mb-0" variant="warning">- <WarningIcon />- <div>- <AlertTitle_Shadcn_ className="text-sm">Branching is not enabled</AlertTitle_Shadcn_>- <AlertDescription_Shadcn_ className="text-xs">- This integration has no effect without Branching feature being active.- <br />- Make sure to enable it using "Enable branching" button at the top of the page first.- </AlertDescription_Shadcn_>- </div>- </Alert_Shadcn_>- )}-- <Form_Shadcn_ {...form}>- <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">- <FormField_Shadcn_- control={form.control}- name="branchLimit"- render={({ field }) => (- <FormItem_Shadcn_ className="flex flex-col">- <FormLabel_Shadcn_ className="!text">Branch limit</FormLabel_Shadcn_>- <FormDescription_Shadcn_ className="text-xs text-foreground-lighter !mt-0 !mb-1">- Total number of branches that can be automatically created for this connection.- </FormDescription_Shadcn_>- <FormControl_Shadcn_ className="flex gap-3 items-center">- <div className="relative">- <Input_Shadcn_- {...field}- className="w-80"- disabled={disabled || !canUpdateGitHubConnection}- onKeyPress={(event) => {- if (event.key === 'Escape') form.reset()- }}- type="number"- />- <RotateCcw- className={cn(- 'text-foreground-lighter transition hover:text cursor-pointer',- 'w-4 h-4 absolute right-3 top-3',- 'duration-150',-- field.value !== String(connection.metadata?.supabaseConfig?.branchLimit)- ? 'opacity-100 transition'- : 'opacity-0'- )}- onClick={() => form.reset()}- />- <Button- loading={isUpdatingConnection}- className={cn(- 'duration-150 transition',- field.value !== String(connection.metadata?.supabaseConfig?.branchLimit)- ? 'opacity-100'- : 'opacity-0'- )}- htmlType="submit"- disabled={- field.value === String(connection.metadata?.supabaseConfig?.branchLimit)- }+ />+ </CardContent>+ <CardContent className={cn(!currentRepositoryId && 'opacity-25 pointer-events-none')}>+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="supabaseDirectory"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Supabase directory"+ description="Relative path to your supabase folder"+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ placeholder="supabase"+ autoComplete="off"+ disabled={disabled || !canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </CardContent>+ <CardContent className={cn(!currentRepositoryId && 'opacity-25 pointer-events-none')}>+ {/* Production Branch Sync Section */}+ <div className="space-y-4">+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="enableProductionSync"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Deploy to production"+ description="Deploy changes to production on push including PR merges">- Update- </Button>- </div>- </FormControl_Shadcn_>- </FormItem_Shadcn_>- )}- />-- <FormField_Shadcn_- control={form.control}- name="supabaseDirectory"- render={({ field }) => (- <FormItem_Shadcn_ className="flex flex-col">- <FormLabel_Shadcn_ className="!text">Supabase directory</FormLabel_Shadcn_>- <FormDescription_Shadcn_ className="text-xs text-foreground-lighter !mt-0 !mb-1">- Path in your repository where <code>supabase</code> directory for this connection- lives.- </FormDescription_Shadcn_>- <FormControl_Shadcn_ className="flex gap-3 items-center">- <div className="relative">- <Input_Shadcn_- {...field}- disabled={disabled || !canUpdateGitHubConnection}- className="w-80"- onKeyPress={(event) => {- if (event.key === 'Escape') form.reset()- }}- />- <RotateCcw- className={cn(- 'text-foreground-lighter transition hover:text cursor-pointer',- 'w-4 h-4 absolute right-3 top-3',- 'duration-150',-- field.value !== connection.metadata?.supabaseConfig?.supabaseDirectory- ? 'opacity-100 transition'- : 'opacity-0'- )}- onClick={() => form.reset()}- />- <Button- loading={isUpdatingConnection}- className={cn(- 'duration-150 transition',- field.value !== connection.metadata?.supabaseConfig?.supabaseDirectory- ? 'opacity-100'- : 'opacity-0'- )}- htmlType="submit"- disabled={- field.value === '' ||- field.value === connection.metadata?.supabaseConfig?.supabaseDirectory- }+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={disabled || !canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <div+ className={cn(+ 'space-y-4 pl-6 border-l',+ (!enableProductionSync || disabled) && 'opacity-25 pointer-events-none'+ )}+ >+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="branchName"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Production branch name"+ description="The GitHub branch to sync with your production database (e.g., main, master)"+ >+ <div className="relative w-full">+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ autoComplete="off"+ disabled={+ disabled || !canUpdateGitHubConnection || !enableProductionSync+ }+ />+ </FormControl_Shadcn_>+ <div className="absolute top-2.5 right-3 flex items-center gap-2">+ {isCheckingBranch && <Loader2 size={14} className="animate-spin" />}+ </div>+ </div>+ </FormItemLayout>+ )}+ />+ </div>+ </div>+ </CardContent>+ <CardContent className={cn(!currentRepositoryId && 'opacity-25 pointer-events-none')}>+ {/* Automatic Branching Section */}+ <div className="space-y-4">+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="new_branch_per_pr"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Automatic branching"+ description="Create preview branches for every pull request">- Update- </Button>- </div>- </FormControl_Shadcn_>- </FormItem_Shadcn_>- )}- />-- <FormField_Shadcn_- control={form.control}- name="supabaseChangesOnly"- render={({ field }) => (- <FormItem_Shadcn_ className="space-y-0 flex gap-x-4">- <FormControl_Shadcn_>- <Switch- className="mt-1"- disabled={disabled || !canUpdateGitHubConnection}- checked={field.value}- onCheckedChange={(e) => {- field.onChange(e)- form.handleSubmit(onSubmit)()- }}+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={disabled || !canCreateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <div+ className={cn(+ 'space-y-4 pl-6 border-l',+ (!newBranchPerPr || disabled) && 'opacity-25 pointer-events-none'+ )}+ >+ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="branchLimit"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Branch limit"+ description="Maximum number of preview branches"+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ type="number"+ autoComplete="off"+ disabled={!newBranchPerPr || disabled || !canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ control={githubSettingsForm.control}+ name="supabaseChangesOnly"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Supabase changes only"+ description="Only create branches when Supabase files change"+ >+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={(val) => field.onChange(val)}+ disabled={!newBranchPerPr || disabled || !canUpdateGitHubConnection}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}/>- </FormControl_Shadcn_>- <div>- <FormLabel_Shadcn_ className="!text">Supabase changes only</FormLabel_Shadcn_>- <FormDescription_Shadcn_ className="text-xs text-foreground-lighter">- Trigger branch creation only when there were changes to <code>supabase</code>{' '}- directory.- </FormDescription_Shadcn_></div>- </FormItem_Shadcn_>- )}- />+ </div>+ </CardContent>+ <CardFooter className="flex justify-between items-center">+ <div>+ {connection && (+ <Button+ type="outline"+ onClick={handleRemoveIntegration}+ disabled={disabled || isDeletingConnection}+ loading={isDeletingConnection}+ >+ Disable integration+ </Button>+ )}+ </div>+ <div className="flex space-x-2">+ {githubSettingsForm.formState.isDirty && (+ <Button+ type="default"+ onClick={() => {+ githubSettingsForm.reset()+ }}+ disabled={disabled || !canUpdateGitHubConnection}+ >+ Cancel+ </Button>+ )}+ <Button+ type="primary"+ htmlType="submit"+ disabled={+ disabled ||+ (!connection && !canCreateGitHubConnection) ||+ (connection && !canUpdateGitHubConnection) ||+ isCheckingBranch ||+ isLoading ||+ (!connection && !githubSettingsForm.getValues().repositoryId) ||+ (connection && !githubSettingsForm.formState.isDirty)+ }+ loading={isCheckingBranch || isLoading}+ >+ {connection ? 'Save changes' : 'Enable integration'}+ </Button>+ </div>+ </CardFooter>+ </Card></form></Form_Shadcn_>- </div>++ <ConfirmationModal+ variant="warning"+ visible={isConfirmingBranchChange}+ title="Changing production git branch"+ confirmLabel="Confirm"+ size="medium"+ onCancel={() => setIsConfirmingBranchChange(false)}+ onConfirm={onConfirmBranchChange}+ loading={isUpdatingConnection}+ >+ <p className="text-sm text-foreground-light">+ Open pull requests will only update your Supabase project on merge if the git base branch+ matches this new production git branch.+ </p>+ </ConfirmationModal>++ <ConfirmationModal+ variant="warning"+ visible={isConfirmingRepoChange}+ title="Changing GitHub repository"+ confirmLabel="Change repository"+ size="medium"+ onCancel={() => setIsConfirmingRepoChange(false)}+ onConfirm={onConfirmRepoChange}+ loading={isLoading}+ >+ <div className="space-y-3">+ <p className="text-sm text-foreground-light">+ This will disconnect your current repository and create a new connection with the+ selected repository. All existing Supabase branches that are connected to the old+ repository will no longer be synced.+ </p>+ </div>+ </ConfirmationModal>+ </>)}diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsxnew file mode 100644index 00000000000..b120389a4e4--- /dev/null+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsx@@ -0,0 +1,99 @@+import { useRouter } from 'next/router'+import { CheckCircle2, Settings, AlertCircle } from 'lucide-react'+import Image from 'next/image'++import { useParams } from 'common'+import { useBranchesQuery } from 'data/branches/branches-query'+import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { BASE_PATH } from 'lib/constants'+import { Button, Card, CardContent } from 'ui'+import Link from 'next/link'++export const GitHubStatus = () => {+ const { ref: projectRef } = useParams()+ const selectedProject = useSelectedProject()+ const selectedOrganization = useSelectedOrganization()+ const parentProjectRef = selectedProject?.parent_project_ref || projectRef++ const { data: connections } = useGitHubConnectionsQuery(+ { organizationId: selectedOrganization?.id },+ { enabled: !!selectedOrganization?.id }+ )++ const { data: branches } = useBranchesQuery(+ { projectRef: parentProjectRef },+ { enabled: !!parentProjectRef }+ )++ const githubConnection = connections?.find(+ (connection) => connection.project.ref === parentProjectRef+ )+ const mainBranch = branches?.find((branch) => branch.is_default)++ const isConnected = Boolean(githubConnection)+ const hasGitBranchSync = Boolean(mainBranch?.git_branch?.trim())+ const hasAutomaticBranching = Boolean(githubConnection?.new_branch_per_pr)++ return (+ <Card>+ <CardContent className="flex items-center justify-between">+ <div className="flex items-center gap-4">+ <Image+ className="dark:invert"+ src={`${BASE_PATH}/img/icons/github-icon.svg`}+ width={20}+ height={20}+ alt="GitHub"+ />++ <div className="flex flex-col gap-1">+ <h3 className="text-sm text-foreground">+ {isConnected+ ? `Connected to ${githubConnection?.repository.name}`+ : 'GitHub Integration'}+ </h3>++ <div className="flex items-center gap-4 text-xs text-foreground-light">+ {isConnected ? (+ <>+ <div className="flex items-center gap-1">+ {hasGitBranchSync ? (+ <CheckCircle2 size={12} className="text-brand-600" />+ ) : (+ <AlertCircle size={12} className="text-warning-600" />+ )}+ <span>+ {hasGitBranchSync+ ? `Syncing production (${mainBranch?.git_branch})`+ : 'Production sync disabled'}+ </span>+ </div>+ <div className="flex items-center gap-1">+ {hasAutomaticBranching ? (+ <CheckCircle2 size={12} className="text-brand-600" />+ ) : (+ <AlertCircle size={12} className="text-warning-600" />+ )}+ <span>+ {hasAutomaticBranching+ ? 'Automatically creating branches'+ : 'Automatic branching disabled'}+ </span>+ </div>+ </>+ ) : (+ <span>Not connected to any repository</span>+ )}+ </div>+ </div>+ </div>++ <Button asChild type="default" icon={<Settings size={14} />}>+ <Link href={`/project/${projectRef}/settings/integrations`}>Configure</Link>+ </Button>+ </CardContent>+ </Card>+ )+}diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsxindex ee471a1b3dd..23d30c995a4 100644--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsx@@ -1,11 +1,7 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useCallback } from 'react'-import { toast } from 'sonner'+import { useMemo } from 'react'import { useParams } from 'common'-import { IntegrationConnectionItem } from 'components/interfaces/Integrations/VercelGithub/IntegrationConnection'-import { EmptyIntegrationConnection } from 'components/interfaces/Integrations/VercelGithub/IntegrationPanels'-import { Markdown } from 'components/interfaces/Markdown'import {ScaffoldContainer,ScaffoldSection,@@ -13,168 +9,78 @@ import {ScaffoldSectionDetail,} from 'components/layouts/Scaffold'import NoPermission from 'components/ui/NoPermission'-import { useGitHubConnectionDeleteMutation } from 'data/integrations/github-connection-delete-mutation'import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'-import type {- IntegrationName,- IntegrationProjectConnection,-} from 'data/integrations/integrations.types'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'-import { useSelectedProject } from 'hooks/misc/useSelectedProject'-import { useSidePanelsStateSnapshot } from 'state/side-panels'-import { IntegrationImageHandler } from '../IntegrationsSettings'+import { BASE_PATH } from 'lib/constants'import GitHubIntegrationConnectionForm from './GitHubIntegrationConnectionForm'-const GitHubTitle = `GitHub Connections`--const GitHubDetailsSection = `-Connect any of your GitHub repositories to a project.-`--const GitHubContentSectionTop = `--### How will GitHub connections work?--You will be able to connect a GitHub repository to a Supabase project.-The GitHub app will watch for changes in your repository such as file changes, branch changes as well as pull request activity.-`+const IntegrationImageHandler = ({ title }: { title: 'vercel' | 'github' }) => {+ return (+ <img+ className="border rounded-lg shadow w-full sm:w-48 mt-6 border-body"+ src={`${BASE_PATH}/img/integrations/covers/${title}-cover.png`}+ alt={`${title} cover`}+ />+ )+}const GitHubSection = () => {const { ref: projectRef } = useParams()- const project = useSelectedProject()- const org = useSelectedOrganization()- const sidePanelsStateSnapshot = useSidePanelsStateSnapshot()- const isBranch = project?.parent_project_ref !== undefined+ const selectedOrganization = useSelectedOrganization()const canReadGitHubConnection = useCheckPermissions(PermissionAction.READ,'integrations.github_connections')- const canCreateGitHubConnection = useCheckPermissions(- PermissionAction.CREATE,- 'integrations.github_connections'- )- const canUpdateGitHubConnection = useCheckPermissions(- PermissionAction.UPDATE,- 'integrations.github_connections'- )-- const { data: allConnections } = useGitHubConnectionsQuery({ organizationId: org?.id })-- const { mutateAsync: deleteGitHubConnection } = useGitHubConnectionDeleteMutation({- onSuccess: () => {- toast.success('Successfully deleted Github connection')- },- })- const connections =- allConnections?.filter((connection) =>- isBranch- ? connection.project.ref === project.parent_project_ref- : connection.project.ref === projectRef- ) ?? []-- const onAddGitHubConnection = useCallback(() => {- sidePanelsStateSnapshot.setGithubConnectionsOpen(true)- }, [sidePanelsStateSnapshot])+ const { data: connections } = useGitHubConnectionsQuery(+ { organizationId: selectedOrganization?.id },+ { enabled: !!projectRef && !!selectedOrganization?.id }+ )- const onDeleteGitHubConnection = useCallback(- async (connection: IntegrationProjectConnection) => {- if (!org?.id) {- toast.error('Organization not found')- return- }- await deleteGitHubConnection({ connectionId: connection.id, organizationId: org.id })- },- [deleteGitHubConnection, org?.id]+ const existingConnection = useMemo(+ () => connections?.find((c) => c.project.ref === projectRef),+ [connections, projectRef])+ const GitHubTitle = `GitHub Integration`++ if (!canReadGitHubConnection) {+ return (+ <ScaffoldContainer>+ <ScaffoldSection>+ <ScaffoldSectionDetail title={GitHubTitle}>+ <p>Connect any of your GitHub repositories to a project.</p>+ <IntegrationImageHandler title="github" />+ </ScaffoldSectionDetail>+ <ScaffoldSectionContent>+ <NoPermission resourceText="view this organization's GitHub connections" />+ </ScaffoldSectionContent>+ </ScaffoldSection>+ </ScaffoldContainer>+ )+ }+return (<ScaffoldContainer><ScaffoldSection><ScaffoldSectionDetail title={GitHubTitle}>- <Markdown content={GitHubDetailsSection} />+ <p>Connect any of your GitHub repositories to a project.</p><IntegrationImageHandler title="github" /></ScaffoldSectionDetail><ScaffoldSectionContent>- {!canReadGitHubConnection ? (- <NoPermission resourceText="view this organization's GitHub connections" />- ) : (- <>- <Markdown content={GitHubContentSectionTop} />- {connections.length > 0 ? (- <ul className="flex flex-col">- {connections.map((connection) => (- <div- key={connection.id}- className="relative flex flex-col -gap-[1px] [&>li]:pb-0"- >- <IntegrationConnectionItem- showNode={false}- disabled={isBranch || !canUpdateGitHubConnection}- key={connection.id}- connection={{- id: String(connection.id),- added_by: {- id: String(connection.user?.id),- primary_email: connection.user?.primary_email ?? '',- username: connection.user?.username ?? '',- },- foreign_project_id: String(connection.repository.id),- supabase_project_ref: connection.project.ref,- organization_integration_id: 'unused',- inserted_at: connection.inserted_at,- updated_at: connection.updated_at,- metadata: {- name: connection.repository.name,- } as any,- }}- type={'GitHub' as IntegrationName}- onDeleteConnection={onDeleteGitHubConnection}- className="!rounded-b-none !mb-0"- />-- <div className="border-b border-l border-r rounded-b-lg">- <GitHubIntegrationConnectionForm- disabled={isBranch || !canUpdateGitHubConnection}- connection={{- id: String(connection.id),- added_by: {- id: String(connection.user?.id),- primary_email: connection.user?.primary_email ?? '',- username: connection.user?.username ?? '',- },- foreign_project_id: String(connection.repository.id),- supabase_project_ref: connection.project.ref,- organization_integration_id: 'unused',- inserted_at: connection.inserted_at,- updated_at: connection.updated_at,- metadata: {- name: connection.repository.name,- supabaseConfig: {- supabaseDirectory: connection.workdir,- supabaseChangesOnly: connection.supabase_changes_only,- branchLimit: connection.branch_limit,- },- } as any,- }}- />- </div>- </div>- ))}- </ul>- ) : (- <EmptyIntegrationConnection- onClick={onAddGitHubConnection}- showNode={false}- disabled={isBranch || !canCreateGitHubConnection}- >- Add new project connection- </EmptyIntegrationConnection>- )}- </>- )}+ <div className="space-y-6">+ <div>+ <h5 className="text-foreground mb-2">How does the GitHub integration work?</h5>+ <p className="text-foreground-light text-sm mb-6">+ Connecting to GitHub allows you to sync preview branches with a chosen GitHub+ branch, keep your production branch in sync, and automatically create preview+ branches for every pull request.+ </p>+ <GitHubIntegrationConnectionForm connection={existingConnection} />+ </div>+ </div></ScaffoldSectionContent></ScaffoldSection></ScaffoldContainer>diff --git a/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx b/apps/studio/components/layouts/AppLayout/BranchDropdown.tsxindex 2af21af2e2c..2021f3df781 100644--- a/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx+++ b/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx@@ -1,4 +1,13 @@-import { AlertCircle, Check, ChevronsUpDown, ListTree, MessageCircle, Shield } from 'lucide-react'+import {+ AlertCircle,+ Check,+ ChevronsUpDown,+ GitBranch,+ ListTree,+ MessageCircle,+ Plus,+ Shield,+} from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'@@ -7,6 +16,7 @@ import { useParams } from 'common'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { Branch, useBranchesQuery } from 'data/branches/branches-query'import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { useAppStateSnapshot } from 'state/app-state'import {Badge,Button,@@ -66,26 +76,129 @@ export const BranchDropdown = () => {const router = useRouter()const { ref } = useParams()const projectDetails = useSelectedProject()+ const snap = useAppStateSnapshot()const isBranch = projectDetails?.parent_project_ref !== undefinedconst projectRef =projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefinedconst { data: branches, isLoading, isError, isSuccess } = useBranchesQuery({ projectRef })- const [open, setOpen] = useState(false)+ const isBranchingEnabled = projectDetails?.is_branch_enabled === trueconst selectedBranch = branches?.find((branch) => branch.project_ref === ref)+ const defaultMainBranch = {+ id: 'main',+ name: 'main',+ project_ref: projectRef ?? ref ?? '',+ is_default: true,+ } as unknown as Branch+const mainBranch = branches?.find((branch) => branch.is_default)const restOfBranches = branches?.filter((branch) => !branch.is_default).sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())- const sortedBranches = mainBranch- ? [mainBranch].concat(restOfBranches ?? [])- : restOfBranches ?? []+ const sortedBranches =+ branches && branches.length > 0+ ? mainBranch+ ? [mainBranch].concat(restOfBranches ?? [])+ : restOfBranches ?? []+ : [defaultMainBranch]const BRANCHING_GITHUB_DISCUSSION_LINK = 'https://github.com/orgs/supabase/discussions/18937'+ const [open, setOpen] = useState(false)++ const MenuContent = ({+ branchList,+ showSearch,+ }: {+ branchList: Branch[]+ showSearch?: boolean+ }) => (+ <Command_Shadcn_>+ {showSearch && <CommandInput_Shadcn_ placeholder="Find branch..." />}+ <CommandList_Shadcn_>+ {showSearch && <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>}++ <CommandGroup_Shadcn_>+ <ScrollArea className="max-h-[210px] overflow-y-auto">+ {branchList.map((branch) => (+ <BranchLink+ key={branch.id}+ branch={branch}+ isSelected={branch.id === selectedBranch?.id || branches?.length === 0}+ setOpen={setOpen}+ />+ ))}+ </ScrollArea>+ </CommandGroup_Shadcn_>++ <CommandSeparator_Shadcn_ />++ <CommandGroup_Shadcn_>+ <CommandItem_Shadcn_+ className="cursor-pointer w-full"+ onSelect={() => {+ setOpen(false)+ snap.setShowCreateBranchModal(true)+ }}+ onClick={() => {+ setOpen(false)+ snap.setShowCreateBranchModal(true)+ }}+ >+ <div className="w-full flex items-center gap-2">+ <Plus size={14} strokeWidth={1.5} />+ <p>Create branch</p>+ </div>+ </CommandItem_Shadcn_>+ <CommandItem_Shadcn_+ className="cursor-pointer w-full"+ onSelect={() => {+ setOpen(false)+ router.push(`/project/${ref}/branches`)+ }}+ onClick={() => setOpen(false)}+ >+ <Link href={`/project/${ref}/branches`} className="w-full flex items-center gap-2">+ <ListTree size={14} strokeWidth={1.5} />+ <p>Manage branches</p>+ </Link>+ </CommandItem_Shadcn_>+ </CommandGroup_Shadcn_>++ <CommandSeparator_Shadcn_ />++ <CommandGroup_Shadcn_>+ <CommandItem_Shadcn_+ className="cursor-pointer w-full"+ onSelect={() => {+ setOpen(false)+ window?.open(BRANCHING_GITHUB_DISCUSSION_LINK, '_blank')?.focus()+ }}+ onClick={() => setOpen(false)}+ >+ <Link+ href={BRANCHING_GITHUB_DISCUSSION_LINK}+ target="_blank"+ onClick={() => {+ setOpen(false)+ }}+ className="w-full flex gap-2"+ >+ <MessageCircle size={14} strokeWidth={1} className="text-muted mt-0.5" />+ <div>+ <p>Branching feedback</p>+ <p className="text-lighter">Join Github Discussion</p>+ </div>+ </Link>+ </CommandItem_Shadcn_>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ )+return (<>{isLoading && <ShimmeringLoader className="w-[90px]" />}@@ -97,90 +210,36 @@ export const BranchDropdown = () => {</div>)}- {isSuccess && branches.length > 0 && (+ {isSuccess && (<><Link href={`/project/${ref}`} className="flex items-center gap-2 flex-shrink-0 text-sm"><span className="text-foreground max-w-32 lg:max-w-none truncate">- {selectedBranch?.name}+ {isBranchingEnabled ? selectedBranch?.name : 'main'}</span>- {selectedBranch?.is_default ? (- <Badge variant="warning">Production</Badge>+ {isBranchingEnabled ? (+ selectedBranch?.is_default ? (+ <Badge variant="warning">Production</Badge>+ ) : (+ <Badge variant="brand">Preview Branch</Badge>+ )) : (- <Badge variant="brand">Preview Branch</Badge>+ <Badge variant="warning">Production</Badge>)}</Link><Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}><PopoverTrigger_Shadcn_ asChild><Buttontype="text"- className={cn('px-0.25 [&_svg]:w-5 [&_svg]:h-5 ml-1')}+ size="tiny"+ className={cn('px-1.5 py-4 [&_svg]:w-5 [&_svg]:h-5 ml-1')}iconRight={<ChevronsUpDown strokeWidth={1.5} />}/></PopoverTrigger_Shadcn_><PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">- <Command_Shadcn_>- <CommandInput_Shadcn_ placeholder="Find branch..." />- <CommandList_Shadcn_>- <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>- <CommandGroup_Shadcn_>- <ScrollArea className="max-h-[210px] overflow-y-auto">- {sortedBranches?.map((branch) => (- <BranchLink- key={branch.id}- branch={branch}- isSelected={branch.id === selectedBranch?.id}- setOpen={setOpen}- />- ))}- </ScrollArea>- </CommandGroup_Shadcn_>- <CommandSeparator_Shadcn_ />- <CommandGroup_Shadcn_>- <CommandItem_Shadcn_- className="cursor-pointer w-full"- onSelect={(e) => {- setOpen(false)- router.push(`/project/${ref}/branches`)- }}- onClick={() => setOpen(false)}- >- <Link- href={`/project/${ref}/branches`}- className="w-full flex items-center gap-2"- >- <ListTree size={14} strokeWidth={1.5} />- <p>Manage branches</p>- </Link>- </CommandItem_Shadcn_>- </CommandGroup_Shadcn_>- <CommandSeparator_Shadcn_ />- <CommandGroup_Shadcn_>- <CommandItem_Shadcn_- className="cursor-pointer w-full"- onSelect={() => {- setOpen(false)- window?.open(BRANCHING_GITHUB_DISCUSSION_LINK, '_blank')?.focus()- }}- onClick={() => setOpen(false)}- >- <Link- href={BRANCHING_GITHUB_DISCUSSION_LINK}- target="_blank"- onClick={() => {- setOpen(false)- }}- className="w-full flex gap-2"- >- <MessageCircle size={14} strokeWidth={1} className="text-muted mt-0.5" />- <div>- <p>Branching feedback</p>- <p className="text-lighter">Join Github Discussion</p>- </div>- </Link>- </CommandItem_Shadcn_>- </CommandGroup_Shadcn_>- </CommandList_Shadcn_>- </Command_Shadcn_>+ <MenuContent+ branchList={isBranchingEnabled ? sortedBranches ?? [] : [defaultMainBranch]}+ showSearch={isBranchingEnabled}+ /></PopoverContent_Shadcn_></Popover_Shadcn_></>diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsxindex b7e0a95ea7a..289bf7b33c4 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsx@@ -49,7 +49,7 @@ export const BranchingPITRNotice = () => {<Button size="tiny" type="default" asChild><Linkhref={`/project/${ref}/settings/addons?panel=pitr`}- onClick={() => snap.setShowEnableBranchingModal(false)}+ onClick={() => snap.setShowCreateBranchModal(false)}>Enable PITR</Link>diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPlanNotice.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPlanNotice.tsxindex 714b3e038ab..9c88b9f3241 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPlanNotice.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPlanNotice.tsx@@ -23,7 +23,7 @@ export const BranchingPlanNotice = () => {<Button size="tiny" type="default" className="mt-4"><Linkhref={`/org/${selectedOrg?.slug}/billing?panel=subscriptionPlan&source=enableBranchingButton`}- onClick={() => snap.setShowEnableBranchingModal(false)}+ onClick={() => snap.setShowCreateBranchModal(false)}>Upgrade to Pro</Link>diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPostgresVersionNotice.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPostgresVersionNotice.tsxindex f1b1ef709d1..29865c992cd 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPostgresVersionNotice.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPostgresVersionNotice.tsx@@ -23,7 +23,7 @@ export const BranchingPostgresVersionNotice = () => {<Button size="tiny" type="default" className="mt-4"><Linkhref={`/project/${ref}/settings/infrastructure`}- onClick={() => snap.setShowEnableBranchingModal(false)}+ onClick={() => snap.setShowCreateBranchModal(false)}>Head to project settings</Link>diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsxdeleted file mode 100644index 670b0e2ec8a..00000000000--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { GitBranch } from 'lucide-react'--import { ButtonTooltip } from 'components/ui/ButtonTooltip'-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'-import { useSelectedProject } from 'hooks/misc/useSelectedProject'-import { useAppStateSnapshot } from 'state/app-state'--export const EnableBranchingButton = () => {- const snap = useAppStateSnapshot()- const project = useSelectedProject()-- const canEnableBranching = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {- resource: { is_default: true },- })- const isDisabled = !canEnableBranching || project?.status !== 'ACTIVE_HEALTHY'-- return (- <ButtonTooltip- disabled={isDisabled}- type={'text'}- icon={<GitBranch strokeWidth={1.5} />}- onClick={() => snap.setShowEnableBranchingModal(true)}- className="bg-none hover:bg-none text-foreground-light hover:text-foreground [&_span]:w-full [&_span]:text-left "- tooltip={{- content: {- side: 'bottom',- text:- project?.status !== 'ACTIVE_HEALTHY'- ? 'Unpause your project to enable branching'- : !canEnableBranching- ? 'You need additional permissions to enable branching'- : undefined,- },- }}- >- Enable branching- </ButtonTooltip>- )-}diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsxdeleted file mode 100644index 2a94ed94a1f..00000000000--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsx+++ /dev/null@@ -1,410 +0,0 @@-import { zodResolver } from '@hookform/resolvers/zod'-import { last } from 'lodash'-import { Check, DollarSign, ExternalLink, FileText, GitBranch, Github, Loader2 } from 'lucide-react'-import Link from 'next/link'-import { useEffect, useState } from 'react'-import { useForm } from 'react-hook-form'-import { toast } from 'sonner'-import * as z from 'zod'--import { useQueryClient } from '@tanstack/react-query'-import { useParams } from 'common'-import SidePanelGitHubRepoLinker from 'components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker'-import AlertError from 'components/ui/AlertError'-import { DocsButton } from 'components/ui/DocsButton'-import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'-import { useBranchCreateMutation } from 'data/branches/branch-create-mutation'-import { useCheckGithubBranchValidity } from 'data/integrations/github-branch-check-query'-import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'-import { projectKeys } from 'data/projects/keys'-import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'-import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'-import { useSelectedProject } from 'hooks/misc/useSelectedProject'-import { useFlag } from 'hooks/ui/useFlag'-import { useRouter } from 'next/router'-import { useAppStateSnapshot } from 'state/app-state'-import { sidePanelsState } from 'state/side-panels'-import {- Badge,- Button,- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogSection,- DialogSectionSeparator,- DialogTitle,- Form_Shadcn_,- FormControl_Shadcn_,- FormField_Shadcn_,- FormItem_Shadcn_,- FormMessage_Shadcn_,- Input_Shadcn_,- Label_Shadcn_ as Label,-} from 'ui'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'-import { BranchingPITRNotice } from './BranchingPITRNotice'-import { BranchingPlanNotice } from './BranchingPlanNotice'-import { BranchingPostgresVersionNotice } from './BranchingPostgresVersionNotice'--export const EnableBranchingModal = () => {- const router = useRouter()- const { ref } = useParams()- const snap = useAppStateSnapshot()- const queryClient = useQueryClient()- const project = useSelectedProject()- const selectedOrg = useSelectedOrganization()- const gitlessBranching = useFlag('gitlessBranching')-- const [isGitBranchValid, setIsGitBranchValid] = useState(false)-- const {- data: connections,- error: connectionsError,- isLoading: isLoadingConnections,- isSuccess: isSuccessConnections,- isError: isErrorConnections,- } = useGitHubConnectionsQuery(- {- organizationId: selectedOrg?.id,- },- { enabled: snap.showEnableBranchingModal }- )-- const hasMinimumPgVersion =- Number(last(project?.dbVersion?.split('-') ?? [])?.split('.')[0] ?? 0) >= 15-- const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: selectedOrg?.slug })- const isFreePlan = subscription?.plan.id === 'free'-- const { data: addons } = useProjectAddonsQuery({ projectRef: ref })- const hasPitrEnabled =- (addons?.selected_addons ?? []).find((addon) => addon.type === 'pitr') !== undefined-- const githubConnection = connections?.find((connection) => connection.project.ref === ref)- const [repoOwner, repoName] = githubConnection?.repository.name.split('/') ?? []-- const { mutateAsync: checkGithubBranchValidity, isLoading: isChecking } =- useCheckGithubBranchValidity({ onError: () => {} })-- const { mutate: createBranch, isLoading: isCreating } = useBranchCreateMutation({- onSuccess: async () => {- await Promise.all([- queryClient.invalidateQueries(projectKeys.detail(ref)),- queryClient.invalidateQueries(projectKeys.list()),- ])- toast.success(`Successfully enabled branching`)- snap.setShowEnableBranchingModal(false)- router.push(`/project/${ref}/branches`)- },- onError: (error) => {- toast.error(`Failed to enable branching: ${error.message}`)- },- })-- const formId = 'enable-branching-form'- const FormSchema = z- .object({- productionBranchName: z- .string()- .min(1, 'Production branch name cannot be empty')- .refine(- (val) => /^[a-zA-Z0-9\-_]+$/.test(val),- 'Branch name can only contain alphanumeric characters, hyphens, and underscores.'- ),- branchName: z.string().optional(),- })- .superRefine(async (val, ctx) => {- if (githubConnection && (!val.branchName || val.branchName.length === 0)) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: 'GitHub branch is required when a repository is connected.',- path: ['branchName'],- })- setIsGitBranchValid(false)- return- }-- if (githubConnection && val.branchName && val.branchName.length > 0) {- try {- await checkGithubBranchValidity({- connectionId: githubConnection.id,- branchName: val.branchName,- })- setIsGitBranchValid(true)- } catch (error) {- setIsGitBranchValid(false)- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `Unable to find branch "${val.branchName}" in ${repoOwner}/${repoName}`,- path: ['branchName'],- })- }- } else {- setIsGitBranchValid(true)- }- })-- const form = useForm<z.infer<typeof FormSchema>>({- mode: 'onBlur',- reValidateMode: 'onChange',- resolver: zodResolver(FormSchema),- defaultValues: { productionBranchName: 'main', branchName: '' },- })-- const isLoading = isLoadingConnections- const isError = isErrorConnections- const isSuccess = isSuccessConnections-- const isFormValid = form.formState.isValid- const canSubmit =- isFormValid && !isCreating && !isChecking && (gitlessBranching || !!githubConnection)-- const onSubmit = (data: z.infer<typeof FormSchema>) => {- if (!ref) return console.error('Project ref is required')- createBranch({- projectRef: ref,- branchName: data.productionBranchName,- ...(data.branchName && isGitBranchValid ? { gitBranch: data.branchName } : {}),- })- }-- const openLinkerPanel = () => {- snap.setShowEnableBranchingModal(false)- sidePanelsState.setGithubConnectionsOpen(true)- }-- useEffect(() => {- if (snap.showEnableBranchingModal) {- form.reset({ productionBranchName: 'main', branchName: '' })- setIsGitBranchValid(false)- }- }, [form, snap.showEnableBranchingModal])-- useEffect(() => {- setIsGitBranchValid(!form.getValues('branchName') || form.getValues('branchName')?.length === 0)- }, [githubConnection?.id, form.getValues('branchName')])-- return (- <>- <Dialog- open={snap.showEnableBranchingModal}- onOpenChange={(open) => !open && snap.setShowEnableBranchingModal(false)}- >- <DialogContent size="large" hideClose>- <Form_Shadcn_ {...form}>- <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>- <DialogHeader padding="small">- <div className="flex items-start justify-between gap-x-4">- <div className="flex items-center gap-x-4">- <GitBranch strokeWidth={2} size={20} />- <div>- <DialogTitle>Enable database branching</DialogTitle>- <DialogDescription>Manage environments in Supabase</DialogDescription>- </div>- </div>- <DocsButton href="https://supabase.com/docs/guides/platform/branching" />- </div>- </DialogHeader>-- {isLoading && (- <div>- <DialogSectionSeparator />- <DialogSection padding="medium">- <GenericSkeletonLoader />- </DialogSection>- <DialogSectionSeparator />- </div>- )}- {isError && (- <div>- <DialogSectionSeparator />- <DialogSection padding="medium">- <AlertError error={connectionsError} subject="Failed to retrieve connections" />- </DialogSection>- <DialogSectionSeparator />- </div>- )}- {isSuccess && (- <>- {isFreePlan ? (- <DialogSection className="!p-0">- <BranchingPlanNotice />- </DialogSection>- ) : !hasMinimumPgVersion ? (- <DialogSection padding="medium">- <BranchingPostgresVersionNotice />- </DialogSection>- ) : (- <>- <DialogSectionSeparator />- <DialogSection padding="medium" className="space-y-4">- <FormField_Shadcn_- control={form.control}- name="productionBranchName"- render={({ field }) => (- <FormItemLayout label="Production Branch Name">- <FormControl_Shadcn_>- <Input_Shadcn_- {...field}- placeholder="e.g. main, production"- autoComplete="off"- />- </FormControl_Shadcn_>- </FormItemLayout>- )}- />- {githubConnection ? (- <>- <FormField_Shadcn_- control={form.control}- name="branchName"- render={({ field }) => (- <FormItem_Shadcn_ className="relative">- <div className="flex items-center justify-between mb-2">- <Label>- Link GitHub Branch{' '}- {githubConnection && (- <span className="text-destructive">*</span>- )}- </Label>- <div className="flex items-center gap-2 text-sm">- <Github size={14} />- <Link- href={`https://github.com/${repoOwner}/${repoName}`}- target="_blank"- rel="noreferrer"- className="text-foreground hover:underline"- >- {repoOwner}/{repoName}- </Link>- <Link- href={`https://github.com/${repoOwner}/${repoName}`}- target="_blank"- rel="noreferrer"- >- <ExternalLink size={14} strokeWidth={1.5} />- </Link>- </div>- </div>- <FormControl_Shadcn_>- <Input_Shadcn_- {...field}- placeholder="e.g. main"- autoComplete="off"- />- </FormControl_Shadcn_>- <div className="absolute top-9 right-3 flex items-center gap-2">- {isChecking && <Loader2 size={14} className="animate-spin" />}- {field.value && !isChecking && isGitBranchValid && (- <Check size={14} className="text-brand" strokeWidth={2} />- )}- </div>- <FormMessage_Shadcn_ className="mt-1" />- </FormItem_Shadcn_>- )}- />- </>- ) : (- <div className="flex items-center gap-2 justify-between">- <div>- <div className="flex items-center gap-2 mb-2">- <Label>GitHub Repository</Label>- {!gitlessBranching && (- <Badge variant="warning" size="small">- Required- </Badge>- )}- </div>- <p className="text-sm text-foreground-light">- {gitlessBranching- ? 'Optionally connect to a GitHub repository to enable deploying previews on Pull Requests and manage migrations automatically.'- : 'Connect to a GitHub repository to enable database branching. This allows you to deploy previews on Pull Requests and manage migrations automatically.'}- </p>- </div>- <Button type="default" icon={<Github />} onClick={openLinkerPanel}>- Connect to GitHub- </Button>- </div>- )}- </DialogSection>- </>- )}- <DialogSectionSeparator />-- <DialogSection padding="medium" className="flex flex-col gap-4">- <h3 className="text-sm text-foreground">Please keep in mind the following:</h3>-- {githubConnection && (- <div className="flex flex-row gap-4">- <div>- <figure className="w-10 h-10 rounded-md bg-info-200 border border-info-400 flex items-center justify-center">- <FileText className="text-info" size={20} strokeWidth={2} />- </figure>- </div>- <div className="flex flex-col gap-y-1">- <p className="text-sm text-foreground">- Migrations are applied from your GitHub repository- </p>- <p className="text-sm text-foreground-light">- Migration files in your <code className="text-xs">./supabase</code>{' '}- directory will run on both Preview Branches and Production when pushing- and merging branches.- </p>- </div>- </div>- )}-- <div className="flex flex-row gap-4">- <div>- <figure className="w-10 h-10 rounded-md bg-info-200 border border-info-400 flex items-center justify-center">- <DollarSign className="text-info" size={20} strokeWidth={2} />- </figure>- </div>- <div className="flex flex-col gap-y-1">- <p className="text-sm text-foreground">- Preview branches are billed $0.01344 per hour- </p>- <p className="text-sm text-foreground-light">- This cost will continue for as long as the branch has not been removed.- </p>- </div>- </div>- {!hasPitrEnabled && <BranchingPITRNotice />}- </DialogSection>- <DialogSectionSeparator />- </>- )}-- <DialogFooter className="justify-end gap-2" padding="small">- <Button- size="medium"- disabled={isCreating}- type="default"- onClick={() => snap.setShowEnableBranchingModal(false)}- >- Cancel- </Button>- <Button- block- size="medium"- form={formId}- disabled={!isSuccess || isCreating || !canSubmit || isChecking || isFreePlan}- loading={isCreating}- type="primary"- htmlType="submit"- >- I understand, enable branching- </Button>- </DialogFooter>- </form>- </Form_Shadcn_>- </DialogContent>- </Dialog>-- <SidePanelGitHubRepoLinker projectRef={ref} />- </>- )-}diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsxindex ca9ef90c9d7..df7f54921b8 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsx@@ -1,11 +1,10 @@-import { useParams } from 'common'+import { Check, Loader2 } from 'lucide-react'+import {EmptyIntegrationConnection,IntegrationConnection,} from 'components/interfaces/Integrations/VercelGithub/IntegrationPanels'import type { GitHubConnection } from 'data/integrations/github-connections-query'-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'-import { Check, Loader2 } from 'lucide-react'import { useSidePanelsStateSnapshot } from 'state/side-panels'import {Badge,@@ -31,9 +30,6 @@ const GithubRepositorySelection = ({isValid,githubConnection,}: GithubRepositorySelectionProps) => {- const { ref } = useParams()- const org = useSelectedOrganization()-const sidePanels = useSidePanelsStateSnapshot()function onSelectConnectRepo() {diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsxindex 7ba2e573556..a0a3304b43a 100644--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx@@ -8,7 +8,6 @@ import { LocalDropdown } from 'components/interfaces/LocalDropdown'import { UserDropdown } from 'components/interfaces/UserDropdown'import { AssistantButton } from 'components/layouts/AppLayout/AssistantButton'import { BranchDropdown } from 'components/layouts/AppLayout/BranchDropdown'-import { EnableBranchingButton } from 'components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton'import { InlineEditorButton } from 'components/layouts/AppLayout/InlineEditorButton'import { OrganizationDropdown } from 'components/layouts/AppLayout/OrganizationDropdown'import { ProjectDropdown } from 'components/layouts/AppLayout/ProjectDropdown'@@ -61,7 +60,6 @@ const LayoutHeader = ({const selectedProject = useSelectedProject()const selectedOrganization = useSelectedOrganization()const { setMobileMenuOpen } = useAppStateSnapshot()- const isBranchingEnabled = selectedProject?.is_branch_enabled === true// We only want to query the org usage and check for possible over-ages for plans without usage billing enabled (free or pro with spend cap)const { data: orgUsage } = useOrgUsageQuery(@@ -135,7 +133,7 @@ const LayoutHeader = ({</div>)}- {selectedProject && isBranchingEnabled && (+ {selectedProject && (<><LayoutHeaderDivider /><BranchDropdown />@@ -177,7 +175,6 @@ const LayoutHeader = ({}}>{<Connect />}- {!isBranchingEnabled && IS_PLATFORM && <EnableBranchingButton />}</motion.div>)}</AnimatePresence>diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsxindex 4368aab294b..e6fd4b1498f 100644--- a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx+++ b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx@@ -4,6 +4,8 @@ import { useRouter } from 'next/router'import { forwardRef, Fragment, PropsWithChildren, ReactNode, useEffect, useState } from 'react'import { useParams } from 'common'+import { CreateBranchModal } from 'components/interfaces/BranchManagement/CreateBranchModal'+import SidePanelGitHubRepoLinker from 'components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker'import ProjectAPIDocs from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs'import { AIAssistant } from 'components/ui/AIAssistantPanel/AIAssistant'import { EditorPanel } from 'components/ui/EditorPanel/EditorPanel'@@ -18,7 +20,6 @@ import { useAppStateSnapshot } from 'state/app-state'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { cn, ResizableHandle, ResizablePanel, ResizablePanelGroup } from 'ui'import MobileSheetNav from 'ui-patterns/MobileSheetNav/MobileSheetNav'-import { EnableBranchingModal } from '../AppLayout/EnableBranchingButton/EnableBranchingModal'import { useEditorType } from '../editors/EditorsLayout.hooks'import BuildingState from './BuildingState'import ConnectingState from './ConnectingState'@@ -86,6 +87,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayoutconst [isClient, setIsClient] = useState(false)const selectedOrganization = useSelectedOrganization()const selectedProject = useSelectedProject()+ const projectRefForGitHubLinker = selectedProject?.parent_project_ref ?? selectedProject?.refconst {editorPanel,mobileMenuOpen,@@ -256,7 +258,8 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout</ResizablePanel></ResizablePanelGroup></div>- <EnableBranchingModal />+ <CreateBranchModal />+ <SidePanelGitHubRepoLinker projectRef={projectRefForGitHubLinker} /><ProjectAPIDocs /><MobileSheetNav open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}>{productMenu}diff --git a/apps/studio/data/branches/branch-create-mutation.ts b/apps/studio/data/branches/branch-create-mutation.tsindex d32400c906a..7086cb8a2d4 100644--- a/apps/studio/data/branches/branch-create-mutation.ts+++ b/apps/studio/data/branches/branch-create-mutation.ts@@ -6,6 +6,7 @@ import type { ResponseError } from 'types'import { branchKeys } from './keys'export type BranchCreateVariables = {+ is_default?: booleanprojectRef: stringbranchName: stringgitBranch?: string@@ -13,6 +14,7 @@ export type BranchCreateVariables = {}export async function createBranch({+ is_default,projectRef,branchName,gitBranch,@@ -23,6 +25,7 @@ export async function createBranch({path: { ref: projectRef },},body: {+ is_default,branch_name: branchName,git_branch: gitBranch,region: region,diff --git a/apps/studio/data/integrations/github-branch-check-query.ts b/apps/studio/data/integrations/github-branch-check-query.tsindex 6f7d8bffa78..e6046666972 100644--- a/apps/studio/data/integrations/github-branch-check-query.ts+++ b/apps/studio/data/integrations/github-branch-check-query.ts@@ -5,20 +5,20 @@ import { get, handleError } from 'data/fetchers'import type { ResponseError } from 'types'export type GithubBranchVariables = {- connectionId: number+ repositoryId: numberbranchName: string}export async function checkGithubBranchValidity(- { connectionId, branchName }: GithubBranchVariables,+ { repositoryId, branchName }: GithubBranchVariables,signal?: AbortSignal) {const { data, error } = await get(- '/platform/integrations/github/branches/{connectionId}/{branchName}',+ '/platform/integrations/github/repositories/{repositoryId}/branches/{branchName}',{params: {path: {- connectionId,+ repositoryId,branchName,},},diff --git a/apps/studio/data/integrations/github-connection-create-mutation.ts b/apps/studio/data/integrations/github-connection-create-mutation.tsindex da6ce1a4c28..18b3f1b256c 100644--- a/apps/studio/data/integrations/github-connection-create-mutation.ts+++ b/apps/studio/data/integrations/github-connection-create-mutation.ts@@ -1,11 +1,16 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'+import { components } from 'api-types'import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'-import type { GitHubConnectionCreateVariables } from './integrations.types'import { integrationKeys } from './keys'+type GitHubConnectionCreateVariables = {+ organizationId: number+ connection: components['schemas']['CreateGitHubConnectionBody']+}+export async function createGitHubConnection({ connection }: GitHubConnectionCreateVariables) {const { data, error } = await post('/platform/integrations/github/connections', {body: connection,diff --git a/apps/studio/data/integrations/github-connection-update-mutation.ts b/apps/studio/data/integrations/github-connection-update-mutation.tsindex be09295a9c1..8153f76cd08 100644--- a/apps/studio/data/integrations/github-connection-update-mutation.ts+++ b/apps/studio/data/integrations/github-connection-update-mutation.ts@@ -1,26 +1,25 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'+import { components } from 'api-types'import { handleError, patch } from 'data/fetchers'import type { ResponseError } from 'types'import { integrationKeys } from './keys'-type UpdateVariables = {+type GitHubConnectionUpdateVariables = {connectionId: string | numberorganizationId: number- workdir: string- supabaseChangesOnly: boolean- branchLimit: number+ connection: components['schemas']['UpdateGitHubConnectionBody']}export async function updateConnection(- { connectionId, workdir, supabaseChangesOnly, branchLimit }: UpdateVariables,+ { connectionId, connection }: GitHubConnectionUpdateVariables,signal?: AbortSignal) {const { data, error } = await patch('/platform/integrations/github/connections/{connection_id}', {params: { path: { connection_id: String(connectionId) } },signal,- body: { workdir, supabase_changes_only: supabaseChangesOnly, branch_limit: branchLimit },+ body: connection,})if (error) handleError(error)@@ -34,11 +33,11 @@ export const useGitHubConnectionUpdateMutation = ({onError,...options}: Omit<- UseMutationOptions<UpdateContentData, ResponseError, UpdateVariables>,+ UseMutationOptions<UpdateContentData, ResponseError, GitHubConnectionUpdateVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<UpdateContentData, ResponseError, UpdateVariables>(+ return useMutation<UpdateContentData, ResponseError, GitHubConnectionUpdateVariables>((args) => updateConnection(args),{async onSuccess(data, variables, context) {diff --git a/apps/studio/data/integrations/integrations.types.ts b/apps/studio/data/integrations/integrations.types.tsindex a453f581771..4e2d69fe60c 100644--- a/apps/studio/data/integrations/integrations.types.ts+++ b/apps/studio/data/integrations/integrations.types.ts@@ -1,5 +1,3 @@-import type { components } from 'data/api'-export type VercelFramework =| (| 'blitzjs'@@ -257,16 +255,30 @@ export type IntegrationConnectionsCreateVariables = {}}-export type GitHubConnectionCreateVariables = {- organizationId: number- connection: components['schemas']['CreateGitHubConnectionBody']-}-export type EnvironmentTargets = 'production' | 'preview' | 'development'-export type UpdateConnectionPayload = {- id: string- organizationIntegrationId: string- envSyncTargets: EnvironmentTargets[]- publicEnvVarPrefix?: string+// GitHub specific connection type based on the API response+export type GitHubConnection = {+ id: number+ inserted_at: string+ updated_at: string+ branch_limit: number+ installation_id: number+ new_branch_per_pr: boolean+ supabase_changes_only: boolean+ workdir: string+ project: {+ id: number+ name: string+ ref: string+ }+ repository: {+ id: number+ name: string+ }+ user: {+ id: number+ primary_email: string | null+ username: string+ } | null}diff --git a/apps/studio/data/integrations/vercel-connection-update-mutate.ts b/apps/studio/data/integrations/vercel-connection-update-mutate.tsindex fa81264f8c4..b210d6df67f 100644--- a/apps/studio/data/integrations/vercel-connection-update-mutate.ts+++ b/apps/studio/data/integrations/vercel-connection-update-mutate.ts@@ -3,9 +3,16 @@ import { toast } from 'sonner'import { handleError, patch } from 'data/fetchers'import type { ResponseError } from 'types'-import type { UpdateConnectionPayload } from './integrations.types'+import { EnvironmentTargets } from './integrations.types'import { integrationKeys } from './keys'+type UpdateConnectionPayload = {+ id: string+ organizationIntegrationId: string+ envSyncTargets: EnvironmentTargets[]+ publicEnvVarPrefix?: string+}+export async function updateVercelConnection({id,envSyncTargets,diff --git a/apps/studio/pages/project/[ref]/index.tsx b/apps/studio/pages/project/[ref]/index.tsxindex e37203eae22..eb3a86ed847 100644--- a/apps/studio/pages/project/[ref]/index.tsx+++ b/apps/studio/pages/project/[ref]/index.tsx@@ -49,7 +49,7 @@ const Home: NextPageWithLayout = () => {useEffect(() => {if (enableBranching && !hasShownEnableBranchingModalRef.current) {hasShownEnableBranchingModalRef.current = true- snap.setShowEnableBranchingModal(true)+ snap.setShowCreateBranchModal(true)}// eslint-disable-next-line react-hooks/exhaustive-deps}, [enableBranching])diff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.tsindex 4a307007a94..56a6ca3b6f1 100644--- a/apps/studio/state/app-state.ts+++ b/apps/studio/state/app-state.ts@@ -51,7 +51,7 @@ const getInitialState = () => {activeDocsSection: ['introduction'],docsLanguage: 'js',showProjectApiDocs: false,- showEnableBranchingModal: false,+ showCreateBranchModal: false,showFeaturePreviewModal: false,selectedFeaturePreview: '',showAiSettingsModal: false,@@ -81,7 +81,7 @@ const getInitialState = () => {activeDocsSection: ['introduction'],docsLanguage: 'js',showProjectApiDocs: false,- showEnableBranchingModal: false,+ showCreateBranchModal: false,showFeaturePreviewModal: false,selectedFeaturePreview: '',showAiSettingsModal: false,@@ -132,9 +132,9 @@ export const appState = proxy({appState.isMfaEnforced = value},- showEnableBranchingModal: false,- setShowEnableBranchingModal: (value: boolean) => {- appState.showEnableBranchingModal = value+ showCreateBranchModal: false,+ setShowCreateBranchModal: (value: boolean) => {+ appState.showCreateBranchModal = value},showFeaturePreviewModal: false,diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.tsindex 58e32b4292b..19be3f6d63b 100644--- a/packages/api-types/types/api.d.ts+++ b/packages/api-types/types/api.d.ts@@ -1942,6 +1942,7 @@ export interface components {| '48xlarge_optimized_cpu'| '48xlarge_high_memory'git_branch?: string+ is_default?: booleanpersistent?: boolean/*** @description Postgres engine version. If not provided, the latest version will be used.diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.tsindex 28f0f1e6e78..86b3987b4a1 100644--- a/packages/api-types/types/platform.d.ts+++ b/packages/api-types/types/platform.d.ts@@ -16618,6 +16618,12 @@ export interface operations {'application/json': components['schemas']['DatabaseDetailResponse'][]}}+ 403: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }}}DatabasesStatusesController_getStatus: {@@ -16915,6 +16921,10 @@ export interface operations {| 'network_receive_bytes'| 'network_transmit_bytes'| 'pgbouncer_pools_client_active_connections'+ | 'realtime_connections_connected'+ | 'realtime_channel_joins'+ | 'realtime_channel_events'+ | 'realtime_channel_presence_events'databaseIdentifier?: stringendDate: stringinterval?: '1m' | '5m' | '10m' | '30m' | '1h' | '1d'