Skip to content

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

Refactor ConnectSheet + Add unit tests to cover various logic (#47764)

Joshen Lim66bfc5fdc319
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.tsx b/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.tsx
index fc3fb8158db..1d16e6fde89 100644
--- a/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.tsx
+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.tsx
@@ -5,8 +5,8 @@ import { useEffect, useMemo, useRef } from 'react'
import { cn, Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from 'ui'
import type { ConnectMode, ProjectKeys } from './Connect.types'
-import { CONNECT_MODES } from './Connect.types'
import { ConnectConfigSection, ModeSelector } from './ConnectConfigSection'
+import { resolveConnectSheetHydration } from './ConnectSheet.utils'
import { ConnectStepsSection } from './ConnectStepsSection'
import { useAvailableConnectModes } from './useAvailableConnectModes'
import { useConnectSheetParams } from './useConnectSheetParams'
@@ -18,23 +18,6 @@ import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useTrack } from '@/lib/telemetry/track'
import { useAppStateSnapshot } from '@/state/app-state'
-function isConnectMode(value: string): value is ConnectMode {
- return CONNECT_MODES.some((mode) => mode === value)
-}
-
-function mapConnectTabToMode(tab: string | null): ConnectMode | null {
- if (!tab) return null
- switch (tab) {
- case 'frameworks':
- case 'mobiles':
- return 'framework'
- case 'orms':
- return 'orm'
- default:
- return isConnectMode(tab) ? tab : null
- }
-}
-
export const ConnectSheet = () => {
const track = useTrack()
const prevShowConnect = useRef(false)
@@ -72,52 +55,21 @@ export const ConnectSheet = () => {
track('connect_sheet_opened', { source: connectSheetSource })
setConnectSheetSource('header_button')
- const effectiveTab = connectTab ?? storedPrefs.connectTab
- const effectiveFramework = queryFramework ?? storedPrefs.framework
- const effectiveUsing = queryUsing ?? storedPrefs.using
- const effectiveMethod = queryMethod ?? storedPrefs.method
- const effectiveType = queryType ?? storedPrefs.type
- const effectiveMcpClient = queryMcpClient ?? storedPrefs.mcpClient
-
- const mappedMode = mapConnectTabToMode(effectiveTab ?? null)
- if (mappedMode && availableModeIds.includes(mappedMode)) {
- setMode(mappedMode)
- }
-
- // Hydrate URL from storedPrefs so the URL reflects the restored state.
- // Only write params relevant to the active mode (matches how
- // handleModeChange/handleFieldChange manage URL params).
- const urlUpdates: Parameters<typeof setConnectParams>[0] = {}
- if (connectTab === null && effectiveTab) urlUpdates.connectTab = effectiveTab
- if (mappedMode === 'framework') {
- if (effectiveFramework) {
- updateField('framework', effectiveFramework)
- if (queryFramework === null) urlUpdates.framework = effectiveFramework
- if (effectiveUsing) {
- updateField('frameworkVariant', effectiveUsing)
- if (queryUsing === null) urlUpdates.using = effectiveUsing
- }
- }
- } else if (mappedMode === 'orm') {
- if (effectiveFramework) {
- updateField('orm', effectiveFramework)
- if (queryFramework === null) urlUpdates.framework = effectiveFramework
- }
- } else if (mappedMode === 'direct') {
- if (effectiveMethod) {
- updateField('connectionMethod', effectiveMethod)
- if (queryMethod === null) urlUpdates.method = effectiveMethod
- }
- if (effectiveType) {
- updateField('connectionType', effectiveType)
- if (queryType === null) urlUpdates.type = effectiveType
- }
- } else if (mappedMode === 'mcp') {
- if (effectiveMcpClient) {
- updateField('mcpClient', effectiveMcpClient)
- if (queryMcpClient === null) urlUpdates.mcpClient = effectiveMcpClient
- }
- }
+ const { mode, fieldUpdates, urlUpdates } = resolveConnectSheetHydration(
+ {
+ connectTab,
+ framework: queryFramework,
+ using: queryUsing,
+ method: queryMethod,
+ type: queryType,
+ mcpClient: queryMcpClient,
+ },
+ storedPrefs,
+ availableModeIds
+ )
+
+ if (mode) setMode(mode)
+ fieldUpdates.forEach(({ fieldId, value }) => updateField(fieldId, value))
if (Object.keys(urlUpdates).length > 0) setQueryParams(urlUpdates)
}, [
showConnect,
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.utils.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.utils.ts
new file mode 100644
index 00000000000..4aca1517558
--- /dev/null
+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectSheet.utils.ts
@@ -0,0 +1,101 @@
+import type { ConnectMode } from './Connect.types'
+import { CONNECT_MODES } from './Connect.types'
+import type { ConnectSheetPrefs } from './useConnectSheetParams'
+
+export type ConnectSheetQueryParams = {
+ connectTab: string | null
+ framework: string | null
+ using: string | null
+ method: string | null
+ type: string | null
+ mcpClient: string | null
+}
+
+export type ConnectSheetUrlUpdates = Partial<Record<keyof ConnectSheetQueryParams, string | null>>
+
+export type ConnectSheetFieldUpdate = { fieldId: string; value: string }
+
+export type ConnectSheetHydration = {
+ mode: ConnectMode | null
+ fieldUpdates: ConnectSheetFieldUpdate[]
+ urlUpdates: ConnectSheetUrlUpdates
+}
+
+function isConnectMode(value: string): value is ConnectMode {
+ return CONNECT_MODES.some((mode) => mode === value)
+}
+
+export function mapConnectTabToMode(tab: string | null): ConnectMode | null {
+ if (!tab) return null
+ switch (tab) {
+ case 'frameworks':
+ case 'mobiles':
+ return 'framework'
+ case 'orms':
+ return 'orm'
+ default:
+ return isConnectMode(tab) ? tab : null
+ }
+}
+
+/**
+ * Computes what should happen when the Connect sheet is opened: which mode/fields
+ * to hydrate from storedPrefs (falling back for whatever isn't already in the URL),
+ * and which URL params to backfill so the URL reflects the restored state.
+ *
+ * Field/URL updates are driven by `mappedMode` regardless of whether that mode is
+ * currently available — only the `mode` result (used to call `setMode`) is gated on
+ * `availableModeIds`, matching the sheet's pre-extraction behavior.
+ */
+export function resolveConnectSheetHydration(
+ query: ConnectSheetQueryParams,
+ storedPrefs: ConnectSheetPrefs,
+ availableModeIds: ConnectMode[]
+): ConnectSheetHydration {
+ const effectiveTab = query.connectTab ?? storedPrefs.connectTab ?? null
+ const effectiveFramework = query.framework ?? storedPrefs.framework ?? null
+ const effectiveUsing = query.using ?? storedPrefs.using ?? null
+ const effectiveMethod = query.method ?? storedPrefs.method ?? null
+ const effectiveType = query.type ?? storedPrefs.type ?? null
+ const effectiveMcpClient = query.mcpClient ?? storedPrefs.mcpClient ?? null
+
+ const mappedMode = mapConnectTabToMode(effectiveTab)
+ const mode = mappedMode && availableModeIds.includes(mappedMode) ? mappedMode : null
+
+ const fieldUpdates: ConnectSheetFieldUpdate[] = []
+ const urlUpdates: ConnectSheetUrlUpdates = {}
+
+ if (query.connectTab === null && effectiveTab) urlUpdates.connectTab = effectiveTab
+
+ if (mappedMode === 'framework') {
+ if (effectiveFramework) {
+ fieldUpdates.push({ fieldId: 'framework', value: effectiveFramework })
+ if (query.framework === null) urlUpdates.framework = effectiveFramework
+ if (effectiveUsing) {
+ fieldUpdates.push({ fieldId: 'frameworkVariant', value: effectiveUsing })
+ if (query.using === null) urlUpdates.using = effectiveUsing
+ }
+ }
+ } else if (mappedMode === 'orm') {
+ if (effectiveFramework) {
+ fieldUpdates.push({ fieldId: 'orm', value: effectiveFramework })
+ if (query.framework === null) urlUpdates.framework = effectiveFramework
+ }
+ } else if (mappedMode === 'direct') {
+ if (effectiveMethod) {
+ fieldUpdates.push({ fieldId: 'connectionMethod', value: effectiveMethod })
+ if (query.method === null) urlUpdates.method = effectiveMethod
+ }
+ if (effectiveType) {
+ fieldUpdates.push({ fieldId: 'connectionType', value: effectiveType })
+ if (query.type === null) urlUpdates.type = effectiveType
+ }
+ } else if (mappedMode === 'mcp') {
+ if (effectiveMcpClient) {
+ fieldUpdates.push({ fieldId: 'mcpClient', value: effectiveMcpClient })
+ if (query.mcpClient === null) urlUpdates.mcpClient = effectiveMcpClient
+ }
+ }
+
+ return { mode, fieldUpdates, urlUpdates }
+}
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx
index 717a0db9b16..aa472c7d04c 100644
--- a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx
+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx
@@ -16,8 +16,12 @@ import type {
} from './Connect.types'
import { ConnectSheetStep } from './ConnectSheetStep'
import {
+ resolveContentPath,
shouldFetchDataApiConfig,
shouldShowDataApiDisabledWarning,
+ shouldShowIpv4AddonNotice,
+ shouldShowSelfHostedMcpNotice,
+ shouldShowSessionPoolerNotice,
} from './ConnectStepsSection.utils'
import { CopyPromptAdmonition } from './CopyPromptAdmonition'
import { buildConnectionStringPooler, getConnectionStrings } from './DatabaseSettings.utils'
@@ -39,26 +43,6 @@ interface ConnectStepsSectionProps {
projectKeys: ProjectKeys
}
-/**
- * Resolves a content path template by replacing {{key}} placeholders with state values.
- * Empty segments are filtered out to handle optional state values like frameworkVariant.
- *
- * Examples:
- * - '{{framework}}/{{frameworkVariant}}/{{library}}' with state {framework: 'nextjs', frameworkVariant: 'app', library: 'supabasejs'}
- * → 'nextjs/app/supabasejs'
- * - '{{orm}}' with state {orm: 'prisma'}
- * → 'prisma'
- * - 'steps/install' (no templates)
- * → 'steps/install'
- */
-function resolveContentPath(template: string, state: ConnectState): string {
- return template
- .replace(/\{\{(\w+)\}\}/g, (_, key) => String(state[key] ?? ''))
- .split('/')
- .filter(Boolean)
- .join('/')
-}
-
/**
* Hook to fetch and prepare connection strings for step content.
*/
@@ -219,16 +203,22 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS
},
}
)
- const showIpv4AddonNotice =
- deploymentMode.isPlatform &&
- state.mode === 'direct' &&
- !ipv4Addon &&
- (state.connectionMethod === 'direct' ||
- (state.connectionMethod === 'transaction' && !state.useSharedPooler))
- const showSessionPoolerNotice =
- deploymentMode.isPlatform && state.mode === 'direct' && state.connectionMethod === 'session'
-
- const showSelfHostedMcpNotice = deploymentMode.isSelfHosted && state.mode === 'mcp'
+ const showIpv4AddonNotice = shouldShowIpv4AddonNotice({
+ isPlatform: deploymentMode.isPlatform,
+ mode: state.mode,
+ connectionMethod: state.connectionMethod,
+ useSharedPooler: state.useSharedPooler,
+ hasIpv4Addon: !!ipv4Addon,
+ })
+ const showSessionPoolerNotice = shouldShowSessionPoolerNotice({
+ isPlatform: deploymentMode.isPlatform,
+ mode: state.mode,
+ connectionMethod: state.connectionMethod,
+ })
+ const showSelfHostedMcpNotice = shouldShowSelfHostedMcpNotice({
+ isSelfHosted: deploymentMode.isSelfHosted,
+ mode: state.mode,
+ })
const shouldFetchDataApiStatus = shouldFetchDataApiConfig({
mode: state.mode,
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.test.ts
deleted file mode 100644
index d34db172b7d..00000000000
--- a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { describe, expect, test } from 'vitest'
-
-import type { ConnectMode } from './Connect.types'
-import {
- shouldFetchDataApiConfig,
- shouldShowDataApiDisabledWarning,
-} from './ConnectStepsSection.utils'
-
-const ALL_MODES: ConnectMode[] = ['framework', 'direct', 'orm', 'mcp', 'server']
-const MCP_WITH_DATABASE_TOOLS = {
- mode: 'mcp' as const,
- mcpFeatures: ['database'],
-}
-
-describe('shouldFetchDataApiConfig', () => {
- test('returns true for framework mode', () => {
- expect(shouldFetchDataApiConfig({ mode: 'framework' })).toBe(true)
- })
-
- test.each(['direct', 'orm', 'server', 'mcp'] as const)('returns false for %s mode', (mode) => {
- expect(shouldFetchDataApiConfig({ mode })).toBe(false)
- })
-
- test('returns false for mcp even when database tools are selected', () => {
- expect(shouldFetchDataApiConfig(MCP_WITH_DATABASE_TOOLS)).toBe(false)
- })
-})
-
-describe('shouldShowDataApiDisabledWarning', () => {
- test.each(ALL_MODES)('returns false while pending for %s mode', (mode) => {
- expect(
- shouldShowDataApiDisabledWarning({
- mode,
- isDataApiEnabled: false,
- isPending: true,
- isError: false,
- })
- ).toBe(false)
- })
-
- test('returns false when config query errored', () => {
- expect(
- shouldShowDataApiDisabledWarning({
- mode: 'framework',
- isDataApiEnabled: false,
- isPending: false,
- isError: true,
- })
- ).toBe(false)
- })
-
- test('returns true for framework when Data API is disabled', () => {
- expect(
- shouldShowDataApiDisabledWarning({
- mode: 'framework',
- isDataApiEnabled: false,
- isPending: false,
- isError: false,
- })
- ).toBe(true)
- })
-
- test.each(['direct', 'orm', 'server', 'mcp'] as const)(
- 'returns false for %s when Data API is disabled',
- (mode) => {
- expect(
- shouldShowDataApiDisabledWarning({
- mode,
- isDataApiEnabled: false,
- isPending: false,
- isError: false,
- })
- ).toBe(false)
- }
- )
-
- test('returns false for mcp with database tools selected when Data API is disabled', () => {
- expect(
- shouldShowDataApiDisabledWarning({
- ...MCP_WITH_DATABASE_TOOLS,
- isDataApiEnabled: false,
- isPending: false,
- isError: false,
- })
- ).toBe(false)
- })
-
- test('returns false when framework mode has Data API enabled', () => {
- expect(
- shouldShowDataApiDisabledWarning({
- mode: 'framework',
- isDataApiEnabled: true,
- isPending: false,
- isError: false,
- })
- ).toBe(false)
- })
-})
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.ts
index 95998f7a513..f24bd752559 100644
--- a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.utils.ts
@@ -1,4 +1,65 @@
-import type { ConnectMode } from './Connect.types'
+import type { ConnectMode, ConnectState } from './Connect.types'
+
+type FieldValue = ConnectState[string]
+
+/**
+ * Resolves a content path template by replacing {{key}} placeholders with state values.
+ * Empty segments are filtered out to handle optional state values like frameworkVariant.
+ *
+ * Examples:
+ * - '{{framework}}/{{frameworkVariant}}/{{library}}' with state {framework: 'nextjs', frameworkVariant: 'app', library: 'supabasejs'}
+ * → 'nextjs/app/supabasejs'
+ * - '{{orm}}' with state {orm: 'prisma'}
+ * → 'prisma'
+ * - 'steps/install' (no templates)
+ * → 'steps/install'
+ */
+export function resolveContentPath(template: string, state: ConnectState): string {
+ return template
+ .replace(/\{\{(\w+)\}\}/g, (_, key) => String(state[key] ?? ''))
+ .split('/')
+ .filter(Boolean)
+ .join('/')
+}
+
+export function shouldShowIpv4AddonNotice({
+ isPlatform,
+ mode,
+ connectionMethod,
+ useSharedPooler,
+ hasIpv4Addon,
+}: {
+ isPlatform: boolean
+ mode: ConnectMode
+ connectionMethod: FieldValue
+ useSharedPooler: FieldValue
+ hasIpv4Addon: boolean
+}): boolean {
+ if (!isPlatform || mode !== 'direct' || hasIpv4Addon) return false
+ return connectionMethod === 'direct' || (connectionMethod === 'transaction' && !useSharedPooler)
+}
+
+export function shouldShowSessionPoolerNotice({
+ isPlatform,
+ mode,
+ connectionMethod,
+}: {
+ isPlatform: boolean
+ mode: ConnectMode
+ connectionMethod: FieldValue
+}): boolean {
+ return isPlatform && mode === 'direct' && connectionMethod === 'session'
+}
+
+export function shouldShowSelfHostedMcpNotice({
+ isSelfHosted,
+ mode,
+}: {
+ isSelfHosted: boolean
+ mode: ConnectMode
+}): boolean {
+ return isSelfHosted && mode === 'mcp'
+}
export function shouldFetchDataApiConfig({ mode }: { mode: ConnectMode }): boolean {
return mode === 'framework'
diff --git a/apps/studio/components/interfaces/ConnectSheet/Connect.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.ts
similarity index 99%
rename from apps/studio/components/interfaces/ConnectSheet/Connect.utils.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.ts
index 8e67cec1437..c5b7a91096c 100644
--- a/apps/studio/components/interfaces/ConnectSheet/Connect.utils.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest'
-import { resolveFrameworkLibraryKey } from './Connect.utils'
+import { resolveFrameworkLibraryKey } from '../Connect.utils'
describe('Connect.utils:resolveFrameworkLibraryKey', () => {
test('should return null if no framework provided', () => {
diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.ts
new file mode 100644
index 00000000000..e86856d6942
--- /dev/null
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.ts
@@ -0,0 +1,176 @@
+import { describe, expect, test } from 'vitest'
+
+import type { ConnectMode } from '../Connect.types'
+import { mapConnectTabToMode, resolveConnectSheetHydration } from '../ConnectSheet.utils'
+import type { ConnectSheetQueryParams } from '../ConnectSheet.utils'
+import type { ConnectSheetPrefs } from '../useConnectSheetParams'
+
+const ALL_MODES: ConnectMode[] = ['framework', 'direct', 'orm', 'mcp', 'server']
+
+const EMPTY_QUERY: ConnectSheetQueryParams = {
+ connectTab: null,
+ framework: null,
+ using: null,
+ method: null,
+ type: null,
+ mcpClient: null,
+}
+
+const EMPTY_PREFS: ConnectSheetPrefs = {}
+
+describe('mapConnectTabToMode', () => {
+ test('returns null for null tab', () => {
+ expect(mapConnectTabToMode(null)).toBeNull()
+ })
+
+ test('returns null for an unrecognized tab', () => {
+ expect(mapConnectTabToMode('not-a-real-tab')).toBeNull()
+ })
+
+ test.each(['frameworks', 'mobiles'])('maps "%s" to framework mode', (tab) => {
+ expect(mapConnectTabToMode(tab)).toBe('framework')
+ })
+
+ test('maps "orms" to orm mode', () => {
+ expect(mapConnectTabToMode('orms')).toBe('orm')
+ })
+
+ test.each(ALL_MODES)('passes through an already-valid mode "%s"', (mode) => {
+ expect(mapConnectTabToMode(mode)).toBe(mode)
+ })
+})
+
+describe('resolveConnectSheetHydration', () => {
+ test('returns no mode, field updates, or URL updates when nothing is stored or in the URL', () => {
+ expect(resolveConnectSheetHydration(EMPTY_QUERY, EMPTY_PREFS, ALL_MODES)).toEqual({
+ mode: null,
+ fieldUpdates: [],
+ urlUpdates: {},
+ })
+ })
+
+ test('resolves mode from the URL when connectTab is already present', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'direct' },
+ EMPTY_PREFS,
+ ALL_MODES
+ )
+ expect(result.mode).toBe('direct')
+ // Already in the URL, so no need to backfill it.
+ expect(result.urlUpdates.connectTab).toBeUndefined()
+ })
+
+ test('falls back to storedPrefs.connectTab and backfills the URL', () => {
+ const result = resolveConnectSheetHydration(EMPTY_QUERY, { connectTab: 'mcp' }, ALL_MODES)
+ expect(result.mode).toBe('mcp')
+ expect(result.urlUpdates.connectTab).toBe('mcp')
+ })
+
+ test('does not set mode when the mapped mode is unavailable, but still computes field/URL updates', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'direct', method: 'transaction' },
+ EMPTY_PREFS,
+ ['framework'] // 'direct' is not available
+ )
+ expect(result.mode).toBeNull()
+ expect(result.fieldUpdates).toEqual([{ fieldId: 'connectionMethod', value: 'transaction' }])
+ })
+
+ describe('framework mode', () => {
+ test('hydrates framework field from storedPrefs and backfills the URL', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'frameworks' },
+ { framework: 'nextjs' },
+ ALL_MODES
+ )
+ expect(result.mode).toBe('framework')
+ expect(result.fieldUpdates).toEqual([{ fieldId: 'framework', value: 'nextjs' }])
+ expect(result.urlUpdates.framework).toBe('nextjs')
+ })
+
+ test('also hydrates frameworkVariant when both framework and using are present', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'frameworks' },
+ { framework: 'nextjs', using: 'app-router' },
+ ALL_MODES
+ )
+ expect(result.fieldUpdates).toEqual([
+ { fieldId: 'framework', value: 'nextjs' },
+ { fieldId: 'frameworkVariant', value: 'app-router' },
+ ])
+ expect(result.urlUpdates.using).toBe('app-router')
+ })
+
+ test('does not hydrate frameworkVariant when framework is missing', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'frameworks' },
+ { using: 'app-router' },
+ ALL_MODES
+ )
+ expect(result.fieldUpdates).toEqual([])
+ })
+
+ test('does not backfill URL params that are already present', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'frameworks', framework: 'nextjs', using: 'app-router' },
+ EMPTY_PREFS,
+ ALL_MODES
+ )
+ expect(result.urlUpdates.framework).toBeUndefined()
+ expect(result.urlUpdates.using).toBeUndefined()
+ // Field updates are still applied to local state even when the URL already has them.
+ expect(result.fieldUpdates).toEqual([
+ { fieldId: 'framework', value: 'nextjs' },
+ { fieldId: 'frameworkVariant', value: 'app-router' },
+ ])
+ })
+ })
+
+ test('orm mode hydrates the "orm" field id (not "framework")', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'orms' },
+ { framework: 'prisma' },
+ ALL_MODES
+ )
+ expect(result.mode).toBe('orm')
+ expect(result.fieldUpdates).toEqual([{ fieldId: 'orm', value: 'prisma' }])
+ expect(result.urlUpdates.framework).toBe('prisma')
+ })
+
+ describe('direct mode', () => {
+ test('hydrates connectionMethod and connectionType independently', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'direct' },
+ { method: 'session', type: 'ipv4' },
+ ALL_MODES
+ )
+ expect(result.fieldUpdates).toEqual([
+ { fieldId: 'connectionMethod', value: 'session' },
+ { fieldId: 'connectionType', value: 'ipv4' },
+ ])
+ expect(result.urlUpdates).toEqual({ method: 'session', type: 'ipv4' })
+ })
+ })
+
+ test('mcp mode hydrates mcpClient', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'mcp' },
+ { mcpClient: 'cursor' },
+ ALL_MODES
+ )
+ expect(result.mode).toBe('mcp')
+ expect(result.fieldUpdates).toEqual([{ fieldId: 'mcpClient', value: 'cursor' }])
+ expect(result.urlUpdates.mcpClient).toBe('cursor')
+ })
+
+ test('server mode has no extra fields to hydrate', () => {
+ const result = resolveConnectSheetHydration(
+ { ...EMPTY_QUERY, connectTab: 'server' },
+ { framework: 'nextjs', method: 'session' },
+ ALL_MODES
+ )
+ expect(result.mode).toBe('server')
+ expect(result.fieldUpdates).toEqual([])
+ expect(result.urlUpdates).toEqual({})
+ })
+})
diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.ts
new file mode 100644
index 00000000000..babff975249
--- /dev/null
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.ts
@@ -0,0 +1,228 @@
+import { describe, expect, test } from 'vitest'
+
+import type { ConnectMode, ConnectState } from '../Connect.types'
+import {
+ resolveContentPath,
+ shouldFetchDataApiConfig,
+ shouldShowDataApiDisabledWarning,
+ shouldShowIpv4AddonNotice,
+ shouldShowSelfHostedMcpNotice,
+ shouldShowSessionPoolerNotice,
+} from '../ConnectStepsSection.utils'
+
+const ALL_MODES: ConnectMode[] = ['framework', 'direct', 'orm', 'mcp', 'server']
+const MCP_WITH_DATABASE_TOOLS = {
+ mode: 'mcp' as const,
+ mcpFeatures: ['database'],
+}
+
+describe('shouldFetchDataApiConfig', () => {
+ test('returns true for framework mode', () => {
+ expect(shouldFetchDataApiConfig({ mode: 'framework' })).toBe(true)
+ })
+
+ test.each(['direct', 'orm', 'server', 'mcp'] as const)('returns false for %s mode', (mode) => {
+ expect(shouldFetchDataApiConfig({ mode })).toBe(false)
+ })
+
+ test('returns false for mcp even when database tools are selected', () => {
+ expect(shouldFetchDataApiConfig(MCP_WITH_DATABASE_TOOLS)).toBe(false)
+ })
+})
+
+describe('shouldShowDataApiDisabledWarning', () => {
+ test.each(ALL_MODES)('returns false while pending for %s mode', (mode) => {
+ expect(
+ shouldShowDataApiDisabledWarning({
+ mode,
+ isDataApiEnabled: false,
+ isPending: true,
+ isError: false,
+ })
+ ).toBe(false)
+ })
+
+ test('returns false when config query errored', () => {
+ expect(
+ shouldShowDataApiDisabledWarning({
+ mode: 'framework',
+ isDataApiEnabled: false,
+ isPending: false,
+ isError: true,
+ })
+ ).toBe(false)
+ })
+
+ test('returns true for framework when Data API is disabled', () => {
+ expect(
+ shouldShowDataApiDisabledWarning({
+ mode: 'framework',
+ isDataApiEnabled: false,
+ isPending: false,
+ isError: false,
+ })
+ ).toBe(true)
+ })
+
+ test.each(['direct', 'orm', 'server', 'mcp'] as const)(
+ 'returns false for %s when Data API is disabled',
+ (mode) => {
+ expect(
+ shouldShowDataApiDisabledWarning({
+ mode,
+ isDataApiEnabled: false,
+ isPending: false,
+ isError: false,
+ })
+ ).toBe(false)
+ }
+ )
+
+ test('returns false for mcp with database tools selected when Data API is disabled', () => {
+ expect(
+ shouldShowDataApiDisabledWarning({
+ ...MCP_WITH_DATABASE_TOOLS,
+ isDataApiEnabled: false,
+ isPending: false,
+ isError: false,
+ })
+ ).toBe(false)
+ })
+
+ test('returns false when framework mode has Data API enabled', () => {
+ expect(
+ shouldShowDataApiDisabledWarning({
+ mode: 'framework',
+ isDataApiEnabled: true,
+ isPending: false,
+ isError: false,
+ })
+ ).toBe(false)
+ })
+})
+
+describe('resolveContentPath', () => {
+ test('replaces multiple placeholders with state values', () => {
+ const state: ConnectState = {
+ mode: 'framework',
+ framework: 'nextjs',
+ frameworkVariant: 'app',
+ library: 'supabasejs',
+ }
+ expect(resolveContentPath('{{framework}}/{{frameworkVariant}}/{{library}}', state)).toBe(
+ 'nextjs/app/supabasejs'
+ )
+ })
+
+ test('filters out segments that resolve to an empty/missing state value', () => {
+ const state: ConnectState = { mode: 'framework', framework: 'nextjs' }
+ expect(resolveContentPath('{{framework}}/{{frameworkVariant}}', state)).toBe('nextjs')
+ })
+
+ test('returns the template unchanged when it has no placeholders', () => {
+ const state: ConnectState = { mode: 'direct' }
+ expect(resolveContentPath('steps/install', state)).toBe('steps/install')
+ })
+})
+
+describe('shouldShowIpv4AddonNotice', () => {
+ const BASE = {
+ isPlatform: true,
+ mode: 'direct' as const,
+ connectionMethod: 'direct',
+ useSharedPooler: false,
+ hasIpv4Addon: false,
+ }
+
+ test('returns true for a direct connection with no IPv4 addon', () => {
+ expect(shouldShowIpv4AddonNotice(BASE)).toBe(true)
+ })
+
+ test('returns true for the transaction pooler when not using the shared pooler', () => {
+ expect(
+ shouldShowIpv4AddonNotice({
+ ...BASE,
+ connectionMethod: 'transaction',
+ useSharedPooler: false,
+ })
+ ).toBe(true)
+ })
+
+ test('returns false for the transaction pooler when using the shared pooler (already IPv4)', () => {
+ expect(
+ shouldShowIpv4AddonNotice({ ...BASE, connectionMethod: 'transaction', useSharedPooler: true })
+ ).toBe(false)
+ })
+
+ test('returns false for the session pooler (has its own notice)', () => {
+ expect(shouldShowIpv4AddonNotice({ ...BASE, connectionMethod: 'session' })).toBe(false)
+ })
+
+ test('returns false when the IPv4 addon is already enabled', () => {
+ expect(shouldShowIpv4AddonNotice({ ...BASE, hasIpv4Addon: true })).toBe(false)
+ })
+
+ test('returns false when not in direct mode', () => {
+ expect(shouldShowIpv4AddonNotice({ ...BASE, mode: 'framework' })).toBe(false)
+ })
+
+ test('returns false when self-hosted (not platform)', () => {
+ expect(shouldShowIpv4AddonNotice({ ...BASE, isPlatform: false })).toBe(false)
+ })
+})
+
+describe('shouldShowSessionPoolerNotice', () => {
+ test('returns true for the session pooler on platform in direct mode', () => {
+ expect(
+ shouldShowSessionPoolerNotice({
+ isPlatform: true,
+ mode: 'direct',
+ connectionMethod: 'session',
+ })
+ ).toBe(true)
+ })
+
+ test('returns false when self-hosted (not platform)', () => {
+ expect(
+ shouldShowSessionPoolerNotice({
+ isPlatform: false,
+ mode: 'direct',
+ connectionMethod: 'session',
+ })
+ ).toBe(false)
+ })
+
+ test('returns false when not in direct mode', () => {
+ expect(
+ shouldShowSessionPoolerNotice({
+ isPlatform: true,
+ mode: 'framework',
+ connectionMethod: 'session',
+ })
+ ).toBe(false)
+ })
+
+ test('returns false for a non-session connection method', () => {
+ expect(
+ shouldShowSessionPoolerNotice({
+ isPlatform: true,
+ mode: 'direct',
+ connectionMethod: 'transaction',
+ })
+ ).toBe(false)
+ })
+})
+
+describe('shouldShowSelfHostedMcpNotice', () => {
+ test('returns true for mcp mode when self-hosted', () => {
+ expect(shouldShowSelfHostedMcpNotice({ isSelfHosted: true, mode: 'mcp' })).toBe(true)
+ })
+
+ test('returns false for mcp mode on platform', () => {
+ expect(shouldShowSelfHostedMcpNotice({ isSelfHosted: false, mode: 'mcp' })).toBe(false)
+ })
+
+ test('returns false when self-hosted but not in mcp mode', () => {
+ expect(shouldShowSelfHostedMcpNotice({ isSelfHosted: true, mode: 'direct' })).toBe(false)
+ })
+})
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.ts
similarity index 99%
rename from apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.ts
index 15efba43f21..834714b8276 100644
--- a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.ts
@@ -8,7 +8,7 @@ import {
parseConnectionParams,
PASSWORD_PLACEHOLDER,
resolveConnectionString,
-} from './ConnectionString.utils'
+} from '../ConnectionString.utils'
describe('parseConnectionParams', () => {
test('returns hidden defaults for an empty string', () => {
diff --git a/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.ts
similarity index 94%
rename from apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.ts
index 49f7bacfa52..f62ff2d7ce2 100644
--- a/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest'
-import { buildConnectPrompt } from './CopyPromptAdmonition'
+import { buildConnectPrompt } from '../CopyPromptAdmonition'
describe('buildConnectPrompt', () => {
test('uses redacted copy values instead of temporarily visible passwords', () => {
diff --git a/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.ts
similarity index 99%
rename from apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.ts
index 3df757d5617..c5697ed5655 100644
--- a/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.ts
@@ -4,7 +4,7 @@ import {
buildConnectionStringPooler,
getSelfHostedDirectStrings,
getSelfHostedPoolerStrings,
-} from './DatabaseSettings.utils'
+} from '../DatabaseSettings.utils'
import type { DeploymentMode } from '@/hooks/misc/useDeploymentMode'
const platform: DeploymentMode = { isPlatform: true, isCli: false, isSelfHosted: false }
diff --git a/apps/studio/components/interfaces/ConnectSheet/connect.resolver.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.ts
similarity index 99%
rename from apps/studio/components/interfaces/ConnectSheet/connect.resolver.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.ts
index 34f3ea26daa..002fe0c7f3d 100644
--- a/apps/studio/components/interfaces/ConnectSheet/connect.resolver.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.ts
@@ -6,8 +6,8 @@ import {
resetDependentFields,
resolveConditional,
resolveSteps,
-} from './connect.resolver'
-import type { ConditionalValue, ConnectSchema, ConnectState, StepTree } from './Connect.types'
+} from '../connect.resolver'
+import type { ConditionalValue, ConnectSchema, ConnectState, StepTree } from '../Connect.types'
// ============================================================================
// resolveConditional Tests
diff --git a/apps/studio/components/interfaces/ConnectSheet/connect.schema.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.ts
similarity index 99%
rename from apps/studio/components/interfaces/ConnectSheet/connect.schema.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.ts
index b40723f1e5e..5c6f8224acf 100644
--- a/apps/studio/components/interfaces/ConnectSheet/connect.schema.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'vitest'
-import { resolveSteps } from './connect.resolver'
-import { connectSchema, EXTRA_PACKAGES, INSTALL_COMMANDS } from './connect.schema'
-import type { ConnectState } from './Connect.types'
+import { resolveSteps } from '../connect.resolver'
+import { connectSchema, EXTRA_PACKAGES, INSTALL_COMMANDS } from '../connect.schema'
+import type { ConnectState } from '../Connect.types'
// ============================================================================
// Schema Structure Tests
diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.revealRace.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.revealRace.test.ts
new file mode 100644
index 00000000000..29e95c7dc55
--- /dev/null
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.revealRace.test.ts
@@ -0,0 +1,100 @@
+import { act, renderHook } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useConnectServerEnv } from '../useConnectServerEnv'
+import { getAPIKeysById } from '@/data/api-keys/api-key-id-query'
+import { useAPIKeys } from '@/data/api-keys/api-keys-query'
+import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+
+// Uses the real useRevealedSecret (not mocked) so the requestId invalidation
+// in clear() actually interacts with revealPromiseRef in useConnectServerEnv.
+vi.mock('@/hooks/misc/useCheckPermissions', () => ({
+ useAsyncCheckPermissions: vi.fn(),
+}))
+vi.mock('@/data/config/project-endpoint-query', () => ({
+ useProjectApiUrl: vi.fn(),
+}))
+vi.mock('@/data/api-keys/api-keys-query', () => ({
+ useAPIKeys: vi.fn(),
+}))
+vi.mock('@/data/api-keys/api-key-id-query', () => ({
+ getAPIKeysById: vi.fn(),
+}))
+
+const SECRET_KEY = { id: 'secret-id', api_key: 'sb_secret_abcdefghijklmnopqrstuv' }
+const SECRET_FULL = 'sb_secret_abcdefghijklmnopqrstuv_full'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((res) => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
+describe('useConnectServerEnv secret reveal (real useRevealedSecret)', () => {
+ beforeEach(() => {
+ vi.mocked(useAsyncCheckPermissions).mockReturnValue({
+ can: true,
+ isLoading: false,
+ } as any)
+ vi.mocked(useProjectApiUrl).mockReturnValue({
+ data: 'https://test.supabase.co',
+ isPending: false,
+ } as any)
+ vi.mocked(useAPIKeys).mockReturnValue({
+ data: { secretKey: SECRET_KEY, publishableKey: { api_key: 'sb_publishable_x' } },
+ isLoading: false,
+ } as any)
+ })
+
+ it('fires a fresh request on reveal after a hide interrupts an in-flight reveal, instead of reusing the invalidated promise', async () => {
+ const first = deferred<{ api_key: string }>()
+ const second = deferred<{ api_key: string }>()
+ vi.mocked(getAPIKeysById).mockReturnValueOnce(first.promise as any)
+ vi.mocked(getAPIKeysById).mockReturnValueOnce(second.promise as any)
+
+ const { result } = renderHook(() => useConnectServerEnv())
+
+ // Reveal is clicked, kicking off the first (never-resolving-yet) request.
+ let togglePromise1!: Promise<void>
+ act(() => {
+ togglePromise1 = result.current.secret.toggle()
+ })
+ expect(result.current.secret.isRevealed).toBe(true)
+
+ // Hide is clicked before that request settles.
+ act(() => {
+ result.current.secret.toggle()
+ })
+ expect(result.current.secret.isRevealed).toBe(false)
+
+ // Reveal is clicked again, still before the first request settles.
+ let togglePromise2!: Promise<void>
+ act(() => {
+ togglePromise2 = result.current.secret.toggle()
+ })
+ expect(result.current.secret.isRevealed).toBe(true)
+
+ // A brand new request must have been issued rather than reusing the
+ // (now-invalidated) first one.
+ expect(getAPIKeysById).toHaveBeenCalledTimes(2)
+
+ // The stale first request finally resolves; it must be ignored.
+ await act(async () => {
+ first.resolve({ api_key: SECRET_FULL + '_stale' })
+ await togglePromise1
+ })
+
+ // The second (live) request resolves with the real value.
+ await act(async () => {
+ second.resolve({ api_key: SECRET_FULL })
+ await togglePromise2
+ })
+
+ expect(result.current.secret.isRevealed).toBe(true)
+ expect(result.current.secret.isRevealing).toBe(false)
+ expect(result.current.secret.displayValue).toBe(SECRET_FULL)
+ })
+})
diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.ts
new file mode 100644
index 00000000000..6497fae5e94
--- /dev/null
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.ts
@@ -0,0 +1,164 @@
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useConnectServerEnv } from '../useConnectServerEnv'
+import { useRevealedSecret } from '@/components/interfaces/APIKeys/useRevealedSecret'
+import { useAPIKeys } from '@/data/api-keys/api-keys-query'
+import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+
+vi.mock('@/hooks/misc/useCheckPermissions', () => ({
+ useAsyncCheckPermissions: vi.fn(),
+}))
+vi.mock('@/data/config/project-endpoint-query', () => ({
+ useProjectApiUrl: vi.fn(),
+}))
+vi.mock('@/data/api-keys/api-keys-query', () => ({
+ useAPIKeys: vi.fn(),
+}))
+vi.mock('@/components/interfaces/APIKeys/useRevealedSecret', () => ({
+ useRevealedSecret: vi.fn(),
+}))
+
+const SECRET_KEY = { id: 'secret-id', api_key: 'sb_secret_abcdefghijklmnopqrstuv' }
+const SECRET_FULL = 'sb_secret_abcdefghijklmnopqrstuv_full'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
+describe('useConnectServerEnv secret reveal', () => {
+ const clearMock = vi.fn()
+ let revealMock: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ vi.mocked(useAsyncCheckPermissions).mockReturnValue({
+ can: true,
+ isLoading: false,
+ } as any)
+ vi.mocked(useProjectApiUrl).mockReturnValue({
+ data: 'https://test.supabase.co',
+ isPending: false,
+ } as any)
+ vi.mocked(useAPIKeys).mockReturnValue({
+ data: { secretKey: SECRET_KEY, publishableKey: { api_key: 'sb_publishable_x' } },
+ isLoading: false,
+ } as any)
+
+ clearMock.mockClear()
+ revealMock = vi.fn()
+ vi.mocked(useRevealedSecret).mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ reveal: revealMock,
+ clear: clearMock,
+ } as any)
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('shares one in-flight reveal request between a concurrent toggle() and getValue()', async () => {
+ const { promise, resolve } = deferred<string>()
+ revealMock.mockReturnValue(promise)
+
+ const { result } = renderHook(() => useConnectServerEnv())
+
+ // A caller invokes getValue() first (e.g. "Copy secret") while isRevealed
+ // is still false...
+ let getValuePromise!: Promise<string>
+ act(() => {
+ getValuePromise = result.current.secret.getValue()
+ })
+
+ // ...then, before that reveal resolves, the user clicks "Reveal".
+ let togglePromise!: Promise<void>
+ act(() => {
+ togglePromise = result.current.secret.toggle()
+ })
+
+ // Only one underlying request should have been made.
+ expect(revealMock).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ resolve(SECRET_FULL)
+ await Promise.all([getValuePromise, togglePromise])
+ })
+
+ expect(await getValuePromise).toBe(SECRET_FULL)
+ // getValue()'s closure was created while isRevealed was still false, but
+ // toggle() flipped it true before the reveal resolved. It must check the
+ // live state, not hide the secret the user just explicitly revealed.
+ expect(clearMock).not.toHaveBeenCalled()
+ expect(result.current.secret.isRevealed).toBe(true)
+ })
+
+ it('hides the secret again after a bare getValue() peek (no concurrent toggle)', async () => {
+ const { promise, resolve } = deferred<string>()
+ revealMock.mockReturnValue(promise)
+
+ const { result } = renderHook(() => useConnectServerEnv())
+
+ let getValuePromise!: Promise<string>
+ act(() => {
+ getValuePromise = result.current.secret.getValue()
+ })
+
+ await act(async () => {
+ resolve(SECRET_FULL)
+ await getValuePromise
+ })
+
+ expect(await getValuePromise).toBe(SECRET_FULL)
+ expect(clearMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('rejects toggle() with the original error attached as `cause`, and resets isRevealed', async () => {
+ const originalError = new Error('network down')
+ revealMock.mockRejectedValue(originalError)
+
+ const { result } = renderHook(() => useConnectServerEnv())
+
+ await expect(
+ act(async () => {
+ await result.current.secret.toggle()
+ })
+ ).rejects.toMatchObject({
+ message: 'Failed to reveal secret API key',
+ cause: originalError,
+ })
+
+ expect(result.current.secret.isRevealed).toBe(false)
+ })
+
+ it('auto-hides the secret after the reveal window elapses', async () => {
+ vi.useFakeTimers()
+ vi.mocked(useRevealedSecret).mockReturnValue({
+ data: SECRET_FULL,
+ isLoading: false,
+ reveal: revealMock.mockResolvedValue(SECRET_FULL),
+ clear: clearMock,
+ } as any)
+
+ const { result } = renderHook(() => useConnectServerEnv())
+
+ await act(async () => {
+ await result.current.secret.toggle()
+ })
+ expect(result.current.secret.isRevealed).toBe(true)
+
+ act(() => {
+ vi.advanceTimersByTime(10_000)
+ })
+
+ expect(result.current.secret.isRevealed).toBe(false)
+ expect(clearMock).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/studio/components/interfaces/ConnectSheet/useConnectSheetShortcut.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.ts
similarity index 97%
rename from apps/studio/components/interfaces/ConnectSheet/useConnectSheetShortcut.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.ts
index 464ec1b252c..d0b32bbe16b 100644
--- a/apps/studio/components/interfaces/ConnectSheet/useConnectSheetShortcut.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.ts
@@ -1,7 +1,7 @@
import { renderHook } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { useConnectSheetShortcut } from './useConnectSheetShortcut'
+import { useConnectSheetShortcut } from '../useConnectSheetShortcut'
import { PROJECT_STATUS } from '@/lib/constants'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
diff --git a/apps/studio/components/interfaces/ConnectSheet/useConnectState.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.ts
similarity index 99%
rename from apps/studio/components/interfaces/ConnectSheet/useConnectState.test.ts
rename to apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.ts
index 476f665ff21..558fcf0fd60 100644
--- a/apps/studio/components/interfaces/ConnectSheet/useConnectState.test.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.ts
@@ -1,7 +1,7 @@
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
-import { useConnectState } from './useConnectState'
+import { useConnectState } from '../useConnectState'
vi.mock('common', () => ({
useParams: () => ({ ref: 'test-ref' }),
diff --git a/apps/studio/components/interfaces/ConnectSheet/useConnectServerEnv.ts b/apps/studio/components/interfaces/ConnectSheet/useConnectServerEnv.ts
index 7e615472575..ab7128ea401 100644
--- a/apps/studio/components/interfaces/ConnectSheet/useConnectServerEnv.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/useConnectServerEnv.ts
@@ -1,11 +1,12 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { useRevealedSecret } from '@/components/interfaces/APIKeys/useRevealedSecret'
import { useAPIKeys } from '@/data/api-keys/api-keys-query'
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { useLatest } from '@/hooks/misc/useLatest'
const AUTO_HIDE_MS = 10_000
const SECRET_MASK = '••••••••••••••••••••'
@@ -52,21 +53,26 @@ export function useConnectServerEnv(): UseConnectServerEnvResult {
'service_api_keys'
)
+ const [isRevealed, setIsRevealed] = useState(false)
+ // So async callbacks below can check the current reveal state after an
+ // await, instead of the value closed over when they started.
+ const isRevealedRef = useLatest(isRevealed)
+
const { data: apiUrl, isPending: isLoadingUrl } = useProjectApiUrl({ projectRef })
+ const resolvedUrl = apiUrl || 'your-project-url'
+ const jwksUrl = apiUrl
+ ? new URL(JWKS_DISCOVERY_PATH, apiUrl).href
+ : `your-project-url${JWKS_DISCOVERY_PATH}`
+
const { data: keys, isLoading: isLoadingKeys } = useAPIKeys(
{ projectRef },
{ enabled: canReadAPIKeys }
)
-
- const canReveal = canReadAPIKeys
-
- const resolvedUrl = apiUrl || 'your-project-url'
const publishableKey = keys?.publishableKey?.api_key ?? keys?.anonKey?.api_key ?? ''
const secretKey = keys?.secretKey
-
- const jwksUrl = apiUrl
- ? new URL(JWKS_DISCOVERY_PATH, apiUrl).href
- : `your-project-url${JWKS_DISCOVERY_PATH}`
+ const maskedValue = secretKey?.api_key
+ ? `${secretKey.api_key.slice(0, 15)}${SECRET_MASK}`
+ : 'your-secret-key'
const {
data: revealedSecret,
@@ -75,44 +81,51 @@ export function useConnectServerEnv(): UseConnectServerEnvResult {
clear,
} = useRevealedSecret({ projectRef, id: secretKey?.id })
- const [isRevealed, setIsRevealed] = useState(false)
-
- useEffect(() => {
- if (!isRevealed || !revealedSecret) return
- const timer = setTimeout(() => {
- setIsRevealed(false)
- clear()
- }, AUTO_HIDE_MS)
- return () => clearTimeout(timer)
- }, [isRevealed, revealedSecret, clear])
-
- const maskedValue = secretKey?.api_key
- ? `${secretKey.api_key.slice(0, 15)}${SECRET_MASK}`
- : 'your-secret-key'
+ // toggle() and getSecretValue() can both decide to reveal before either
+ // resolves (e.g. clicking "Reveal" and "Copy" in quick succession); share
+ // one in-flight request rather than firing two and racing to set state.
+ const revealPromiseRef = useRef<ReturnType<typeof reveal> | null>(null)
+ const revealOnce = useCallback(() => {
+ if (!revealPromiseRef.current) {
+ revealPromiseRef.current = reveal().finally(() => {
+ revealPromiseRef.current = null
+ })
+ }
+ return revealPromiseRef.current
+ }, [reveal])
+
+ // clear() invalidates the in-flight reveal request (by request id) but
+ // doesn't know about revealPromiseRef, so a hide immediately followed by
+ // another reveal would otherwise reuse that now-invalidated promise
+ // instead of firing a fresh request.
+ const clearReveal = useCallback(() => {
+ revealPromiseRef.current = null
+ clear()
+ }, [clear])
const toggle = useCallback(async () => {
- if (!secretKey || !canReveal) return
+ if (!secretKey || !canReadAPIKeys) return
if (isRevealed) {
setIsRevealed(false)
- clear()
+ clearReveal()
} else {
setIsRevealed(true)
try {
- await reveal()
- } catch {
+ await revealOnce()
+ } catch (error) {
setIsRevealed(false)
- throw new Error('Failed to reveal secret API key')
+ throw new Error('Failed to reveal secret API key', { cause: error })
}
}
- }, [secretKey, canReveal, isRevealed, clear, reveal])
+ }, [secretKey, canReadAPIKeys, isRevealed, clearReveal, revealOnce])
const getSecretValue = useCallback(async () => {
- if (!secretKey || !canReveal) return 'your-secret-key'
+ if (!secretKey || !canReadAPIKeys) return 'your-secret-key'
if (revealedSecret) return revealedSecret
- const value = await reveal()
- if (!isRevealed) clear()
+ const value = await revealOnce()
+ if (!isRevealedRef.current) clearReveal()
return value ?? 'your-secret-key'
- }, [secretKey, canReveal, revealedSecret, reveal, isRevealed, clear])
+ }, [secretKey, canReadAPIKeys, revealedSecret, revealOnce, clearReveal])
const buildEnv = useCallback(async () => {
const secretValue = await getSecretValue()
@@ -124,6 +137,15 @@ export function useConnectServerEnv(): UseConnectServerEnvResult {
].join('\n')
}, [resolvedUrl, publishableKey, jwksUrl, getSecretValue])
+ useEffect(() => {
+ if (!isRevealed || !revealedSecret) return
+ const timer = setTimeout(() => {
+ setIsRevealed(false)
+ clearReveal()
+ }, AUTO_HIDE_MS)
+ return () => clearTimeout(timer)
+ }, [isRevealed, revealedSecret, clearReveal])
+
return {
isLoading: isLoadingUrl || isLoadingKeys || isLoadingPermission,
canReadAPIKeys,
@@ -132,7 +154,7 @@ export function useConnectServerEnv(): UseConnectServerEnvResult {
jwksUrl,
secret: {
exists: !!secretKey,
- canReveal,
+ canReveal: canReadAPIKeys,
isRevealed,
isRevealing,
maskedValue,
diff --git a/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts b/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts
index 9d9c1952460..4182fc684d4 100644
--- a/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts
+++ b/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts
@@ -135,7 +135,7 @@ function getFieldOptionsFromSource({
const region = formatDatabaseRegion(db?.region ?? '')
const id = formatDatabaseID(db.identifier ?? '')
const label = db.identifier.includes('-rr-')
- ? `Read Replica (${region} - ${id}}`
+ ? `Read Replica (${region} - ${id})`
: 'Primary Database'
return { value: db.identifier, label }
})