The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(support form): create api route to upload attachments (#39543)
Charis4f0ce0a0e357
diff --git a/apps/studio/components/interfaces/Support/AttachmentUpload.tsx b/apps/studio/components/interfaces/Support/AttachmentUpload.tsxindex 9e2d5a9ef13..a1713ff2218 100644--- a/apps/studio/components/interfaces/Support/AttachmentUpload.tsx+++ b/apps/studio/components/interfaces/Support/AttachmentUpload.tsx@@ -1,23 +1,36 @@import { compact } from 'lodash'import { Plus, X } from 'lucide-react'-import { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ChangeEvent,+ type RefObject,+} from 'react'import { toast } from 'sonner'// End of third-party imports+import { useFlag } from 'common'+import { useGenerateAttachmentURLsMutation } from 'data/support/generate-attachment-urls-mutation'import { uuidv4 } from 'lib/helpers'+import { useProfile } from 'lib/profile'import { cn } from 'ui'import { createSupportStorageClient } from './support-storage-client'const MAX_ATTACHMENTS = 5-const uploadAttachments = async (ref: string, files: File[]) => {+const uploadAttachments = async ({ userId, files }: { userId: string; files: File[] }) => {+ if (files.length === 0) return []+const supportSupabaseClient = createSupportStorageClient()const filesToUpload = Array.from(files)const uploadedFiles = await Promise.all(filesToUpload.map(async (file) => {const suffix = file.type.split('/')[1]- const prefix = `${ref}/${uuidv4()}.${suffix}`+ const prefix = `${userId}/${uuidv4()}.${suffix}`const options = { cacheControl: '3600' }const { data, error } = await supportSupabaseClient.storage@@ -29,24 +42,17 @@ const uploadAttachments = async (ref: string, files: File[]) => {}))const keys = compact(uploadedFiles).map((file) => file.path)-- if (keys.length === 0) return []-- const { data, error } = await supportSupabaseClient.storage- .from('support-attachments')- .createSignedUrls(keys, 10 * 365 * 24 * 60 * 60)- if (error) {- console.error('Failed to retrieve URLs for attachments', error)- }- return data ? data.map((file) => file.signedUrl) : []+ return keys}export function useAttachmentUpload() {+ const { profile } = useProfile()const uploadButtonRef = useRef<HTMLInputElement>(null)-const [uploadedFiles, setUploadedFiles] = useState<File[]>([])const [uploadedDataUrls, setUploadedDataUrls] = useState<string[]>([])+ const { mutateAsync: generateAttachmentURLs } = useGenerateAttachmentURLsMutation()+const isFull = uploadedFiles.length >= MAX_ATTACHMENTSconst addFile = useCallback(() => {@@ -92,14 +98,18 @@ export function useAttachmentUpload() {}}, [uploadedFiles])- const createAttachments = useCallback(- async (projectRef: string) => {- const attachments =- uploadedFiles.length > 0 ? await uploadAttachments(projectRef, uploadedFiles) : []- return attachments- },- [uploadedFiles]- )+ const createAttachments = useCallback(async () => {+ if (!profile?.id) {+ console.error('[Support Form > uploadAttachments] Unable to upload files, missing user ID')+ toast.error('Unable to upload attachments')+ return []+ }++ const filenames = await uploadAttachments({ userId: profile.gotrue_id, files: uploadedFiles })+ const urls = await generateAttachmentURLs({ filenames })+ return urls+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [uploadedFiles])return useMemo(() => ({@@ -116,22 +126,49 @@ export function useAttachmentUpload() {}interface AttachmentUploadDisplayProps {- uploadButtonRef: React.RefObject<HTMLInputElement>+ uploadButtonRef: RefObject<HTMLInputElement>isFull: boolean+ uploadedDataUrls: string[]addFile: () => voidhandleFileUpload: (event: ChangeEvent<HTMLInputElement>) => Promise<void>removeFileUpload: (idx: number) => void- uploadedDataUrls: Array<string>}export function AttachmentUploadDisplay({uploadButtonRef,isFull,+ uploadedDataUrls,addFile,handleFileUpload,removeFileUpload,- uploadedDataUrls,}: AttachmentUploadDisplayProps) {+ const { profile } = useProfile()+ const enableUploads = useFlag('supportFormAttachments')++ if (!enableUploads) {+ return (+ <div>+ <h3 className="text-sm text-foreground">Attachments</h3>+ <p className="text-sm text-foreground-lighter mt-2">+ Uploads are temporarily disabled. Please reply to the acknowledgement email you will+ receive with any screenshots you'd like to upload.+ </p>+ </div>+ )+ }++ if (!profile) {+ return (+ <div>+ <h3 className="text-sm text-foreground">Attachments</h3>+ <p className="text-sm text-foreground-lighter mt-2">+ Uploads are only supported when logged in. Please reply to the acknowledgement email you+ will receive with any screenshots you'd like to upload.+ </p>+ </div>+ )+ }+return (<div className="flex flex-col gap-y-4"><div className="flex flex-col gap-y-1">diff --git a/apps/studio/components/interfaces/Support/SupportForm.utils.tsx b/apps/studio/components/interfaces/Support/SupportForm.utils.tsxindex 3ee06ef84ba..d655f57671b 100644--- a/apps/studio/components/interfaces/Support/SupportForm.utils.tsx+++ b/apps/studio/components/interfaces/Support/SupportForm.utils.tsx@@ -3,17 +3,16 @@ import {createLoader,createParser,createSerializer,- type inferParserType,parseAsString,- parseAsStringLiteral,+ type inferParserType,type UseQueryStatesKeysMap,} from 'nuqs'// End of third-party importsimport {+ DocsSearchResultType as PageType,type DocsSearchResult as Page,type DocsSearchResultSection as PageSection,- DocsSearchResultType as PageType,} from 'common'import { getProjectDetail } from 'data/projects/project-detail-query'import { DOCS_URL } from 'lib/constants'diff --git a/apps/studio/components/interfaces/Support/SupportFormV2.tsx b/apps/studio/components/interfaces/Support/SupportFormV2.tsxindex fb2497e53b9..d405b1ca4c7 100644--- a/apps/studio/components/interfaces/Support/SupportFormV2.tsx+++ b/apps/studio/components/interfaces/Support/SupportFormV2.tsx@@ -1,4 +1,4 @@-import type { Dispatch, MouseEventHandler } from 'react'+import { type Dispatch, type MouseEventHandler } from 'react'import type { SubmitHandler, UseFormReturn } from 'react-hook-form'// End of third-party imports@@ -14,7 +14,7 @@ import {AffectedServicesSelector,CATEGORIES_WITHOUT_AFFECTED_SERVICES,} from './AffectedServicesSelector'-import { useAttachmentUpload } from './AttachmentUpload'+import { AttachmentUploadDisplay, useAttachmentUpload } from './AttachmentUpload'import { CategoryAndSeverityInfo } from './CategoryAndSeverityInfo'import { ClientLibraryInfo } from './ClientLibraryInfo'import { MessageField } from './MessageField'@@ -72,7 +72,7 @@ export const SupportFormV2 = ({ form, initialError, state, dispatch }: SupportFoconst onSubmit: SubmitHandler<SupportFormValues> = async (values) => {dispatch({ type: 'SUBMIT' })- const attachments = await attachmentUpload.createAttachments(projectRef)+ const attachments = await attachmentUpload.createAttachments()const selectedLibrary = values.library? CLIENT_LIBRARIES.find((library) => library.language === values.library)@@ -153,14 +153,7 @@ export const SupportFormV2 = ({ form, initialError, state, dispatch }: SupportFo<ClientLibraryInfo form={form} library={library} category={category} /><AffectedServicesSelector form={form} category={category} /><MessageField form={form} originalError={initialError} />- {/* <AttachmentUploadDisplay {...attachmentUpload} /> */}- <div>- <h3 className="text-sm text-foreground">Attachments</h3>- <p className="text-sm text-foreground-lighter mt-2">- Uploads have been temporarily disabled. Please reply to the acknowledgement email you- will receive with any screenshots you'd like to upload- </p>- </div>+ <AttachmentUploadDisplay {...attachmentUpload} /></div><DialogSectionSeparator />diff --git a/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsx b/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsxindex 450ca6df91d..4daa0e2e14c 100644--- a/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsx+++ b/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsx@@ -1,1273 +1,1310 @@-import { test } from 'vitest'--test('placeholder', () => {})-// import { screen, waitFor } from '@testing-library/react'-// import userEvent from '@testing-library/user-event'-// import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'-// // End of third-party imports-//-// import { API_URL } from 'lib/constants'-// import { HttpResponse, http } from 'msw'-// import { createMockOrganization, createMockProject } from 'tests/helpers'-// import { customRender } from 'tests/lib/custom-render'-// import { addAPIMock, mswServer } from 'tests/lib/msw'-// import { createMockProfileContext } from 'tests/lib/profile-helpers'-// import { NO_ORG_MARKER, NO_PROJECT_MARKER } from '../SupportForm.utils'-// import { SupportFormPage } from '../SupportFormPage'-//-// type Screen = typeof screen-//-// const mockOrganizations = [-// createMockOrganization({-// id: 1,-// slug: 'org-1',-// name: 'Organization 1',-// plan: { id: 'free', name: 'Free' },-// }),-// createMockOrganization({-// id: 2,-// slug: 'org-2',-// name: 'Organization 2',-// plan: { id: 'pro', name: 'Pro' },-// }),-// ]-//-// const mockProjects = [-// {-// ...createMockProject({-// id: 1,-// ref: 'project-1',-// name: 'Project 1',-// organization_id: 1,-// }),-// organization_slug: 'org-1',-// preview_branch_refs: [],-// },-// {-// ...createMockProject({-// id: 2,-// ref: 'project-2',-// name: 'Project 2',-// organization_id: 2,-// }),-// organization_slug: 'org-2',-// preview_branch_refs: [],-// },-// {-// ...createMockProject({-// id: 3,-// ref: 'project-3',-// name: 'Project 3',-// organization_id: 1,-// }),-// organization_slug: 'org-1',-// preview_branch_refs: [],-// },-// ]-//-// vi.mock('react-inlinesvg', () => ({-// __esModule: true,-// default: () => null,-// }))-//-// // Mock the support storage client module - will be configured per test-// vi.mock('../support-storage-client', () => ({-// createSupportStorageClient: vi.fn(),-// }))-//-// // Mock sonner toast-// vi.mock('sonner', () => ({-// toast: {-// success: vi.fn(),-// error: vi.fn(),-// },-// }))-//-// vi.mock(import('common'), async (importOriginal) => {-// const actual = await importOriginal()-// return {-// ...actual,-// useParams: vi.fn().mockReturnValue({ ref: 'default' }),-// useIsLoggedIn: vi.fn().mockReturnValue(true),-// isFeatureEnabled: vi.fn((feature: any, disabledFeatures: any) => {-// if (typeof feature === 'string') {-// if (feature === 'support:show_client_libraries') {-// return true-// }-// return (actual as any).isFeatureEnabled(feature, disabledFeatures)-// }-//-// if (Array.isArray(feature)) {-// const result = (actual as any).isFeatureEnabled(feature, disabledFeatures)-// if (feature.includes('support:show_client_libraries')) {-// if (result && typeof result === 'object') {-// return {-// ...result,-// 'support:show_client_libraries': true,-// }-// }-// }-// return result-// }-//-// return (actual as any).isFeatureEnabled(feature, disabledFeatures)-// }),-// }-// })-//-// vi.mock(import('lib/gotrue'), async (importOriginal) => {-// const actual = await importOriginal()-// return {-// ...actual,-// auth: {-// ...(actual.auth as any),-// onAuthStateChange: vi.fn(),-// },-// }-// })-//-// const renderSupportFormPage = (options?: Parameters<typeof customRender>[1]) =>-// customRender(<SupportFormPage />, {-// profileContext: createMockProfileContext(),-// ...options,-// })-//-// const getStatusLink = (screen: Screen) => {-// const statusLink = screen-// .getAllByRole('link')-// .find((el) => el.getAttribute('href') === 'https://status.supabase.com/')-// expect(statusLink).toBeDefined()-// return statusLink-// }-//-// const getOrganizationSelector = (screen: Screen) =>-// screen.getByRole('combobox', { name: 'Select an organization' })-//-// const getProjectSelector = (screen: Screen) =>-// screen.getByRole('combobox', { name: 'Select a project' })-//-// const getSummaryField = (screen: Screen) => screen.getByPlaceholderText(/summary of the problem/i)-//-// const getMessageField = (screen: Screen) => screen.getByPlaceholderText(/describe the issue/i)-//-// const getCategorySelector = (screen: Screen) =>-// screen.getByRole('combobox', { name: 'Select an issue' })-//-// const getSubmitButton = (screen: Screen) =>-// screen.getByRole('button', { name: 'Send support request' })-//-// const selectCategoryOption = async (screen: Screen, optionLabel: string) => {-// await userEvent.click(getCategorySelector(screen))-// const option = await screen.findByRole('option', {-// name: (accessibleName) => accessibleName.toLowerCase().startsWith(optionLabel.toLowerCase()),-// })-// await userEvent.click(option)-// }-//-// const getSeveritySelector = (screen: Screen) =>-// screen.getByRole('combobox', { name: 'Select a severity' })-//-// const selectSeverityOption = async (screen: Screen, optionLabel: string) => {-// await userEvent.click(getSeveritySelector(screen))-// const option = await screen.findByRole('option', {-// name: (accessibleName) => accessibleName.toLowerCase().startsWith(optionLabel.toLowerCase()),-// })-// await userEvent.click(option)-// }-//-// const getLibrarySelector = (screen: Screen) =>-// screen.getByRole('combobox', { name: 'Select a library' })-//-// const selectLibraryOption = async (screen: Screen, optionLabel: string) => {-// // await waitFor(() => {-// // expect(() => getLibrarySelector(screen)).not.toThrow()-// // })-// const selector = getLibrarySelector(screen)-// await userEvent.click(selector)-// const option = await screen.findByRole('option', {-// name: (accessibleName) => accessibleName.toLowerCase().startsWith(optionLabel.toLowerCase()),-// })-// await userEvent.click(option)-// }-//-// const getSupportForm = () => {-// const form = document.querySelector<HTMLFormElement>('form#support-form')-// expect(form).not.toBeNull()-// return form!-// }-//-// const getAttachmentFileInput = () => {-// const input = getSupportForm().querySelector<HTMLInputElement>(-// 'input[type="file"][accept*="image"]'-// )-// expect(input).not.toBeNull()-// return input!-// }-//-// const getAttachmentRemoveButtons = (screen: Screen) =>-// screen.queryAllByRole('button', { name: 'Remove attachment' })-//-// const createDeferred = () => {-// let resolve!: () => void-// const promise = new Promise<void>((res) => {-// resolve = res-// })-// return { promise, resolve }-// }-//-// const originalUserAgent = window.navigator.userAgent-//-// describe('SupportFormPage', () => {-// afterEach(() => {-// Object.defineProperty(window.navigator, 'userAgent', {-// value: originalUserAgent,-// configurable: true,-// })-// })-//-// beforeEach(() => {-// Object.defineProperty(window.navigator, 'userAgent', {-// value:-// 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',-// configurable: true,-// })-//-// Object.defineProperty(window, 'location', {-// value: { search: '' },-// writable: true,-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/organizations',-// response: mockOrganizations,-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/projects',-// response: mockProjects,-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/projects/:ref',-// response: mockProjects[0],-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/status',-// response: { is_healthy: true } as any,-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/auth/:ref/config',-// response: { SITE_URL: 'https://supabase.com', URI_ALLOW_LIST: '' } as any,-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/organizations/:slug/projects',-// response: ({ params, request }) => {-// const slug = (params as { slug: string }).slug-// const projects = mockProjects.filter((project) => project.organization_slug === slug)-//-// const url = new URL(request.url)-// const limit = Number(url.searchParams.get('limit') ?? projects.length)-// const offset = Number(url.searchParams.get('offset') ?? 0)-// const sort = url.searchParams.get('sort') ?? 'name_asc'-//-// const sorted = [...projects].sort((a, b) => {-// switch (sort) {-// case 'name_desc':-// return b.name.localeCompare(a.name)-// default:-// return a.name.localeCompare(b.name)-// }-// })-//-// const paginated = sorted.slice(offset, offset + limit)-//-// return HttpResponse.json({-// projects: paginated,-// pagination: {-// count: projects.length,-// limit,-// offset,-// },-// })-// },-// })-//-// mswServer.use(-// http.get('http://localhost:3000/img/supabase-logo.svg', () => HttpResponse.text(''))-// )-// })-//-// test('shows system status: healthy', async () => {-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getStatusLink(screen)).toHaveTextContent('All systems operational')-// })-// })-//-// test('shows system status: not healthy', async () => {-// addAPIMock({-// method: 'get',-// path: '/platform/status',-// response: { is_healthy: false } as any,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getStatusLink(screen)).toHaveTextContent('Active incident ongoing')-// })-// })-//-// test('shows system status: check failed', async () => {-// mswServer.use(-// http.get(`${API_URL}/platform/status`, () => HttpResponse.json(null, { status: 500 }))-// )-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getStatusLink(screen)).toHaveTextContent('Failed to check status')-// })-// })-//-// test('loading a URL with a valid project slug prefills the organization and project', async () => {-// Object.defineProperty(window, 'location', {-// value: { search: '?projectRef=project-3' },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(screen.getByRole('combobox', { name: 'Select a project' })).toHaveTextContent(-// 'Project 3'-// )-// })-// })-//-// test('loading a URL with no project slug falls back to first organization and project', async () => {-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-// })-//-// test('loading a URL with an invalid project slug falls back to first organization and project', async () => {-// mswServer.use(-// http.get(`${API_URL}/platform/projects/:ref`, () => HttpResponse.json(null, { status: 404 }))-// )-// Object.defineProperty(window, 'location', {-// value: { search: '?projectRef=project-nonexistent' },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-// })-//-// test('loading a URL with a message prefills the message field', async () => {-// const testMessage = 'This is a test support message from URL'-// Object.defineProperty(window, 'location', {-// value: { search: `?message=${encodeURIComponent(testMessage)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getMessageField(screen)).toHaveValue(testMessage)-// })-// })-//-// test('loading a URL with a subject prefills the subject field', async () => {-// const testSubject = 'Test Subject'-// Object.defineProperty(window, 'location', {-// value: { search: `?subject=${encodeURIComponent(testSubject)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// const subjectField = getSummaryField(screen)-// expect(subjectField).toHaveValue(testSubject)-// })-// })-//-// test('loading a URL with a category prefills the category field', async () => {-// const testCategory = 'Problem'-// Object.defineProperty(window, 'location', {-// value: { search: `?category=${encodeURIComponent(testCategory)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')-// })-// })-//-// test('loading a URL with a category prefills the category field (case-insensitive)', async () => {-// const testCategory = 'dashboard_bug'-// Object.defineProperty(window, 'location', {-// value: { search: `?category=${encodeURIComponent(testCategory)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')-// })-// })-//-// test('loading a URL with an invalid category gracefully falls back', async () => {-// const testCategory = 'Invalid'-// Object.defineProperty(window, 'location', {-// value: { search: `?category=${encodeURIComponent(testCategory)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Select an issue')-// })-// })-//-// test('loading a URL with multiple initial fields fills them all in', async () => {-// const testCategory = 'Problem'-// const testSubject = 'Test Subject'-// Object.defineProperty(window, 'location', {-// value: {-// search: `?category=${encodeURIComponent(testCategory)}&subject=${encodeURIComponent(testSubject)}`,-// },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')-// expect(getSummaryField(screen)).toHaveValue(testSubject)-// })-// })-//-// test('includes Sentry issue ID from URL in submission payload', async () => {-// const sentryIssueId = 'mock-sentry-id'-//-// const submitSpy = vi.fn()-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// Object.defineProperty(window, 'location', {-// value: { search: `?sid=${encodeURIComponent(sentryIssueId)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await selectCategoryOption(screen, 'Dashboard bug')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')-// })-//-// await userEvent.type(getSummaryField(screen), 'Dashboard stopped loading')-// await userEvent.type(getMessageField(screen), 'The dashboard page loads blank after login')-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-// expect(submitSpy.mock.calls[0]?.[0]?.dashboardSentryIssueId).toBe(sentryIssueId)-// }, 10_000)-//-// test('includes initial error message from URL in submission payload', async () => {-// const initialError = 'failed to fetch user data'-// const messageBody = 'The dashboard page loads blank after login'-//-// const submitSpy = vi.fn()-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// Object.defineProperty(window, 'location', {-// value: { search: `?error=${encodeURIComponent(initialError)}` },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await selectCategoryOption(screen, 'Dashboard bug')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')-// })-//-// await userEvent.type(getSummaryField(screen), 'Dashboard stopped loading')-// await userEvent.type(getMessageField(screen), messageBody)-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload?.message).toMatch(initialError)-// }, 10_000)-//-// test('submits support request with problem category, library, and affected services', async () => {-// const submitSpy = vi.fn()-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/auth/:ref/config',-// response: ({ params }) => {-// const { ref } = params as { ref: string }-// return HttpResponse.json({-// SITE_URL: `https://${ref}.example.com`,-// URI_ALLOW_LIST: `https://${ref}.example.com/callbacks`,-// } as any)-// },-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await selectCategoryOption(screen, 'APIs and client libraries')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')-// })-//-// await selectSeverityOption(screen, 'High')-// await waitFor(() => {-// expect(getSeveritySelector(screen)).toHaveTextContent('High')-// })-//-// await selectLibraryOption(screen, 'JavaScript')-// await waitFor(() => {-// expect(getLibrarySelector(screen)).toHaveTextContent('Javascript')-// })-//-// const summaryField = getSummaryField(screen)-// await userEvent.clear(summaryField)-// await userEvent.type(summaryField, 'API requests failing in production')-//-// const messageField = getMessageField(screen)-// await userEvent.clear(messageField)-// await userEvent.type(messageField, 'Requests return status 500 when calling the RPC endpoint')-//-// const supportAccessToggle = screen.getByRole('switch', {-// name: /allow support access to your project/i,-// })-// expect(supportAccessToggle).toBeChecked()-// await userEvent.click(supportAccessToggle)-// expect(supportAccessToggle).not.toBeChecked()-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload).toMatchObject({-// subject: 'API requests failing in production',-// message: 'Requests return status 500 when calling the RPC endpoint',-// category: 'Problem',-// severity: 'High',-// projectRef: 'project-1',-// organizationSlug: 'org-1',-// library: 'javascript',-// affectedServices: '',-// allowSupportAccess: false,-// verified: true,-// tags: ['dashboard-support-form'],-// siteUrl: 'https://project-1.example.com',-// additionalRedirectUrls: 'https://project-1.example.com/callbacks',-// browserInformation: 'Chrome',-// })-//-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// }, 10_000)-//-// test('submits urgent login issues ticket for a different organization', async () => {-// const submitSpy = vi.fn()-//-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/auth/:ref/config',-// response: ({ params }) => {-// const { ref } = params as { ref: string }-// return HttpResponse.json({-// SITE_URL: `https://${ref}.supabase.dev`,-// URI_ALLOW_LIST: `https://${ref}.supabase.dev/redirect`,-// } as any)-// },-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// })-//-// await userEvent.click(getOrganizationSelector(screen))-// await userEvent.click(await screen.findByRole('option', { name: 'Organization 2' }))-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 2')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 2')-// })-//-// await selectCategoryOption(screen, 'Issues with logging in')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Issues with logging in')-// })-//-// await selectSeverityOption(screen, 'Urgent')-// await waitFor(() => {-// expect(getSeveritySelector(screen)).toHaveTextContent('Urgent')-// })-//-// const summaryField = getSummaryField(screen)-// await userEvent.clear(summaryField)-// await userEvent.type(summaryField, 'Cannot log in to dashboard')-//-// const messageField = getMessageField(screen)-// await userEvent.clear(messageField)-// await userEvent.type(messageField, 'MFA challenge fails with an unknown error code')-//-// expect(-// screen.queryByRole('switch', { name: /allow support access to your project/i })-// ).toBeNull()-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload).toMatchObject({-// subject: 'Cannot log in to dashboard',-// message: 'MFA challenge fails with an unknown error code',-// category: 'Login_issues',-// severity: 'Urgent',-// projectRef: 'project-2',-// organizationSlug: 'org-2',-// library: '',-// affectedServices: '',-// allowSupportAccess: false,-// verified: true,-// tags: ['dashboard-support-form'],-// siteUrl: 'https://project-2.supabase.dev',-// additionalRedirectUrls: 'https://project-2.supabase.dev/redirect',-// browserInformation: 'Chrome',-// })-//-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// }, 10_000)-//-// test('submits database unresponsive ticket with initial error', async () => {-// const submitSpy = vi.fn()-//-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/auth/:ref/config',-// response: ({ params }) => {-// const { ref } = params as { ref: string }-// return HttpResponse.json({-// SITE_URL: `https://${ref}.apps.supabase.co`,-// URI_ALLOW_LIST: `https://${ref}.apps.supabase.co/auth`,-// } as any)-// },-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/projects/:ref',-// response: ({ params }) => {-// const { ref } = params as { ref: string }-// const project = mockProjects.find((candidate) => candidate.ref === ref)-// return project ? HttpResponse.json(project) : HttpResponse.json(null, { status: 404 })-// },-// })-//-// Object.defineProperty(window, 'location', {-// value: { search: '?projectRef=project-3&error=Connection timeout detected' },-// writable: true,-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getProjectSelector(screen)).toHaveTextContent('Project 3')-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// })-//-// await selectCategoryOption(screen, 'Database unresponsive')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Database unresponsive')-// })-//-// await selectSeverityOption(screen, 'Normal')-// await waitFor(() => {-// expect(getSeveritySelector(screen)).toHaveTextContent('Normal')-// })-//-// const summaryField = getSummaryField(screen)-// await userEvent.clear(summaryField)-// await userEvent.type(summaryField, 'Database unreachable after upgrade')-//-// const messageField = getMessageField(screen)-// await userEvent.clear(messageField)-// await userEvent.type(messageField, 'Connections time out after 30 seconds')-//-// const supportAccessToggle = screen.getByRole('switch', {-// name: /allow support access to your project/i,-// })-// expect(supportAccessToggle).toBeChecked()-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload).toMatchObject({-// subject: 'Database unreachable after upgrade',-// category: 'Database_unresponsive',-// severity: 'Normal',-// projectRef: 'project-3',-// organizationSlug: 'org-1',-// library: '',-// affectedServices: '',-// allowSupportAccess: true,-// verified: true,-// tags: ['dashboard-support-form'],-// siteUrl: 'https://project-3.apps.supabase.co',-// additionalRedirectUrls: 'https://project-3.apps.supabase.co/auth',-// browserInformation: 'Chrome',-// })-// expect(payload.message).toBe(-// 'Connections time out after 30 seconds\nError: Connection timeout detected'-// )-//-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// }, 10_000)-//-// test('when organization changes, project selector updates to match', async () => {-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await userEvent.click(getOrganizationSelector(screen))-// await userEvent.click(screen.getByRole('option', { name: 'Organization 2' }))-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 2')-// })-//-// await waitFor(() => {-// expect(getProjectSelector(screen)).toHaveTextContent('Project 2')-// })-// })-//-// test('AI Assistant suggestion displays when valid project and organization are selected', async () => {-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(screen.getByText('Try the AI Assistant')).toBeInTheDocument()-// })-// })-//-// test('can upload attachments', async () => {-// const url = URL as unknown as {-// createObjectURL?: (obj: Blob) => string-// revokeObjectURL?: (url: string) => void-// }-// const originalCreateObjectURL = url.createObjectURL-// const originalRevokeObjectURL = url.revokeObjectURL-//-// let urlIndex = 0-// const createObjectURLMock = vi.fn(() => {-// urlIndex += 1-// return `blob:mock-url-${urlIndex}`-// })-// const revokeObjectURLMock = vi.fn()-// url.createObjectURL = createObjectURLMock-// url.revokeObjectURL = revokeObjectURLMock-//-// let unmount: (() => void) | undefined-// try {-// const renderResult = renderSupportFormPage()-// unmount = renderResult.unmount-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// })-//-// const fileInput = getAttachmentFileInput()-// const firstFile = new File(['first file'], 'first.png', { type: 'image/png' })-// const secondFile = new File(['second file'], 'second.jpg', { type: 'image/jpeg' })-// await userEvent.upload(fileInput, [firstFile, secondFile])-//-// await waitFor(() => {-// expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)-// })-// expect(createObjectURLMock).toHaveBeenCalledTimes(2)-//-// const firstRemoveButton = getAttachmentRemoveButtons(screen)[0]-// await userEvent.click(firstRemoveButton)-//-// await waitFor(() => {-// expect(getAttachmentRemoveButtons(screen)).toHaveLength(1)-// })-// expect(revokeObjectURLMock).toHaveBeenCalled()-//-// const thirdFile = new File(['third file'], 'third.png', { type: 'image/png' })-// await userEvent.upload(getAttachmentFileInput(), thirdFile)-//-// await waitFor(() => {-// expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)-// })-//-// expect(createObjectURLMock).toHaveBeenCalled()-// } finally {-// unmount?.()-// url.createObjectURL = originalCreateObjectURL-// url.revokeObjectURL = originalRevokeObjectURL-// }-// })-//-// test('cannot submit form again while it is submitting', async () => {-// const submission = createDeferred()-// const submitSpy = vi.fn()-//-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async () => {-// submitSpy()-// await submission.promise-// return HttpResponse.json({ ok: true })-// },-// })-//-// renderSupportFormPage()-//-// try {-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await selectCategoryOption(screen, 'Dashboard bug')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')-// })-// await userEvent.type(getSummaryField(screen), 'Unable to connect to database')-// await userEvent.type(getMessageField(screen), 'Connections time out after 30 seconds')-//-// const submitButton = getSubmitButton(screen)-// await userEvent.click(submitButton)-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// await waitFor(() => {-// expect(submitButton).toBeDisabled()-// })-//-// await userEvent.click(submitButton)-// expect(submitSpy).toHaveBeenCalledTimes(1)-// } finally {-// submission.resolve()-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// }-// }, 10_000)-//-// test('shows toast on submission error and allows form re-editing and resubmission', async () => {-// const submitSpy = vi.fn()-// const toastErrorSpy = vi.fn()-// const toastSuccessSpy = vi.fn()-//-// const { toast } = await import('sonner')-// vi.mocked(toast.error).mockImplementation(toastErrorSpy)-// vi.mocked(toast.success).mockImplementation(toastSuccessSpy)-//-// const errorMessage = 'Network error: Unable to reach server'-//-// // First attempt: return an error-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async () => {-// return HttpResponse.json({ message: errorMessage }, { status: 500 })-// },-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await selectCategoryOption(screen, 'Dashboard bug')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')-// })-//-// await userEvent.type(getSummaryField(screen), 'Cannot access settings')-// await userEvent.type(getMessageField(screen), 'Settings page shows 500 error')-//-// const submitButton = getSubmitButton(screen)-// await userEvent.click(submitButton)-//-// await waitFor(() => {-// expect(toastErrorSpy).toHaveBeenCalled()-// })-// expect(toastErrorSpy.mock.calls[0]?.[0]).toMatch(/Failed to submit support ticket/)-//-// await waitFor(() => {-// expect(submitButton).not.toBeDisabled()-// })-//-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// const messageField = getMessageField(screen)-// await userEvent.clear(messageField)-// await userEvent.type(messageField, 'Settings page shows 500 error - updated description')-//-// await userEvent.click(submitButton)-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload.subject).toBe('Cannot access settings')-// expect(payload.message).toBe('Settings page shows 500 error - updated description')-//-// await waitFor(() => {-// expect(toastSuccessSpy).toHaveBeenCalledWith('Support request sent. Thank you!')-// })-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// }, 10_000)-//-// test('submits support request with attachments and includes attachment URLs in message', async () => {-// const submitSpy = vi.fn()-//-// // Mock URL.createObjectURL and revokeObjectURL-// const url = URL as unknown as {-// createObjectURL?: (obj: Blob) => string-// revokeObjectURL?: (url: string) => void-// }-// const originalCreateObjectURL = url.createObjectURL-// const originalRevokeObjectURL = url.revokeObjectURL-//-// let urlIndex = 0-// const createObjectURLMock = vi.fn(() => {-// urlIndex += 1-// return `blob:mock-url-${urlIndex}`-// })-// const revokeObjectURLMock = vi.fn()-// url.createObjectURL = createObjectURLMock-// url.revokeObjectURL = revokeObjectURLMock-//-// // Mock the storage upload and createSignedUrls endpoints-// const signedUrls = [-// 'https://storage.example.com/signed/file1.png?token=abc123',-// 'https://storage.example.com/signed/file2.jpg?token=def456',-// ]-//-// const { createSupportStorageClient } = await import('../support-storage-client')-// const mockStorageClient = {-// storage: {-// from: vi.fn(() => ({-// upload: vi.fn(async (path: string) => ({-// data: { Id: path, Key: path, path },-// error: null,-// })),-// createSignedUrls: vi.fn(async (paths: Array<string>) => ({-// data: paths.map((path, idx) => ({-// signedUrl: signedUrls[idx] || `https://storage.example.com/signed/${path}`,-// path,-// error: null,-// })),-// error: null,-// })),-// })),-// },-// }-//-// vi.mocked(createSupportStorageClient).mockReturnValue(mockStorageClient as any)-//-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/auth/:ref/config',-// response: ({ params }) => {-// const { ref } = params as { ref: string }-// return HttpResponse.json({-// SITE_URL: `https://${ref}.example.com`,-// URI_ALLOW_LIST: `https://${ref}.example.com/auth`,-// } as any)-// },-// })-//-// let unmount: (() => void) | undefined-// try {-// const renderResult = renderSupportFormPage()-// unmount = renderResult.unmount-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')-// expect(getProjectSelector(screen)).toHaveTextContent('Project 1')-// })-//-// await selectCategoryOption(screen, 'Database unresponsive')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Database unresponsive')-// })-//-// await selectSeverityOption(screen, 'High')-// await waitFor(() => {-// expect(getSeveritySelector(screen)).toHaveTextContent('High')-// })-//-// const summaryField = getSummaryField(screen)-// await userEvent.clear(summaryField)-// await userEvent.type(summaryField, 'Query timeouts after maintenance')-//-// const messageField = getMessageField(screen)-// await userEvent.clear(messageField)-// await userEvent.type(-// messageField,-// 'All queries timing out after scheduled maintenance window'-// )-//-// const fileInput = getAttachmentFileInput()-// const firstFile = new File(['screenshot 1'], 'error-screenshot.png', { type: 'image/png' })-// const secondFile = new File(['screenshot 2'], 'logs-screenshot.jpg', { type: 'image/jpeg' })-// await userEvent.upload(fileInput, [firstFile, secondFile])-//-// await waitFor(() => {-// expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)-// })-//-// const supportAccessToggle = screen.getByRole('switch', {-// name: /allow support access to your project/i,-// })-// expect(supportAccessToggle).toBeChecked()-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload).toMatchObject({-// subject: 'Query timeouts after maintenance',-// category: 'Database_unresponsive',-// severity: 'High',-// projectRef: 'project-1',-// organizationSlug: 'org-1',-// library: '',-// affectedServices: '',-// allowSupportAccess: true,-// verified: true,-// tags: ['dashboard-support-form'],-// siteUrl: 'https://project-1.example.com',-// additionalRedirectUrls: 'https://project-1.example.com/auth',-// browserInformation: 'Chrome',-// })-//-// // Verify that attachment URLs are included in the message-// expect(payload.message).toContain('All queries timing out after scheduled maintenance window')-// expect(payload.message).toContain(signedUrls[0])-// expect(payload.message).toContain(signedUrls[1])-//-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// } finally {-// unmount?.()-// url.createObjectURL = originalCreateObjectURL-// url.revokeObjectURL = originalRevokeObjectURL-// vi.mocked(createSupportStorageClient).mockReset()-// }-// }, 10_000)-//-// test('can submit form with no organizations and no projects', async () => {-// const submitSpy = vi.fn()-//-// addAPIMock({-// method: 'get',-// path: '/platform/organizations',-// response: [],-// })-//-// addAPIMock({-// method: 'get',-// path: '/platform/projects',-// response: [],-// })-//-// addAPIMock({-// method: 'post',-// path: '/platform/feedback/send',-// response: async ({ request }) => {-// submitSpy(await request.json())-// return HttpResponse.json({ ok: true })-// },-// })-//-// renderSupportFormPage()-//-// await waitFor(() => {-// expect(getOrganizationSelector(screen)).toHaveTextContent('No specific organization')-// })-// await waitFor(() => {-// expect(getProjectSelector(screen)).toHaveTextContent('No specific project')-// })-//-// await selectCategoryOption(screen, 'Dashboard bug')-// await waitFor(() => {-// expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')-// })-//-// await userEvent.type(getSummaryField(screen), 'Cannot access my account')-// await userEvent.type(getMessageField(screen), 'I need help accessing my Supabase account')-//-// await userEvent.click(getSubmitButton(screen))-//-// await waitFor(() => {-// expect(submitSpy).toHaveBeenCalledTimes(1)-// })-//-// const payload = submitSpy.mock.calls[0]?.[0]-// expect(payload).toMatchObject({-// subject: 'Cannot access my account',-// message: 'I need help accessing my Supabase account',-// category: 'Dashboard_bug',-// projectRef: NO_PROJECT_MARKER,-// organizationSlug: NO_ORG_MARKER,-// library: '',-// affectedServices: '',-// allowSupportAccess: false,-// verified: true,-// tags: ['dashboard-support-form'],-// browserInformation: 'Chrome',-// })-//-// await waitFor(() => {-// expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()-// })-// }, 10_000)-// })+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'+// End of third-party imports++import { API_URL } from 'lib/constants'+import { HttpResponse, http } from 'msw'+import { createMockOrganization, createMockProject } from 'tests/helpers'+import { customRender } from 'tests/lib/custom-render'+import { addAPIMock, mswServer } from 'tests/lib/msw'+import { createMockProfileContext } from 'tests/lib/profile-helpers'+import { NO_ORG_MARKER, NO_PROJECT_MARKER } from '../SupportForm.utils'+import { SupportFormPage } from '../SupportFormPage'++type Screen = typeof screen++const mockOrganizations = [+ createMockOrganization({+ id: 1,+ slug: 'org-1',+ name: 'Organization 1',+ plan: { id: 'free', name: 'Free' },+ }),+ createMockOrganization({+ id: 2,+ slug: 'org-2',+ name: 'Organization 2',+ plan: { id: 'pro', name: 'Pro' },+ }),+]++const mockProjects = [+ {+ ...createMockProject({+ id: 1,+ ref: 'project-1',+ name: 'Project 1',+ organization_id: 1,+ }),+ organization_slug: 'org-1',+ preview_branch_refs: [],+ },+ {+ ...createMockProject({+ id: 2,+ ref: 'project-2',+ name: 'Project 2',+ organization_id: 2,+ }),+ organization_slug: 'org-2',+ preview_branch_refs: [],+ },+ {+ ...createMockProject({+ id: 3,+ ref: 'project-3',+ name: 'Project 3',+ organization_id: 1,+ }),+ organization_slug: 'org-1',+ preview_branch_refs: [],+ },+]++vi.mock('react-inlinesvg', () => ({+ __esModule: true,+ default: () => null,+}))++// Mock the support storage client module - will be configured per test+vi.mock('../support-storage-client', () => ({+ createSupportStorageClient: vi.fn(),+}))++// Mock sonner toast+vi.mock('sonner', () => ({+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ },+}))++vi.mock(import('common'), async (importOriginal) => {+ const actual = await importOriginal()+ vi.spyOn((actual as any).gotrueClient, 'getSession').mockResolvedValue({+ data: {+ session: {+ user: {+ id: '00000000-0000-0000-0000-000000000000',+ },+ },+ },+ })+ return {+ ...actual,+ useFlag: vi.fn().mockReturnValue(true),+ useParams: vi.fn().mockReturnValue({ ref: 'default' }),+ useIsLoggedIn: vi.fn().mockReturnValue(true),+ isFeatureEnabled: vi.fn((feature: any, disabledFeatures: any) => {+ if (typeof feature === 'string') {+ if (feature === 'support:show_client_libraries') {+ return true+ }+ return (actual as any).isFeatureEnabled(feature, disabledFeatures)+ }++ if (Array.isArray(feature)) {+ const result = (actual as any).isFeatureEnabled(feature, disabledFeatures)+ if (feature.includes('support:show_client_libraries')) {+ if (result && typeof result === 'object') {+ return {+ ...result,+ 'support:show_client_libraries': true,+ }+ }+ }+ return result+ }++ return (actual as any).isFeatureEnabled(feature, disabledFeatures)+ }),+ }+})++vi.mock(import('lib/gotrue'), async (importOriginal) => {+ const actual = await importOriginal()+ return {+ ...actual,+ auth: {+ ...(actual.auth as any),+ onAuthStateChange: vi.fn(),+ },+ }+})++const renderSupportFormPage = (options?: Parameters<typeof customRender>[1]) =>+ customRender(<SupportFormPage />, {+ profileContext: createMockProfileContext(),+ ...options,+ })++const getStatusLink = (screen: Screen) => {+ const statusLink = screen+ .getAllByRole('link')+ .find((el) => el.getAttribute('href') === 'https://status.supabase.com/')+ expect(statusLink).toBeDefined()+ return statusLink+}++const getOrganizationSelector = (screen: Screen) =>+ screen.getByRole('combobox', { name: 'Select an organization' })++const getProjectSelector = (screen: Screen) =>+ screen.getByRole('combobox', { name: 'Select a project' })++const getSummaryField = (screen: Screen) => screen.getByPlaceholderText(/summary of the problem/i)++const getMessageField = (screen: Screen) => screen.getByPlaceholderText(/describe the issue/i)++const getCategorySelector = (screen: Screen) =>+ screen.getByRole('combobox', { name: 'Select an issue' })++const getSubmitButton = (screen: Screen) =>+ screen.getByRole('button', { name: 'Send support request' })++const selectCategoryOption = async (screen: Screen, optionLabel: string) => {+ await userEvent.click(getCategorySelector(screen))+ const option = await screen.findByRole('option', {+ name: (accessibleName) => accessibleName.toLowerCase().startsWith(optionLabel.toLowerCase()),+ })+ await userEvent.click(option)+}++const getSeveritySelector = (screen: Screen) =>+ screen.getByRole('combobox', { name: 'Select a severity' })++const selectSeverityOption = async (screen: Screen, optionLabel: string) => {+ await userEvent.click(getSeveritySelector(screen))+ const option = await screen.findByRole('option', {+ name: (accessibleName) => accessibleName.toLowerCase().startsWith(optionLabel.toLowerCase()),+ })+ await userEvent.click(option)+}++const getLibrarySelector = (screen: Screen) =>+ screen.getByRole('combobox', { name: 'Select a library' })++const selectLibraryOption = async (screen: Screen, optionLabel: string) => {+ // await waitFor(() => {+ // expect(() => getLibrarySelector(screen)).not.toThrow()+ // })+ const selector = getLibrarySelector(screen)+ await userEvent.click(selector)+ const option = await screen.findByRole('option', {+ name: (accessibleName) => accessibleName.toLowerCase().startsWith(optionLabel.toLowerCase()),+ })+ await userEvent.click(option)+}++const getSupportForm = () => {+ const form = document.querySelector<HTMLFormElement>('form#support-form')+ expect(form).not.toBeNull()+ return form!+}++const getAttachmentFileInput = () => {+ const input = getSupportForm().querySelector<HTMLInputElement>(+ 'input[type="file"][accept*="image"]'+ )+ expect(input).not.toBeNull()+ return input!+}++const getAttachmentRemoveButtons = (screen: Screen) =>+ screen.queryAllByRole('button', { name: 'Remove attachment' })++const createDeferred = () => {+ let resolve!: () => void+ const promise = new Promise<void>((res) => {+ resolve = res+ })+ return { promise, resolve }+}++const createMockLocation = (search = '') => {+ const url = new URL('http://localhost:3000/')+ url.search = search.startsWith('?') || search === '' ? search : `?${search}`+ return {+ href: url.href,+ origin: url.origin,+ protocol: url.protocol,+ host: url.host,+ hostname: url.hostname,+ port: url.port,+ pathname: url.pathname,+ search: url.search,+ hash: url.hash,+ }+}++const originalUserAgent = window.navigator.userAgent++describe('SupportFormPage', () => {+ afterEach(() => {+ Object.defineProperty(window.navigator, 'userAgent', {+ value: originalUserAgent,+ configurable: true,+ })+ })++ beforeEach(() => {+ Object.defineProperty(window.navigator, 'userAgent', {+ value:+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',+ configurable: true,+ })+ Object.defineProperty(window, 'location', {+ value: createMockLocation(),+ writable: true,+ })+ Object.defineProperty(window, 'scrollTo', {+ value: vi.fn(),+ writable: true,+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations',+ response: mockOrganizations,+ })++ addAPIMock({+ method: 'get',+ path: '/platform/projects',+ response: mockProjects,+ })++ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref',+ response: ({ params }) => {+ const { ref } = params as { ref: string }+ const project = mockProjects.find((candidate) => candidate.ref === ref)+ return project+ ? HttpResponse.json(project)+ : HttpResponse.json({ msg: 'Project not found' }, { status: 404 })+ },+ })++ addAPIMock({+ method: 'get',+ path: '/platform/status',+ response: { is_healthy: true } as any,+ })++ addAPIMock({+ method: 'get',+ path: '/platform/auth/:ref/config',+ response: { SITE_URL: 'https://supabase.com', URI_ALLOW_LIST: '' } as any,+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/projects',+ response: ({ params, request }) => {+ const slug = (params as { slug: string }).slug+ const projects = mockProjects.filter((project) => project.organization_slug === slug)++ const url = new URL(request.url)+ const limit = Number(url.searchParams.get('limit') ?? projects.length)+ const offset = Number(url.searchParams.get('offset') ?? 0)+ const sort = url.searchParams.get('sort') ?? 'name_asc'++ const sorted = [...projects].sort((a, b) => {+ switch (sort) {+ case 'name_desc':+ return b.name.localeCompare(a.name)+ default:+ return a.name.localeCompare(b.name)+ }+ })++ const paginated = sorted.slice(offset, offset + limit)++ return HttpResponse.json({+ projects: paginated,+ pagination: {+ count: projects.length,+ limit,+ offset,+ },+ })+ },+ })++ mswServer.use(+ http.get('http://localhost:3000/img/supabase-logo.svg', () => HttpResponse.text(''))+ )+ })++ test('shows system status: healthy', async () => {+ renderSupportFormPage()++ await waitFor(() => {+ expect(getStatusLink(screen)).toHaveTextContent('All systems operational')+ })+ })++ test('shows system status: not healthy', async () => {+ addAPIMock({+ method: 'get',+ path: '/platform/status',+ response: { is_healthy: false } as any,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getStatusLink(screen)).toHaveTextContent('Active incident ongoing')+ })+ })++ test('shows system status: check failed', async () => {+ mswServer.use(+ http.get(`${API_URL}/platform/status`, () =>+ HttpResponse.json({ msg: 'Status service unavailable' }, { status: 500 })+ )+ )++ renderSupportFormPage()++ await waitFor(() => {+ expect(getStatusLink(screen)).toHaveTextContent('Failed to check status')+ })+ })++ test('loading a URL with a valid project slug prefills the organization and project', async () => {+ Object.defineProperty(window, 'location', {+ value: createMockLocation('?projectRef=project-3'),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(screen.getByRole('combobox', { name: 'Select a project' })).toHaveTextContent(+ 'Project 3'+ )+ })+ })++ test('loading a URL with no project slug falls back to first organization and project', async () => {+ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })+ })++ test('loading a URL with an invalid project slug falls back to first organization and project', async () => {+ mswServer.use(+ http.get(`${API_URL}/platform/projects/:ref`, () =>+ HttpResponse.json({ msg: 'Project not found' }, { status: 404 })+ )+ )+ Object.defineProperty(window, 'location', {+ value: createMockLocation('?projectRef=project-nonexistent'),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })+ })++ test('loading a URL with a message prefills the message field', async () => {+ const testMessage = 'This is a test support message from URL'+ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?message=${encodeURIComponent(testMessage)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getMessageField(screen)).toHaveValue(testMessage)+ })+ })++ test('loading a URL with a subject prefills the subject field', async () => {+ const testSubject = 'Test Subject'+ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?subject=${encodeURIComponent(testSubject)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ const subjectField = getSummaryField(screen)+ expect(subjectField).toHaveValue(testSubject)+ })+ })++ test('loading a URL with a category prefills the category field', async () => {+ const testCategory = 'Problem'+ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?category=${encodeURIComponent(testCategory)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')+ })+ })++ test('loading a URL with a category prefills the category field (case-insensitive)', async () => {+ const testCategory = 'dashboard_bug'+ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?category=${encodeURIComponent(testCategory)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')+ })+ })++ test('loading a URL with an invalid category gracefully falls back', async () => {+ const testCategory = 'Invalid'+ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?category=${encodeURIComponent(testCategory)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Select an issue')+ })+ })++ test('loading a URL with multiple initial fields fills them all in', async () => {+ const testCategory = 'Problem'+ const testSubject = 'Test Subject'+ Object.defineProperty(window, 'location', {+ value: createMockLocation(+ `?category=${encodeURIComponent(testCategory)}&subject=${encodeURIComponent(testSubject)}`+ ),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')+ expect(getSummaryField(screen)).toHaveValue(testSubject)+ })+ })++ test('includes Sentry issue ID from URL in submission payload', async () => {+ const sentryIssueId = 'mock-sentry-id'++ const submitSpy = vi.fn()+ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?sid=${encodeURIComponent(sentryIssueId)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await selectCategoryOption(screen, 'Dashboard bug')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')+ })++ await userEvent.type(getSummaryField(screen), 'Dashboard stopped loading')+ await userEvent.type(getMessageField(screen), 'The dashboard page loads blank after login')++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })+ expect(submitSpy.mock.calls[0]?.[0]?.dashboardSentryIssueId).toBe(sentryIssueId)+ }, 10_000)++ test('includes initial error message from URL in submission payload', async () => {+ const initialError = 'failed to fetch user data'+ const messageBody = 'The dashboard page loads blank after login'++ const submitSpy = vi.fn()+ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?error=${encodeURIComponent(initialError)}`),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await selectCategoryOption(screen, 'Dashboard bug')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')+ })++ await userEvent.type(getSummaryField(screen), 'Dashboard stopped loading')+ await userEvent.type(getMessageField(screen), messageBody)++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload?.message).toMatch(initialError)+ }, 10_000)++ test('submits support request with problem category, library, and affected services', async () => {+ const submitSpy = vi.fn()+ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ addAPIMock({+ method: 'get',+ path: '/platform/auth/:ref/config',+ response: ({ params }) => {+ const { ref } = params as { ref: string }+ return HttpResponse.json({+ SITE_URL: `https://${ref}.example.com`,+ URI_ALLOW_LIST: `https://${ref}.example.com/callbacks`,+ } as any)+ },+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await selectCategoryOption(screen, 'APIs and client libraries')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')+ })++ await selectSeverityOption(screen, 'High')+ await waitFor(() => {+ expect(getSeveritySelector(screen)).toHaveTextContent('High')+ })++ await selectLibraryOption(screen, 'JavaScript')+ await waitFor(() => {+ expect(getLibrarySelector(screen)).toHaveTextContent('Javascript')+ })++ const summaryField = getSummaryField(screen)+ await userEvent.clear(summaryField)+ await userEvent.type(summaryField, 'API requests failing in production')++ const messageField = getMessageField(screen)+ await userEvent.clear(messageField)+ await userEvent.type(messageField, 'Requests return status 500 when calling the RPC endpoint')++ const supportAccessToggle = screen.getByRole('switch', {+ name: /allow support access to your project/i,+ })+ expect(supportAccessToggle).toBeChecked()+ await userEvent.click(supportAccessToggle)+ expect(supportAccessToggle).not.toBeChecked()++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload).toMatchObject({+ subject: 'API requests failing in production',+ message: 'Requests return status 500 when calling the RPC endpoint',+ category: 'Problem',+ severity: 'High',+ projectRef: 'project-1',+ organizationSlug: 'org-1',+ library: 'javascript',+ affectedServices: '',+ allowSupportAccess: false,+ verified: true,+ tags: ['dashboard-support-form'],+ siteUrl: 'https://project-1.example.com',+ additionalRedirectUrls: 'https://project-1.example.com/callbacks',+ browserInformation: 'Chrome',+ })++ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ }, 10_000)++ test('submits urgent login issues ticket for a different organization', async () => {+ const submitSpy = vi.fn()++ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ addAPIMock({+ method: 'get',+ path: '/platform/auth/:ref/config',+ response: ({ params }) => {+ const { ref } = params as { ref: string }+ return HttpResponse.json({+ SITE_URL: `https://${ref}.supabase.dev`,+ URI_ALLOW_LIST: `https://${ref}.supabase.dev/redirect`,+ } as any)+ },+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ })++ await userEvent.click(getOrganizationSelector(screen))+ await userEvent.click(await screen.findByRole('option', { name: 'Organization 2' }))++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 2')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 2')+ })++ await selectCategoryOption(screen, 'Issues with logging in')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Issues with logging in')+ })++ await selectSeverityOption(screen, 'Urgent')+ await waitFor(() => {+ expect(getSeveritySelector(screen)).toHaveTextContent('Urgent')+ })++ const summaryField = getSummaryField(screen)+ await userEvent.clear(summaryField)+ await userEvent.type(summaryField, 'Cannot log in to dashboard')++ const messageField = getMessageField(screen)+ await userEvent.clear(messageField)+ await userEvent.type(messageField, 'MFA challenge fails with an unknown error code')++ expect(+ screen.queryByRole('switch', { name: /allow support access to your project/i })+ ).toBeNull()++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload).toMatchObject({+ subject: 'Cannot log in to dashboard',+ message: 'MFA challenge fails with an unknown error code',+ category: 'Login_issues',+ severity: 'Urgent',+ projectRef: 'project-2',+ organizationSlug: 'org-2',+ library: '',+ affectedServices: '',+ allowSupportAccess: false,+ verified: true,+ tags: ['dashboard-support-form'],+ siteUrl: 'https://project-2.supabase.dev',+ additionalRedirectUrls: 'https://project-2.supabase.dev/redirect',+ browserInformation: 'Chrome',+ })++ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ }, 10_000)++ test('submits database unresponsive ticket with initial error', async () => {+ const submitSpy = vi.fn()++ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ addAPIMock({+ method: 'get',+ path: '/platform/auth/:ref/config',+ response: ({ params }) => {+ const { ref } = params as { ref: string }+ return HttpResponse.json({+ SITE_URL: `https://${ref}.apps.supabase.co`,+ URI_ALLOW_LIST: `https://${ref}.apps.supabase.co/auth`,+ } as any)+ },+ })++ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref',+ response: ({ params }) => {+ const { ref } = params as { ref: string }+ const project = mockProjects.find((candidate) => candidate.ref === ref)+ return project+ ? HttpResponse.json(project)+ : HttpResponse.json({ msg: 'Project not found' }, { status: 404 })+ },+ })++ Object.defineProperty(window, 'location', {+ value: createMockLocation('?projectRef=project-3&error=Connection timeout detected'),+ writable: true,+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getProjectSelector(screen)).toHaveTextContent('Project 3')+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ })++ await selectCategoryOption(screen, 'Database unresponsive')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Database unresponsive')+ })++ await selectSeverityOption(screen, 'Normal')+ await waitFor(() => {+ expect(getSeveritySelector(screen)).toHaveTextContent('Normal')+ })++ const summaryField = getSummaryField(screen)+ await userEvent.clear(summaryField)+ await userEvent.type(summaryField, 'Database unreachable after upgrade')++ const messageField = getMessageField(screen)+ await userEvent.clear(messageField)+ await userEvent.type(messageField, 'Connections time out after 30 seconds')++ const supportAccessToggle = screen.getByRole('switch', {+ name: /allow support access to your project/i,+ })+ expect(supportAccessToggle).toBeChecked()++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload).toMatchObject({+ subject: 'Database unreachable after upgrade',+ category: 'Database_unresponsive',+ severity: 'Normal',+ projectRef: 'project-3',+ organizationSlug: 'org-1',+ library: '',+ affectedServices: '',+ allowSupportAccess: true,+ verified: true,+ tags: ['dashboard-support-form'],+ siteUrl: 'https://project-3.apps.supabase.co',+ additionalRedirectUrls: 'https://project-3.apps.supabase.co/auth',+ browserInformation: 'Chrome',+ })+ expect(payload.message).toBe(+ 'Connections time out after 30 seconds\nError: Connection timeout detected'+ )++ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ }, 10_000)++ test('when organization changes, project selector updates to match', async () => {+ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await userEvent.click(getOrganizationSelector(screen))+ await userEvent.click(screen.getByRole('option', { name: 'Organization 2' }))+ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 2')+ })++ await waitFor(() => {+ expect(getProjectSelector(screen)).toHaveTextContent('Project 2')+ })+ })++ test('AI Assistant suggestion displays when valid project and organization are selected', async () => {+ renderSupportFormPage()++ await waitFor(() => {+ expect(screen.getByText('Try the AI Assistant')).toBeInTheDocument()+ })+ })++ test('can upload attachments', async () => {+ const url = URL as unknown as {+ createObjectURL?: (obj: Blob) => string+ revokeObjectURL?: (url: string) => void+ }+ const originalCreateObjectURL = url.createObjectURL+ const originalRevokeObjectURL = url.revokeObjectURL++ let urlIndex = 0+ const createObjectURLMock = vi.fn(() => {+ urlIndex += 1+ return `blob:mock-url-${urlIndex}`+ })+ const revokeObjectURLMock = vi.fn()+ url.createObjectURL = createObjectURLMock+ url.revokeObjectURL = revokeObjectURLMock++ let unmount: (() => void) | undefined+ try {+ const renderResult = renderSupportFormPage()+ unmount = renderResult.unmount++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ })++ const fileInput = getAttachmentFileInput()+ const firstFile = new File(['first file'], 'first.png', { type: 'image/png' })+ const secondFile = new File(['second file'], 'second.jpg', { type: 'image/jpeg' })+ await userEvent.upload(fileInput, [firstFile, secondFile])++ await waitFor(() => {+ expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)+ })+ expect(createObjectURLMock).toHaveBeenCalledTimes(2)++ const firstRemoveButton = getAttachmentRemoveButtons(screen)[0]+ await userEvent.click(firstRemoveButton)++ await waitFor(() => {+ expect(getAttachmentRemoveButtons(screen)).toHaveLength(1)+ })+ expect(revokeObjectURLMock).toHaveBeenCalled()++ const thirdFile = new File(['third file'], 'third.png', { type: 'image/png' })+ await userEvent.upload(getAttachmentFileInput(), thirdFile)++ await waitFor(() => {+ expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)+ })++ expect(createObjectURLMock).toHaveBeenCalled()+ } finally {+ unmount?.()+ url.createObjectURL = originalCreateObjectURL+ url.revokeObjectURL = originalRevokeObjectURL+ }+ })++ test('cannot submit form again while it is submitting', async () => {+ const submission = createDeferred()+ const submitSpy = vi.fn()++ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async () => {+ submitSpy()+ await submission.promise+ return HttpResponse.json({ ok: true })+ },+ })++ renderSupportFormPage()++ try {+ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await selectCategoryOption(screen, 'Dashboard bug')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')+ })+ await userEvent.type(getSummaryField(screen), 'Unable to connect to database')+ await userEvent.type(getMessageField(screen), 'Connections time out after 30 seconds')++ const submitButton = getSubmitButton(screen)+ await userEvent.click(submitButton)++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ await waitFor(() => {+ expect(submitButton).toBeDisabled()+ })++ await userEvent.click(submitButton)+ expect(submitSpy).toHaveBeenCalledTimes(1)+ } finally {+ submission.resolve()+ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })+ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ }+ }, 10_000)++ test('shows toast on submission error and allows form re-editing and resubmission', async () => {+ const submitSpy = vi.fn()+ const toastErrorSpy = vi.fn()+ const toastSuccessSpy = vi.fn()++ const { toast } = await import('sonner')+ vi.mocked(toast.error).mockImplementation(toastErrorSpy)+ vi.mocked(toast.success).mockImplementation(toastSuccessSpy)++ const errorMessage = 'Network error: Unable to reach server'++ // First attempt: return an error+ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async () => {+ return HttpResponse.json({ message: errorMessage }, { status: 500 })+ },+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await selectCategoryOption(screen, 'Dashboard bug')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')+ })++ await userEvent.type(getSummaryField(screen), 'Cannot access settings')+ await userEvent.type(getMessageField(screen), 'Settings page shows 500 error')++ const submitButton = getSubmitButton(screen)+ await userEvent.click(submitButton)++ await waitFor(() => {+ expect(toastErrorSpy).toHaveBeenCalled()+ })+ expect(toastErrorSpy.mock.calls[0]?.[0]).toMatch(/Failed to submit support ticket/)++ await waitFor(() => {+ expect(submitButton).not.toBeDisabled()+ })++ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ const messageField = getMessageField(screen)+ await userEvent.clear(messageField)+ await userEvent.type(messageField, 'Settings page shows 500 error - updated description')++ await userEvent.click(submitButton)++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload.subject).toBe('Cannot access settings')+ expect(payload.message).toBe('Settings page shows 500 error - updated description')++ await waitFor(() => {+ expect(toastSuccessSpy).toHaveBeenCalledWith('Support request sent. Thank you!')+ })+ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ }, 10_000)++ test('submits support request with attachments and includes attachment URLs in message', async () => {+ const submitSpy = vi.fn()++ // Mock URL.createObjectURL and revokeObjectURL+ const url = URL as unknown as {+ createObjectURL?: (obj: Blob) => string+ revokeObjectURL?: (url: string) => void+ }+ const originalCreateObjectURL = url.createObjectURL+ const originalRevokeObjectURL = url.revokeObjectURL++ let urlIndex = 0+ const createObjectURLMock = vi.fn(() => {+ urlIndex += 1+ return `blob:mock-url-${urlIndex}`+ })+ const revokeObjectURLMock = vi.fn()+ url.createObjectURL = createObjectURLMock+ url.revokeObjectURL = revokeObjectURLMock++ // Mock the storage upload and createSignedUrls endpoints+ const signedUrls = [+ 'https://storage.example.com/signed/file1.png?token=abc123',+ 'https://storage.example.com/signed/file2.jpg?token=def456',+ ]++ const { createSupportStorageClient } = await import('../support-storage-client')+ const mockStorageClient = {+ storage: {+ from: vi.fn(() => ({+ upload: vi.fn(async (path: string) => ({+ data: { Id: path, Key: path, path },+ error: null,+ })),+ })),+ },+ }+ vi.mocked(createSupportStorageClient).mockReturnValue(mockStorageClient as any)++ mswServer.use(+ http.post('http://localhost:3000/api/generate-attachment-url', async ({ request }) => {+ const { filenames } = (await request.json()) as { filenames: string[] }+ const urls = filenames.map((_, index) => signedUrls[index] ?? '')+ return HttpResponse.json(urls)+ })+ )++ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ addAPIMock({+ method: 'get',+ path: '/platform/auth/:ref/config',+ response: ({ params }) => {+ const { ref } = params as { ref: string }+ return HttpResponse.json({+ SITE_URL: `https://${ref}.example.com`,+ URI_ALLOW_LIST: `https://${ref}.example.com/auth`,+ } as any)+ },+ })++ let unmount: (() => void) | undefined+ try {+ const renderResult = renderSupportFormPage()+ unmount = renderResult.unmount++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')+ expect(getProjectSelector(screen)).toHaveTextContent('Project 1')+ })++ await selectCategoryOption(screen, 'Database unresponsive')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Database unresponsive')+ })++ await selectSeverityOption(screen, 'High')+ await waitFor(() => {+ expect(getSeveritySelector(screen)).toHaveTextContent('High')+ })++ const summaryField = getSummaryField(screen)+ await userEvent.clear(summaryField)+ await userEvent.type(summaryField, 'Query timeouts after maintenance')++ const messageField = getMessageField(screen)+ await userEvent.clear(messageField)+ await userEvent.type(+ messageField,+ 'All queries timing out after scheduled maintenance window'+ )++ const fileInput = getAttachmentFileInput()+ const firstFile = new File(['screenshot 1'], 'error-screenshot.png', { type: 'image/png' })+ const secondFile = new File(['screenshot 2'], 'logs-screenshot.jpg', { type: 'image/jpeg' })+ await userEvent.upload(fileInput, [firstFile, secondFile])++ await waitFor(() => {+ expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)+ })++ const supportAccessToggle = screen.getByRole('switch', {+ name: /allow support access to your project/i,+ })+ expect(supportAccessToggle).toBeChecked()++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload).toMatchObject({+ subject: 'Query timeouts after maintenance',+ category: 'Database_unresponsive',+ severity: 'High',+ projectRef: 'project-1',+ organizationSlug: 'org-1',+ library: '',+ affectedServices: '',+ allowSupportAccess: true,+ verified: true,+ tags: ['dashboard-support-form'],+ siteUrl: 'https://project-1.example.com',+ additionalRedirectUrls: 'https://project-1.example.com/auth',+ browserInformation: 'Chrome',+ })++ // Verify that attachment URLs are included in the message+ expect(payload.message).toContain('All queries timing out after scheduled maintenance window')+ expect(payload.message).toContain(signedUrls[0])+ expect(payload.message).toContain(signedUrls[1])++ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ } finally {+ unmount?.()+ url.createObjectURL = originalCreateObjectURL+ url.revokeObjectURL = originalRevokeObjectURL+ vi.mocked(createSupportStorageClient).mockReset()+ }+ }, 10_000)++ test('can submit form with no organizations and no projects', async () => {+ const submitSpy = vi.fn()++ addAPIMock({+ method: 'get',+ path: '/platform/organizations',+ response: [],+ })++ addAPIMock({+ method: 'get',+ path: '/platform/projects',+ response: [],+ })++ addAPIMock({+ method: 'post',+ path: '/platform/feedback/send',+ response: async ({ request }) => {+ submitSpy(await request.json())+ return HttpResponse.json({ ok: true })+ },+ })++ renderSupportFormPage()++ await waitFor(() => {+ expect(getOrganizationSelector(screen)).toHaveTextContent('No specific organization')+ })+ await waitFor(() => {+ expect(getProjectSelector(screen)).toHaveTextContent('No specific project')+ })++ await selectCategoryOption(screen, 'Dashboard bug')+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')+ })++ await userEvent.type(getSummaryField(screen), 'Cannot access my account')+ await userEvent.type(getMessageField(screen), 'I need help accessing my Supabase account')++ await userEvent.click(getSubmitButton(screen))++ await waitFor(() => {+ expect(submitSpy).toHaveBeenCalledTimes(1)+ })++ const payload = submitSpy.mock.calls[0]?.[0]+ expect(payload).toMatchObject({+ subject: 'Cannot access my account',+ message: 'I need help accessing my Supabase account',+ category: 'Dashboard_bug',+ projectRef: NO_PROJECT_MARKER,+ organizationSlug: NO_ORG_MARKER,+ library: '',+ affectedServices: '',+ allowSupportAccess: false,+ verified: true,+ tags: ['dashboard-support-form'],+ browserInformation: 'Chrome',+ })++ await waitFor(() => {+ expect(screen.getByRole('heading', { name: /success/i })).toBeInTheDocument()+ })+ }, 10_000)+})diff --git a/apps/studio/data/support/generate-attachment-urls-mutation.ts b/apps/studio/data/support/generate-attachment-urls-mutation.tsnew file mode 100644index 00000000000..e8144fd7be5--- /dev/null+++ b/apps/studio/data/support/generate-attachment-urls-mutation.ts@@ -0,0 +1,68 @@+import { useMutation, UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { constructHeaders } from 'data/fetchers'+import { BASE_PATH } from 'lib/constants'+import { ResponseError } from 'types'++export type GenerateAttachmentURLsResponse = {+ title: string+ description: string+}++export type GenerateAttachmentURLsVariables = {+ filenames: string[]+}++export async function generateAttachmentURLs({ filenames }: GenerateAttachmentURLsVariables) {+ const headers = await constructHeaders()++ try {+ const response = await fetch(`${BASE_PATH}/api/generate-attachment-url`, {+ method: 'POST',+ headers,+ body: JSON.stringify({ filenames }),+ })++ if (!response.ok) {+ const status = response.status+ const message = await response.text()+ throw new Error(`Failed to generate attachment URLs at endpoint: ${status} ${message}`)+ }++ const signedUrls = await response.json()+ return signedUrls as string[]+ } catch (error: any) {+ // [Joshen] Should throw an error i think but doing so causes some errors in the unit tests which i'm not exactly sure how to resolve+ // [MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.+ return []+ }+}++type GenerateAttachmentURLsData = Awaited<ReturnType<typeof generateAttachmentURLs>>++export const useGenerateAttachmentURLsMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<GenerateAttachmentURLsData, ResponseError, GenerateAttachmentURLsVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<GenerateAttachmentURLsData, ResponseError, GenerateAttachmentURLsVariables>(+ (vars) => generateAttachmentURLs(vars),+ {+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to generate attachment URLS: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/apps/studio/lib/api/apiAuthenticate.ts b/apps/studio/lib/api/apiAuthenticate.tsindex 02922dfd80c..4b34341a37f 100644--- a/apps/studio/lib/api/apiAuthenticate.ts+++ b/apps/studio/lib/api/apiAuthenticate.ts@@ -33,7 +33,7 @@ export async function apiAuthenticate(* @returns* user with only id prop or detail object. It depends on requireUserDetail config*/-async function fetchUserClaims(req: NextApiRequest): Promise<JwtPayload> {+export async function fetchUserClaims(req: NextApiRequest): Promise<JwtPayload> {const token = req.headers.authorization?.replace(/bearer /i, '')if (!token) {throw new Error('missing access token')diff --git a/apps/studio/middleware.ts b/apps/studio/middleware.tsindex f531e687291..7b894c8de92 100644--- a/apps/studio/middleware.ts+++ b/apps/studio/middleware.ts@@ -21,6 +21,7 @@ const HOSTED_SUPPORTED_API_URLS = ['/check-cname','/edge-functions/test','/edge-functions/body',+ '/generate-attachment-url',]export function middleware(request: NextRequest) {diff --git a/apps/studio/pages/api/generate-attachment-url.ts b/apps/studio/pages/api/generate-attachment-url.tsnew file mode 100644index 00000000000..371aaecbf3f--- /dev/null+++ b/apps/studio/pages/api/generate-attachment-url.ts@@ -0,0 +1,83 @@+import { createClient } from '@supabase/supabase-js'+import type { NextApiRequest, NextApiResponse } from 'next'+import z from 'zod'++import apiWrapper from 'lib/api/apiWrapper'+import { getUserClaims } from 'lib/gotrue'++export const maxDuration = 120++const GenerateAttachmentUrlSchema = z.object({+ filenames: z.array(z.string()),+})++async function handlePost(req: NextApiRequest, res: NextApiResponse) {+ const { claims, error: userClaimsError } = await getUserClaims(req.headers.authorization!)+ if (userClaimsError || !claims) {+ return res.status(401).json({ error: { message: 'Unauthorized' } })+ }+ const userId = claims.sub++ const json = JSON.parse(req.body)+ const parseResult = GenerateAttachmentUrlSchema.safeParse(json)+ if (!parseResult.success) {+ return res.status(400).json({ error: { message: 'Invalid request body' } })+ }+ const filenames = parseResult.data.filenames++ const requestedPrefixes = [...new Set(filenames.map((filename) => filename.split('/')[0]))]+ if (requestedPrefixes.some((prefix) => prefix !== userId)) {+ return res+ .status(403)+ .json({ error: { message: 'Forbidden: Users can only access their own resources' } })+ }++ const adminSupabase = createClient(+ process.env.NEXT_PUBLIC_SUPPORT_API_URL!,+ process.env.SUPPORT_SUPABASE_SECRET_KEY!,+ {+ auth: {+ persistSession: false,+ autoRefreshToken: false,+ // @ts-expect-error+ multiTab: false,+ detectSessionInUrl: false,+ localStorage: {+ getItem: (_key: string) => undefined,+ setItem: (_key: string, _value: string) => {},+ removeItem: (_key: string) => {},+ },+ },+ }+ )++ // Create signed URLs for 10 years+ const { data, error: signedUrlError } = await adminSupabase.storage+ .from('support-attachments')+ .createSignedUrls(filenames, 10 * 365 * 24 * 60 * 60)+ if (signedUrlError) {+ console.error('Failed to sign URLs for attachments', signedUrlError)+ return res.status(500).json({ error: { message: 'Failed to sign URLs for attachments' } })+ }+ return res.status(200).json(data ? data.map((file) => file.signedUrl) : [])+}++async function handler(req: NextApiRequest, res: NextApiResponse) {+ const { method } = req++ switch (method) {+ case 'POST':+ return handlePost(req, res)+ default:+ res.setHeader('Allow', ['POST'])+ res.status(405).json({+ data: null,+ error: { message: `Method ${method} Not Allowed` },+ })+ }+}++const wrapper = (req: NextApiRequest, res: NextApiResponse) =>+ apiWrapper(req, res, handler, { withAuth: true })++export default wrapperdiff --git a/turbo.json b/turbo.jsonindex 5ae3d625e22..27e175cb07e 100644--- a/turbo.json+++ b/turbo.json@@ -113,6 +113,7 @@"IS_THROTTLED","AI_PRO_MODEL","AI_NORMAL_MODEL",+ "SUPPORT_SUPABASE_SECRET_KEY","NIMBUS_PROD_PROJECTS_URL"],"passThroughEnv": ["CURRENT_CLI_VERSION", "VERCEL_GIT_COMMIT_SHA"],