fix(studio): reset rename form between same-named SQL snippets (#49275)

## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Bug fix

## What is the current behavior?

In the SQL Editor, when two snippets are both named "Untitled query" and
one is renamed, the rename modal's state is not reset afterwards.
Opening the rename modal for the second snippet prefills the input with
the first snippet's new name, and the second snippet can't be renamed at
all because the "Rename query" button stays disabled.

`RenameQueryModal` fed the snippet to react-hook-form through the
`values` option, which only re-runs its reset when the values object
deep-changes. Two snippets with the same name (and no description)
produce a deep-equal object, so switching between them never resets the
form — it keeps the previously renamed name and stays non-dirty.

## What is the new behavior?

The form is mounted per snippet (`key={snippet.id}`) with plain
`defaultValues`, so no form state can carry over between snippets
regardless of name collisions. `SQLEditorNav` derives modal visibility
from the selected snippet and clears it on cancel/complete, matching
`SearchList`.

Covered by a new component test in `RenameQueryModal.test.tsx` that
renames one "Untitled query", reopens the modal for a second one, and
asserts the field resets and the second rename submits.

## Additional context

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed the rename dialog retaining input from a previously renamed
snippet.
* Ensured the rename form resets correctly after successful submission
and when switching between snippets.
* **Tests**
* Added regression coverage for renaming multiple untitled snippets with
the same original name.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Charis authored and GitHub committed 2026-08-20 09:09:45 -04:00
1 parent 1a483ab255
commit 474bf5da4a
3 files changed
+143 -97

No files matched your search

@@ -34,6 +34,8 @@ const createSnippet = (id: string, name: string): SnippetWithContent => ({
const SNIPPET_A = createSnippet('snippet-a', 'First query')
const SNIPPET_B = createSnippet('snippet-b', 'Second query')
const UNTITLED_A = createSnippet('untitled-a', 'Untitled query')
const UNTITLED_B = createSnippet('untitled-b', 'Untitled query')
/** The modal renders the AI title generator, which checks for an OpenAI key when self-hosted. */
const mockOpenAIKeyCheck = () =>
@@ -108,6 +110,47 @@ describe('RenameQueryModal', () => {
expect(screen.getByRole('button', { name: 'Rename query' })).toBeDisabled()
})
test('resets for the next snippet when both snippets share a name', async () => {
mockOpenAIKeyCheck()
const requests = mockUpsert()
const onComplete = vi.fn()
const { rerender } = customRender(
<RenameQueryModal snippet={UNTITLED_A} visible onCancel={vi.fn()} onComplete={onComplete} />
)
await userEvent.clear(getNameInput())
await userEvent.type(getNameInput(), 'Renamed query')
fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))
await waitFor(() => expect(onComplete).toHaveBeenCalledOnce())
// The parent keeps the renamed snippet selected while closing the modal, then reopens it for
// a second snippet that still carries the same original name
rerender(
<RenameQueryModal
snippet={UNTITLED_A}
visible={false}
onCancel={vi.fn()}
onComplete={onComplete}
/>
)
rerender(
<RenameQueryModal snippet={UNTITLED_B} visible onCancel={vi.fn()} onComplete={onComplete} />
)
await waitFor(() => expect(getNameInput()).toHaveValue('Untitled query'))
await userEvent.clear(getNameInput())
await userEvent.type(getNameInput(), 'Second renamed query')
fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))
await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(2))
expect(requests).toEqual([
{ id: 'untitled-a', name: 'Renamed query' },
{ id: 'untitled-b', name: 'Second renamed query' },
])
})
test('discards an abandoned edit when cancelled', async () => {
mockOpenAIKeyCheck()
const onCancel = vi.fn()
@@ -49,12 +49,13 @@ const formSchema = z.object({
description: z.string().optional(),
})
export const RenameQueryModal = ({
snippet = {} as any,
visible,
onCancel,
onComplete,
}: RenameQueryModalProps) => {
interface RenameQueryFormProps {
snippet: SqlSnippet | Snippet
onCancel: () => void
onComplete: () => void
}
const RenameQueryForm = ({ snippet, onCancel, onComplete }: RenameQueryFormProps) => {
const { ref } = useParams()
const router = useRouter()
@@ -145,7 +146,7 @@ export const RenameQueryModal = ({
}
toast.success('Successfully renamed snippet!')
reset({ name, description }, { keepDirtyValues: false })
reset({ name, description })
if (onComplete) onComplete()
} catch (error: any) {
// [Joshen] We probably need some rollback cause all the saving is async
@@ -156,98 +157,105 @@ export const RenameQueryModal = ({
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: { name: name ?? '', description: description ?? '' },
values: { name: name ?? '', description: description ?? '' },
resetOptions: { keepDirtyValues: true },
})
const { reset, formState } = form
const { isDirty, isSubmitting } = formState
const handleCancel = () => {
onCancel()
reset(undefined, { keepDirtyValues: false })
}
return (
<Dialog open={visible} onOpenChange={handleCancel}>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} noValidate>
<DialogSection className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItemLayout name="name" layout="vertical" label="Name">
<FormControl>
<Input {...field} id="name" />
</FormControl>
</FormItemLayout>
)}
/>
<div className="flex w-full justify-end mt-2">
<ButtonTooltip
variant="default"
onClick={() => generateTitle()}
size="tiny"
disabled={
isTitleGenerationLoading || !isApiKeySet || isHipaaProjectDisallowed || isAiOptedOut
}
tooltip={{
content: {
side: 'bottom',
text: isHipaaProjectDisallowed
? 'This feature is not available for HIPAA projects.'
: isAiOptedOut
? 'Your organization has opted out of AI features.'
: isApiKeySet
? undefined
: 'Add your "OPENAI_API_KEY" to your environment variables to use this feature.',
},
}}
>
<div className="flex items-center gap-1">
<div className="scale-75">
<AiIconAnimation loading={isTitleGenerationLoading} />
</div>
<span>Rename with Supabase AI</span>
</div>
</ButtonTooltip>
</div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItemLayout name="description" layout="vertical" label="Description">
<FormControl>
<Textarea
{...field}
id="description"
rows={4}
placeholder="Describe query"
className="resize-none"
/>
</FormControl>
</FormItemLayout>
)}
/>
</DialogSection>
<DialogFooter>
<Button type="reset" variant="default" onClick={onCancel} disabled={isSubmitting}>
Cancel
</Button>
<Button type="submit" loading={isSubmitting} disabled={isSubmitting || !isDirty}>
Rename query
</Button>
</DialogFooter>
</form>
</Form>
)
}
export const RenameQueryModal = ({
snippet = {} as any,
visible,
onCancel,
onComplete,
}: RenameQueryModalProps) => {
return (
<Dialog open={visible} onOpenChange={onCancel}>
<DialogContent size="small">
<DialogHeader>
<DialogTitle>Rename</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} noValidate>
<DialogSection className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItemLayout name="name" layout="vertical" label="Name">
<FormControl>
<Input {...field} id="name" />
</FormControl>
</FormItemLayout>
)}
/>
<div className="flex w-full justify-end mt-2">
<ButtonTooltip
variant="default"
onClick={() => generateTitle()}
size="tiny"
disabled={
isTitleGenerationLoading ||
!isApiKeySet ||
isHipaaProjectDisallowed ||
isAiOptedOut
}
tooltip={{
content: {
side: 'bottom',
text: isHipaaProjectDisallowed
? 'This feature is not available for HIPAA projects.'
: isAiOptedOut
? 'Your organization has opted out of AI features.'
: isApiKeySet
? undefined
: 'Add your "OPENAI_API_KEY" to your environment variables to use this feature.',
},
}}
>
<div className="flex items-center gap-1">
<div className="scale-75">
<AiIconAnimation loading={isTitleGenerationLoading} />
</div>
<span>Rename with Supabase AI</span>
</div>
</ButtonTooltip>
</div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItemLayout name="description" layout="vertical" label="Description">
<FormControl>
<Textarea
{...field}
id="description"
rows={4}
placeholder="Describe query"
className="resize-none"
/>
</FormControl>
</FormItemLayout>
)}
/>
</DialogSection>
<DialogFooter>
<Button type="reset" variant="default" onClick={handleCancel} disabled={isSubmitting}>
Cancel
</Button>
<Button type="submit" loading={isSubmitting} disabled={isSubmitting || !isDirty}>
Rename query
</Button>
</DialogFooter>
</form>
</Form>
{/* Keyed by snippet so that each snippet gets a fresh form, with no state carried over */}
<RenameQueryForm
key={snippet.id}
snippet={snippet}
onCancel={onCancel}
onComplete={onComplete}
/>
</DialogContent>
</Dialog>
)
@@ -84,7 +84,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
const [showMoveModal, setShowMoveModal] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
const [showRenameModal, setShowRenameModal] = useState(false)
const [expandedFolderIds, setExpandedFolderIds] = useState<string[]>([])
const [selectedSnippets, setSelectedSnippets] = useState<Snippet[]>([])
@@ -564,7 +563,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
setSelectedSnippets([element.metadata as unknown as Snippet])
}}
onSelectRename={() => {
setShowRenameModal(true)
setSelectedSnippetToRename(element.metadata as Snippet)
}}
onSelectDownload={() => {
@@ -646,7 +644,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
setSelectedSnippets([element.metadata as unknown as Snippet])
}}
onSelectRename={() => {
setShowRenameModal(true)
setSelectedSnippetToRename(element.metadata as Snippet)
}}
onSelectDownload={() => {
@@ -754,7 +751,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
if (props.isBranch) {
snapV2.editFolder(element.id as string)
} else {
setShowRenameModal(true)
setSelectedSnippetToRename(element.metadata as Snippet)
}
}}
@@ -817,7 +813,6 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
setSelectedSnippets([snippet])
}}
onSelectRename={(snippet) => {
setShowRenameModal(true)
setSelectedSnippetToRename(snippet)
}}
/>
@@ -832,9 +827,9 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
<RenameQueryModal
snippet={selectedSnippetToRename}
visible={showRenameModal}
onCancel={() => setShowRenameModal(false)}
onComplete={() => setShowRenameModal(false)}
visible={!!selectedSnippetToRename}
onCancel={() => setSelectedSnippetToRename(undefined)}
onComplete={() => setSelectedSnippetToRename(undefined)}
/>
<MoveQueryModal