Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Show connection settings if already configured despite no GH auth (#51427)

Joshen Lim2b393377c6dc
diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/ConnectGitHubButton.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/ConnectGitHubButton.tsx
new file mode 100644
index 00000000000..e823d82a5e0
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/ConnectGitHubButton.tsx
@@ -0,0 +1,28 @@
+import { Button } from 'ui'
+
+import { openInstallGitHubIntegrationWindow } from '@/lib/github'
+
+export const ConnectGitHubButton = ({
+ id,
+ onConnectClick,
+ refetch,
+}: {
+ id?: string
+
+ onConnectClick?: () => void
+ refetch: () => void
+}) => {
+ return (
+ <Button
+ id={id}
+ size="tiny"
+ type="button"
+ onClick={() => {
+ onConnectClick?.()
+ openInstallGitHubIntegrationWindow('authorize', refetch)
+ }}
+ >
+ Connect GitHub
+ </Button>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx
index a9d0c4a28a0..932d2ca5fe6 100644
--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx
+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx
@@ -2,7 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { AnimatePresence, motion } from 'framer-motion'
import { Loader2 } from 'lucide-react'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
import {
@@ -22,10 +22,12 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import * as z from 'zod'
+import { ConnectGitHubButton } from './ConnectGitHubButton'
import {
GitHubRepositoryField,
useGitHubRepositoryOptions,
} from '@/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField'
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { InlineLink } from '@/components/ui/InlineLink'
import { UpgradeToPro } from '@/components/ui/UpgradeToPro'
import { useBranchCreateMutation } from '@/data/branches/branch-create-mutation'
@@ -69,6 +71,8 @@ export const GitHubIntegrationConnectionForm = ({
'integrations.github_connections'
)
+ const canManageGitHubConnection = canCreateGitHubConnection && canUpdateGitHubConnection
+
const {
gitHubAuthorization,
githubRepos,
@@ -77,12 +81,12 @@ export const GitHubIntegrationConnectionForm = ({
refetch: refetchRepositoryOptions,
} = useGitHubRepositoryOptions()
- const { mutate: updateBranch } = useBranchUpdateMutation({
+ const { mutateAsync: updateBranch } = useBranchUpdateMutation({
onSuccess: () => {
toast.success('Production branch settings successfully updated')
},
})
- const { mutate: createBranch } = useBranchCreateMutation({
+ const { mutateAsync: createBranch } = useBranchCreateMutation({
onSuccess: () => {
toast.success('Production branch settings successfully updated')
},
@@ -99,11 +103,8 @@ export const GitHubIntegrationConnectionForm = ({
const { mutateAsync: checkGithubBranchValidity, isPending: isCheckingBranch } =
useCheckGithubBranchValidity({ onError: () => {} })
- const { mutate: createConnection, isPending: isCreatingConnection } =
+ const { mutateAsync: createConnection, isPending: isCreatingConnection } =
useGitHubConnectionCreateMutation({
- onSuccess: () => {
- toast.success('GitHub connection updated')
- },
onError: (error) => {
// Don't show error toast when connection already exists - the branch
// settings update will still proceed and show its own success toast
@@ -120,7 +121,7 @@ export const GitHubIntegrationConnectionForm = ({
},
})
- const { mutate: updateConnectionSettings, isPending: isUpdatingConnection } =
+ const { mutateAsync: updateConnectionSettings, isPending: isUpdatingConnection } =
useGitHubConnectionUpdateMutation()
const prodBranch = existingBranches?.find((branch) => branch.is_default)
@@ -159,19 +160,34 @@ export const GitHubIntegrationConnectionForm = ({
}
})
+ const hasGitBranch = Boolean(prodBranch?.git_branch?.trim())
+ const connectionValues: z.infer<typeof GitHubSettingsSchema> | undefined = connection
+ ? {
+ repositoryId: connection.repository.id.toString(),
+ enableProductionSync: hasGitBranch,
+ branchName: hasGitBranch ? (prodBranch?.git_branch ?? '') : '',
+ new_branch_per_pr: connection.new_branch_per_pr,
+ supabaseDirectory: connection.workdir || '',
+ supabaseChangesOnly: connection.supabase_changes_only,
+ branchLimit: String(connection.branch_limit),
+ }
+ : undefined
+
const githubSettingsForm = useForm<z.infer<typeof GitHubSettingsSchema>>({
resolver: zodResolver(GitHubSettingsSchema),
mode: 'onSubmit',
reValidateMode: 'onBlur',
defaultValues: {
repositoryId: connection?.repository.id.toString() || '',
+ branchName: prodBranch?.git_branch || 'main',
enableProductionSync: true,
- branchName: 'main',
new_branch_per_pr: true,
supabaseDirectory: '.',
supabaseChangesOnly: true,
branchLimit: '3',
},
+ values: connectionValues,
+ resetOptions: { keepDirtyValues: true },
})
const enableProductionSync = useWatch({
@@ -219,7 +235,7 @@ export const GitHubIntegrationConnectionForm = ({
) => {
if (!selectedProject?.ref || !selectedOrganization?.id) return
- createConnection({
+ const connectionRequest = createConnection({
organizationId: selectedOrganization.id,
connection: {
installation_id: selectedRepo.installation_id,
@@ -234,19 +250,24 @@ export const GitHubIntegrationConnectionForm = ({
},
})
- if (!prodBranch) {
- createBranch({
- projectRef: selectedProject.ref,
- branchName: 'main',
- gitBranch: data.branchName,
- is_default: true,
- })
- } else {
- updateBranch({
- branchRef: prodBranch.project_ref,
- projectRef: selectedProject.ref,
- gitBranch: data.branchName,
- })
+ const branchRequest = prodBranch
+ ? updateBranch({
+ branchRef: prodBranch.project_ref,
+ projectRef: selectedProject.ref,
+ gitBranch: data.branchName,
+ })
+ : createBranch({
+ projectRef: selectedProject.ref,
+ branchName: 'main',
+ gitBranch: data.branchName,
+ is_default: true,
+ })
+
+ // Only re-baseline the form once both requests succeed, so a failure keeps the edits unsaved
+ const results = await Promise.allSettled([connectionRequest, branchRequest])
+ if (results.every((result) => result.status === 'fulfilled')) {
+ toast.success('GitHub connection updated')
+ githubSettingsForm.reset(data, { keepDirtyValues: false })
}
}
@@ -272,7 +293,7 @@ export const GitHubIntegrationConnectionForm = ({
) => {
if (!selectedProject?.ref || !selectedOrganization?.id) return
- updateConnectionSettings({
+ const connectionRequest = updateConnectionSettings({
connectionId: currentConnection.id,
organizationId: selectedOrganization.id,
connection: {
@@ -285,24 +306,28 @@ export const GitHubIntegrationConnectionForm = ({
},
})
- if (prodBranch) {
- updateBranch({
- branchRef: prodBranch.project_ref,
- projectRef: selectedProject.ref,
- gitBranch: data.enableProductionSync ? data.branchName : '',
- branchName: data.branchName || 'main',
- })
- } else {
- // if for some reason, the project doesn't have a default branch yet, create it.
- createBranch({
- projectRef: selectedProject.ref,
- gitBranch: data.enableProductionSync ? data.branchName : '',
- branchName: data.branchName || 'main',
- is_default: true,
- })
- }
+ // if for some reason, the project doesn't have a default branch yet, create it.
+ const branchRequest = prodBranch
+ ? updateBranch({
+ branchRef: prodBranch.project_ref,
+ projectRef: selectedProject.ref,
+ gitBranch: data.enableProductionSync ? data.branchName : '',
+ branchName: data.branchName || 'main',
+ })
+ : createBranch({
+ projectRef: selectedProject.ref,
+ gitBranch: data.enableProductionSync ? data.branchName : '',
+ branchName: data.branchName || 'main',
+ is_default: true,
+ })
setIsConfirmingBranchChange(false)
+
+ // Only re-baseline the form once both requests succeed, so a failure keeps the edits unsaved
+ const results = await Promise.allSettled([connectionRequest, branchRequest])
+ if (results.every((result) => result.status === 'fulfilled')) {
+ githubSettingsForm.reset(data, { keepDirtyValues: false })
+ }
}
const onConfirmBranchChange = async () => {
@@ -320,15 +345,18 @@ export const GitHubIntegrationConnectionForm = ({
connectionId: connection.id,
})
- githubSettingsForm.reset({
- repositoryId: '',
- enableProductionSync: true,
- branchName: 'main',
- new_branch_per_pr: true,
- supabaseDirectory: '.',
- supabaseChangesOnly: true,
- branchLimit: '3',
- })
+ githubSettingsForm.reset(
+ {
+ repositoryId: '',
+ enableProductionSync: true,
+ branchName: 'main',
+ new_branch_per_pr: true,
+ supabaseDirectory: '.',
+ supabaseChangesOnly: true,
+ branchLimit: '3',
+ },
+ { keepDirtyValues: false }
+ )
} catch (error) {
console.error('Error removing integration:', error)
toast.error('Failed to remove integration')
@@ -356,37 +384,21 @@ export const GitHubIntegrationConnectionForm = ({
}
}
- 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])
+ const handleToggleProductionSync = (isEnabled: boolean) => {
+ githubSettingsForm.setValue('enableProductionSync', isEnabled, { shouldDirty: true })
+ githubSettingsForm.setValue('branchName', isEnabled ? prodBranch?.git_branch || 'main' : '', {
+ shouldDirty: true,
+ })
+ }
const isLoading =
isLoadingEntitlements ||
isCreatingConnection ||
isUpdatingConnection ||
isDeletingConnection ||
- isLoadingRepositoryOptions
+ (!!gitHubAuthorization && isLoadingRepositoryOptions)
+
+ const isFieldDisabled = !canUpdateGitHubConnection || !gitHubAuthorization
let repositoryDescription = 'Select the repository to connect to your project'
if (connection) {
@@ -397,6 +409,16 @@ export const GitHubIntegrationConnectionForm = ({
return (
<>
+ {!gitHubAuthorization && !!currentRepositoryId && (
+ <Admonition
+ className="mb-4"
+ layout="responsive"
+ title="Authorize GitHub to manage integration settings"
+ description="Required to list your repositories and change this project's connection"
+ actions={<ConnectGitHubButton refetch={refetchRepositoryOptions} />}
+ />
+ )}
+
<Form {...githubSettingsForm}>
<form
onSubmit={githubSettingsForm.handleSubmit(handleCreateOrUpdateConnection)}
@@ -410,10 +432,7 @@ export const GitHubIntegrationConnectionForm = ({
label="GitHub repository"
layout="flex-row-reverse"
description={repositoryDescription}
- disabled={
- (!connection && !canCreateGitHubConnection) ||
- (connection && !canUpdateGitHubConnection)
- }
+ disabled={!gitHubAuthorization || !canManageGitHubConnection}
selectedRepositoryName={connection?.repository.name}
repositories={githubRepos}
gitHubAuthorization={gitHubAuthorization}
@@ -427,7 +446,7 @@ export const GitHubIntegrationConnectionForm = ({
</CardContent>
<AnimatePresence>
- {gitHubAuthorization !== null && !!currentRepositoryId && (
+ {!!currentRepositoryId && (
<motion.div
initial={{ opacity: 0, y: -16 }}
animate={{ opacity: 1, y: 0 }}
@@ -459,7 +478,7 @@ export const GitHubIntegrationConnectionForm = ({
{...field}
placeholder="."
autoComplete="off"
- disabled={!canUpdateGitHubConnection}
+ disabled={isFieldDisabled}
/>
</FormControl>
</FormItemLayout>
@@ -480,9 +499,10 @@ export const GitHubIntegrationConnectionForm = ({
>
<FormControl>
<Switch
+ aria-label="Toggle deploy to production"
checked={field.value}
- onCheckedChange={field.onChange}
- disabled={!canUpdateGitHubConnection}
+ onCheckedChange={handleToggleProductionSync}
+ disabled={isFieldDisabled}
/>
</FormControl>
</FormItemLayout>
@@ -509,7 +529,7 @@ export const GitHubIntegrationConnectionForm = ({
<Input
{...field}
autoComplete="off"
- disabled={!canUpdateGitHubConnection || !enableProductionSync}
+ disabled={isFieldDisabled || !enableProductionSync}
/>
</FormControl>
<div className="absolute top-2.5 right-3 flex items-center gap-2">
@@ -562,9 +582,14 @@ export const GitHubIntegrationConnectionForm = ({
>
<FormControl>
<Switch
+ aria-label="Toggle automatic branching"
checked={!hasAccessToBranching ? false : field.value}
onCheckedChange={field.onChange}
- disabled={!hasAccessToBranching || !canCreateGitHubConnection}
+ disabled={
+ !hasAccessToBranching ||
+ !canCreateGitHubConnection ||
+ isFieldDisabled
+ }
/>
</FormControl>
</FormItemLayout>
@@ -596,7 +621,8 @@ export const GitHubIntegrationConnectionForm = ({
disabled={
!hasAccessToBranching ||
!newBranchPerPr ||
- !canUpdateGitHubConnection
+ !canUpdateGitHubConnection ||
+ isFieldDisabled
}
/>
</FormControl>
@@ -615,12 +641,14 @@ export const GitHubIntegrationConnectionForm = ({
>
<FormControl>
<Switch
+ aria-label="Toggle Supabase changes only"
checked={!hasAccessToBranching ? false : field.value}
onCheckedChange={(val) => field.onChange(val)}
disabled={
!hasAccessToBranching ||
!newBranchPerPr ||
- !canUpdateGitHubConnection
+ !canUpdateGitHubConnection ||
+ isFieldDisabled
}
/>
</FormControl>
@@ -646,28 +674,37 @@ export const GitHubIntegrationConnectionForm = ({
<div className="flex space-x-2">
{githubSettingsForm.formState.isDirty && (
<Button
- onClick={() => githubSettingsForm.reset()}
+ onClick={() =>
+ githubSettingsForm.reset(connectionValues, { keepDirtyValues: false })
+ }
disabled={!canUpdateGitHubConnection || isCheckingBranch}
>
Cancel
</Button>
)}
- <Button
+ <ButtonTooltip
variant="primary"
type="submit"
disabled={
!hasAccessToGitHubIntegration ||
- (!connection && !canCreateGitHubConnection) ||
- (connection && !canUpdateGitHubConnection) ||
isCheckingBranch ||
isLoading ||
+ !canManageGitHubConnection ||
(!connection && !githubSettingsForm.getValues().repositoryId) ||
(connection && !githubSettingsForm.formState.isDirty)
}
loading={isLoading}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canManageGitHubConnection
+ ? "You need additional permissions to update this project's GitHub integration settings"
+ : undefined,
+ },
+ }}
>
{connection ? 'Save changes' : 'Enable integration'}
- </Button>
+ </ButtonTooltip>
</div>
</CardFooter>
</motion.div>
diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx
index 5d635e1c2f0..def429b9010 100644
--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx
+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField.tsx
@@ -18,6 +18,7 @@ import {
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { ConnectGitHubButton } from './ConnectGitHubButton'
import { useGitHubAuthorizationQuery } from '@/data/integrations/github-authorization-query'
import { useGitHubRepositoriesQuery } from '@/data/integrations/github-repositories-query'
import { openInstallGitHubIntegrationWindow } from '@/lib/github'
@@ -30,18 +31,6 @@ export type GitHubRepository = {
default_branch: string
}
-export const GITHUB_ICON = (
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 96" className="w-5 shrink-0">
- <title>GitHub icon</title>
- <path
- fill="currentColor"
- 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>
-)
-
export const useGitHubRepositoryOptions = () => {
const {
data: gitHubAuthorization,
@@ -134,21 +123,9 @@ export const GitHubRepositoryField = <TFormValues extends FieldValues>({
name={name}
render={({ field }) => (
<FormItemLayout id={name} label={label} layout={layout} description={description}>
- {gitHubAuthorization === null ? (
+ {gitHubAuthorization === null && !currentRepositoryId ? (
<FormControl>
- <Button
- id={name}
- size="tiny"
- type="button"
- disabled={disabled}
- onClick={() => {
- onConnectClick?.()
- openInstallGitHubIntegrationWindow('authorize', refetch)
- }}
- icon={GITHUB_ICON}
- >
- Connect GitHub
- </Button>
+ <ConnectGitHubButton id={name} onConnectClick={onConnectClick} refetch={refetch} />
</FormControl>
) : (
<Popover open={isRepoSelectorOpen} onOpenChange={setIsRepoSelectorOpen}>
@@ -159,8 +136,7 @@ export const GitHubRepositoryField = <TFormValues extends FieldValues>({
type="button"
className="justify-start h-[34px] w-full [&>div:last-child]:ml-auto"
disabled={disabled || isLoading}
- loading={isLoading}
- icon={GITHUB_ICON}
+ loading={!!gitHubAuthorization && isLoading}
iconRight={<ChevronDown />}
>
{selectedRepository?.name ||
@@ -180,7 +156,6 @@ export const GitHubRepositoryField = <TFormValues extends FieldValues>({
<CommandItem
key={repo.id}
value={`${repo.name.replaceAll('"', '')}-${repo.id}`}
- className="flex gap-2 items-center"
onSelect={() => {
field.onChange(repo.id)
@@ -200,7 +175,6 @@ export const GitHubRepositoryField = <TFormValues extends FieldValues>({
setIsRepoSelectorOpen(false)
}}
>
- {GITHUB_ICON}
<span className="truncate" title={repo.name}>
{repo.name}
</span>
diff --git a/apps/studio/data/integrations/github-authorization-delete-mutation.ts b/apps/studio/data/integrations/github-authorization-delete-mutation.ts
index e275bdc0f44..95a3dc9ad66 100644
--- a/apps/studio/data/integrations/github-authorization-delete-mutation.ts
+++ b/apps/studio/data/integrations/github-authorization-delete-mutation.ts
@@ -26,14 +26,8 @@ export const useGitHubAuthorizationDeleteMutation = ({
return useMutation<GitHubAuthorizationDeleteData, ResponseError, void>({
mutationFn: () => deleteGitHubAuthorization(),
async onSuccess(data, variables, context) {
- await Promise.all([
- queryClient.invalidateQueries({
- queryKey: integrationKeys.githubAuthorization(),
- }),
- queryClient.invalidateQueries({
- queryKey: integrationKeys.githubRepositoriesList(),
- }),
- ])
+ queryClient.removeQueries({ queryKey: integrationKeys.githubAuthorization() })
+ queryClient.removeQueries({ queryKey: integrationKeys.githubRepositoriesList() })
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {