Skip to content

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

feat(studio): add Explorer onboarding and startup preference (#50493)

Saxon Fletcher0043e6f53b19
diff --git a/apps/studio/components/interfaces/Account/Preferences/DashboardSettingsToggles.tsx b/apps/studio/components/interfaces/Account/Preferences/DashboardSettingsToggles.tsx
index fac9e41f0ed..b9f57404293 100644
--- a/apps/studio/components/interfaces/Account/Preferences/DashboardSettingsToggles.tsx
+++ b/apps/studio/components/interfaces/Account/Preferences/DashboardSettingsToggles.tsx
@@ -1,11 +1,23 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
-import { Card, Form } from 'ui'
+import {
+ Card,
+ CardContent,
+ Form,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import * as z from 'zod'
import { DashboardToggle } from './DashboardToggle'
import { useIsInlineEditorSetting, useIsQueueOperationsSetting } from './useDashboardSettings'
+import { explorerHomeSchema, useExplorerPreferences } from './useExplorerPreferences'
+import { useIsExplorerEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useTrack } from '@/lib/telemetry/track'
const DashboardSettingsSchema = z.object({
@@ -14,6 +26,8 @@ const DashboardSettingsSchema = z.object({
})
export const DashboardSettingsToggles = () => {
+ const isExplorerEnabled = useIsExplorerEnabled()
+ const { home, setHome, isReady } = useExplorerPreferences()
const { inlineEditorEnabled, setInlineEditorEnabled } = useIsInlineEditorSetting()
const { isQueueOperationsEnabled, setIsQueueOperationsEnabled } = useIsQueueOperationsSetting()
@@ -52,6 +66,33 @@ export const DashboardSettingsToggles = () => {
return (
<Form {...form}>
<Card>
+ {isExplorerEnabled && (
+ <CardContent>
+ <FormItemLayout
+ isReactForm={false}
+ label="Explorer startup"
+ description="Choose how Explorer opens."
+ layout="flex-row-reverse"
+ >
+ <Select
+ value={home}
+ onValueChange={(value) => {
+ const result = explorerHomeSchema.safeParse(value)
+ if (result.success) setHome(result.data)
+ }}
+ disabled={!isReady}
+ >
+ <SelectTrigger aria-label="Explorer startup">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="home">Start page</SelectItem>
+ <SelectItem value="query">SQL query</SelectItem>
+ </SelectContent>
+ </Select>
+ </FormItemLayout>
+ </CardContent>
+ )}
<DashboardToggle
form={form}
name="inlineEditorEnabled"
diff --git a/apps/studio/components/interfaces/Account/Preferences/ExplorerHomePreference.tsx b/apps/studio/components/interfaces/Account/Preferences/ExplorerHomePreference.tsx
new file mode 100644
index 00000000000..4b3c46bc3cc
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/Preferences/ExplorerHomePreference.tsx
@@ -0,0 +1,56 @@
+import { RadioGroupCard, RadioGroupCardItem } from 'ui'
+
+import { ExplorerHomePreview } from './ExplorerHomePreview'
+import { explorerHomeSchema, type ExplorerHome } from './useExplorerPreferences'
+
+interface ExplorerHomePreferenceProps {
+ value: ExplorerHome
+ onValueChange: (value: ExplorerHome) => void
+ disabled?: boolean
+}
+
+export const ExplorerHomePreference = ({
+ value,
+ onValueChange,
+ disabled,
+}: ExplorerHomePreferenceProps) => (
+ <RadioGroupCard
+ aria-label="Choose how Explorer opens"
+ value={value}
+ onValueChange={(value) => {
+ const result = explorerHomeSchema.safeParse(value)
+ if (result.success) onValueChange(result.data)
+ }}
+ disabled={disabled}
+ className="grid-cols-1 gap-3 sm:grid-cols-2"
+ >
+ <RadioGroupCardItem
+ value="home"
+ className="w-full p-4"
+ label={
+ <span className="flex flex-col gap-1">
+ <span className="text-sm text-foreground">Start page</span>
+ <span className="text-sm leading-relaxed text-foreground-light">
+ Choose a query, chat, or notebook to get started.
+ </span>
+ </span>
+ }
+ >
+ <ExplorerHomePreview home="home" />
+ </RadioGroupCardItem>
+ <RadioGroupCardItem
+ value="query"
+ className="w-full p-4"
+ label={
+ <span className="flex flex-col gap-1">
+ <span className="text-sm text-foreground">SQL query</span>
+ <span className="text-sm leading-relaxed text-foreground-light">
+ Open a new query tab, ready to write SQL.
+ </span>
+ </span>
+ }
+ >
+ <ExplorerHomePreview home="query" />
+ </RadioGroupCardItem>
+ </RadioGroupCard>
+)
diff --git a/apps/studio/components/interfaces/Account/Preferences/ExplorerHomePreview.tsx b/apps/studio/components/interfaces/Account/Preferences/ExplorerHomePreview.tsx
new file mode 100644
index 00000000000..c0407221b93
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/Preferences/ExplorerHomePreview.tsx
@@ -0,0 +1,47 @@
+import type { ExplorerHome } from './useExplorerPreferences'
+
+export const ExplorerHomePreview = ({ home }: { home: ExplorerHome }) => (
+ <svg
+ viewBox="0 0 240 128"
+ fill="none"
+ aria-hidden="true"
+ className="mb-2 w-full rounded border border-default bg-surface-100 stroke-border"
+ >
+ <path d="M0 0h48v128H0z" className="fill-muted stroke-none" />
+ <path d="M48 0v128" />
+ <g className="fill-foreground-muted/40 stroke-none">
+ <rect x="8" y="15" width="30" height="4" rx="1" />
+ <rect x="8" y="32" width="26" height="3" rx="1" />
+ <rect x="8" y="44" width="20" height="3" rx="1" />
+ <rect x="8" y="56" width="24" height="3" rx="1" />
+ </g>
+
+ {home === 'home' ? (
+ <>
+ <rect x="88" y="48" width="112" height="22" rx="3" />
+ <rect x="88" y="78" width="52" height="17" rx="2" />
+ <rect x="148" y="78" width="52" height="17" rx="2" />
+ <g className="fill-foreground-muted/40 stroke-none">
+ <rect x="112" y="35" width="64" height="4" rx="1" />
+ <rect x="96" y="57" width="58" height="3" rx="1" />
+ <rect x="96" y="85" width="32" height="3" rx="1" />
+ <rect x="156" y="85" width="32" height="3" rx="1" />
+ </g>
+ </>
+ ) : (
+ <>
+ <path d="M48 65h192" />
+ <g className="fill-foreground-muted/40 stroke-none">
+ <rect x="62" y="18" width="30" height="3" rx="1" />
+ <rect x="98" y="18" width="18" height="3" rx="1" />
+ <rect x="70" y="28" width="52" height="3" rx="1" />
+ <rect x="62" y="38" width="22" height="3" rx="1" />
+ <rect x="90" y="38" width="40" height="3" rx="1" />
+ </g>
+ <rect x="58" y="77" width="172" height="12" className="fill-muted stroke-none" />
+ <rect x="58" y="77" width="172" height="36" rx="2" />
+ <path d="M58 89h172M58 101h172M105 77v36M168 77v36" />
+ </>
+ )}
+ </svg>
+)
diff --git a/apps/studio/components/interfaces/Account/Preferences/useExplorerPreferences.test.tsx b/apps/studio/components/interfaces/Account/Preferences/useExplorerPreferences.test.tsx
new file mode 100644
index 00000000000..9cfb6d6696e
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/Preferences/useExplorerPreferences.test.tsx
@@ -0,0 +1,187 @@
+import { QueryClient } from '@tanstack/react-query'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { clearLocalStorage, LOCAL_STORAGE_KEYS } from 'common'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useExplorerPreferences } from './useExplorerPreferences'
+import type { ProfileContextType } from '@/lib/profile'
+import { customRenderHook, CustomWrapper } from '@/tests/lib/custom-render'
+import { createMockProfile, createMockProfileContext } from '@/tests/lib/profile-helpers'
+
+const mockIsPlatform = vi.hoisted(() => ({ value: true }))
+
+vi.mock('common', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('common')>()),
+ get IS_PLATFORM() {
+ return mockIsPlatform.value
+ },
+}))
+
+const storageKey = LOCAL_STORAGE_KEYS.EXPLORER_PREFERENCES
+const renderPreferences = (accountId = 1, queryClient?: QueryClient) =>
+ customRenderHook(useExplorerPreferences, {
+ queryClient,
+ profileContext: createMockProfileContext({ profile: createMockProfile({ id: accountId }) }),
+ })
+
+beforeEach(() => {
+ mockIsPlatform.value = true
+})
+afterEach(() => localStorage.clear())
+
+describe('useExplorerPreferences', () => {
+ it('defaults to the start page with onboarding incomplete', async () => {
+ const { result } = renderPreferences()
+ await waitFor(() => expect(result.current.isReady).toBe(true))
+ expect(result.current.home).toBe('home')
+ expect(result.current.hasCompletedOnboarding).toBe(false)
+ })
+
+ it('persists both settings across remounts and sign-out storage cleanup', async () => {
+ const first = renderPreferences()
+ await waitFor(() => expect(first.result.current.isReady).toBe(true))
+ act(() => {
+ first.result.current.setHome('query')
+ first.result.current.completeOnboarding()
+ })
+ await waitFor(() => expect(first.result.current.hasCompletedOnboarding).toBe(true))
+ first.unmount()
+ clearLocalStorage()
+
+ const second = renderPreferences()
+ await waitFor(() => expect(second.result.current.isReady).toBe(true))
+ expect(second.result.current.home).toBe('query')
+ expect(second.result.current.hasCompletedOnboarding).toBe(true)
+
+ act(() => second.result.current.setHome('home'))
+ expect(second.result.current.hasCompletedOnboarding).toBe(true)
+ })
+
+ it('isolates accounts and preserves other accounts when saving', async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const first = renderPreferences(1, queryClient)
+ const second = renderPreferences(2, queryClient)
+ await waitFor(() => expect(first.result.current.isReady).toBe(true))
+ await waitFor(() => expect(second.result.current.isReady).toBe(true))
+
+ act(() => {
+ first.result.current.setHome('query')
+ first.result.current.completeOnboarding()
+ })
+ expect(second.result.current.home).toBe('home')
+ expect(second.result.current.hasCompletedOnboarding).toBe(false)
+ act(() => second.result.current.completeOnboarding())
+
+ expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual({
+ '1': { home: 'query', hasCompletedOnboarding: true },
+ '2': { home: 'home', hasCompletedOnboarding: true },
+ })
+ })
+
+ it('synchronizes separate consumers of the same account preference', async () => {
+ const queryClient = new QueryClient()
+ const first = renderPreferences(1, queryClient)
+ const second = renderPreferences(1, queryClient)
+ await waitFor(() => expect(first.result.current.isReady).toBe(true))
+ act(() => first.result.current.setHome('query'))
+ await waitFor(() => expect(second.result.current.home).toBe('query'))
+ })
+
+ it('does not read or write another account while the profile is loading', async () => {
+ const { result } = customRenderHook(useExplorerPreferences, {
+ profileContext: {
+ ...createMockProfileContext(),
+ profile: undefined,
+ isLoading: true,
+ isSuccess: false,
+ },
+ })
+ act(() => {
+ result.current.setHome('query')
+ result.current.completeOnboarding()
+ })
+ expect(result.current.isReady).toBe(false)
+ expect(localStorage.getItem(storageKey)).toBeNull()
+ })
+
+ it.each([
+ 'null',
+ '[]',
+ '42',
+ '{}',
+ '{"1":null}',
+ '{"1":{"home":"invalid","hasCompletedOnboarding":"true"}}',
+ 'invalid JSON',
+ ])('recovers from invalid stored preferences: %s', async (stored) => {
+ localStorage.setItem(storageKey, stored)
+ const { result } = renderPreferences()
+ await waitFor(() => expect(result.current.isReady).toBe(true))
+ expect(result.current.home).toBe('home')
+ expect(result.current.hasCompletedOnboarding).toBe(false)
+ act(() => result.current.completeOnboarding())
+ expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual({
+ '1': { home: 'home', hasCompletedOnboarding: true },
+ })
+ })
+
+ describe('self-hosted', () => {
+ beforeEach(() => {
+ mockIsPlatform.value = false
+ })
+
+ it('keeps the preference and onboarding completion when the profile loads', async () => {
+ const queryClient = new QueryClient()
+ let profileContext: ProfileContextType = {
+ ...createMockProfileContext(),
+ profile: undefined,
+ isLoading: true,
+ isSuccess: false,
+ }
+ const { result, rerender } = renderHook(useExplorerPreferences, {
+ wrapper: ({ children }) => (
+ <CustomWrapper queryClient={queryClient} profileContext={profileContext}>
+ {children}
+ </CustomWrapper>
+ ),
+ })
+ await waitFor(() => expect(result.current.isReady).toBe(true))
+ act(() => {
+ result.current.setHome('query')
+ result.current.completeOnboarding()
+ })
+ await waitFor(() => expect(result.current.hasCompletedOnboarding).toBe(true))
+
+ profileContext = createMockProfileContext()
+ rerender()
+
+ expect(result.current.home).toBe('query')
+ expect(result.current.hasCompletedOnboarding).toBe(true)
+ act(() => result.current.setHome('home'))
+ expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual({
+ 'self-hosted': { home: 'home', hasCompletedOnboarding: true },
+ })
+ })
+
+ it('uses the self-hosted key even when a profile is already available', async () => {
+ const accountPreferences = { home: 'home', hasCompletedOnboarding: false }
+ localStorage.setItem(
+ storageKey,
+ JSON.stringify({
+ 'self-hosted': { home: 'query', hasCompletedOnboarding: true },
+ '1': accountPreferences,
+ })
+ )
+ const { result } = customRenderHook(useExplorerPreferences, {
+ profileContext: createMockProfileContext(),
+ })
+ await waitFor(() => expect(result.current.isReady).toBe(true))
+ expect(result.current.home).toBe('query')
+ expect(result.current.hasCompletedOnboarding).toBe(true)
+ act(() => result.current.setHome('home'))
+ expect(JSON.parse(localStorage.getItem(storageKey)!)).toEqual({
+ 'self-hosted': { home: 'home', hasCompletedOnboarding: true },
+ '1': accountPreferences,
+ })
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Account/Preferences/useExplorerPreferences.ts b/apps/studio/components/interfaces/Account/Preferences/useExplorerPreferences.ts
new file mode 100644
index 00000000000..3430602041a
--- /dev/null
+++ b/apps/studio/components/interfaces/Account/Preferences/useExplorerPreferences.ts
@@ -0,0 +1,43 @@
+import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'common'
+import { z } from 'zod'
+
+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
+import { useProfile } from '@/lib/profile'
+
+export const explorerHomeSchema = z.enum(['home', 'query'])
+export type ExplorerHome = z.infer<typeof explorerHomeSchema>
+
+const preferencesSchema = z.object({
+ home: explorerHomeSchema.catch('home'),
+ hasCompletedOnboarding: z.boolean().catch(false),
+})
+const accountsSchema = z.record(z.unknown())
+const defaultPreferences = preferencesSchema.parse({})
+
+export const useExplorerPreferences = () => {
+ const { profile } = useProfile()
+ const accountId = IS_PLATFORM && profile ? profile.id.toString() : 'self-hosted'
+ const [stored, setStored, { isSuccess, isError }] = useLocalStorageQuery<unknown>(
+ LOCAL_STORAGE_KEYS.EXPLORER_PREFERENCES,
+ {}
+ )
+ const accounts = accountsSchema.safeParse(stored).data ?? {}
+ const preferences = preferencesSchema.safeParse(accounts[accountId]).data ?? defaultPreferences
+ const isReady = (!IS_PLATFORM || !!profile) && (isSuccess || isError)
+
+ const updatePreferences = (updates: Partial<z.infer<typeof preferencesSchema>>) => {
+ if (!isReady) return
+ setStored((current: unknown) => {
+ const accounts = accountsSchema.safeParse(current).data ?? {}
+ const previous = preferencesSchema.safeParse(accounts[accountId]).data ?? defaultPreferences
+ return { ...accounts, [accountId]: { ...previous, ...updates } }
+ })
+ }
+
+ return {
+ ...preferences,
+ isReady,
+ setHome: (home: ExplorerHome) => updatePreferences({ home }),
+ completeOnboarding: () => updatePreferences({ hasCompletedOnboarding: true }),
+ }
+}
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx
index 3e811df3720..4accbab5a83 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx
@@ -1,16 +1,55 @@
-import { NotebookText, SquareCode } from 'lucide-react'
-import { useState } from 'react'
+import { useParams } from 'common'
+import { Loader2, NotebookText, SquareCode } from 'lucide-react'
+import { useEffect, useEffectEvent, useRef, useState } from 'react'
import { cn } from 'ui'
import { isSqlStatement } from './ExplorerHomeTab.utils'
+import { ExplorerOnboarding } from './ExplorerOnboarding'
import { useCreateChat, useCreateNotebook, useCreateQuery } from './hooks'
import { NOTEBOOK_TEMPLATES } from './templates'
+import { useExplorerPreferences } from '@/components/interfaces/Account/Preferences/useExplorerPreferences'
import { ActionCard } from '@/components/layouts/Tabs/ActionCard'
import { CHAT_TEMPLATES } from '@/components/ui/AIAssistantPanel/AIAssistant.prompts'
import { AssistantAgentHarnessFooter } from '@/components/ui/AIAssistantPanel/AssistantAgentHarnessFooter'
import { AssistantChatForm } from '@/components/ui/AIAssistantPanel/AssistantChatForm'
export const ExplorerHomeTab = () => {
+ const { home, hasCompletedOnboarding, isReady } = useExplorerPreferences()
+
+ if (!isReady) return <ExplorerHomeLoading />
+ if (!hasCompletedOnboarding) return <ExplorerOnboarding />
+ if (home === 'query') return <ExplorerHomeQuery />
+
+ return <ExplorerHomeContent />
+}
+
+const ExplorerHomeLoading = () => (
+ <div
+ role="status"
+ aria-label="Opening Explorer"
+ className="flex h-full items-center justify-center bg-surface-100"
+ >
+ <Loader2 size={18} className="animate-spin motion-reduce:animate-none text-foreground-muted" />
+ </div>
+)
+
+const ExplorerHomeQuery = () => {
+ const { ref } = useParams()
+ const { createQuery, projectRef } = useCreateQuery()
+ const openedProjectRef = useRef<string | undefined>(undefined)
+
+ const openQuery = useEffectEvent(() => {
+ if (!ref || ref !== projectRef || openedProjectRef.current === ref) return
+ openedProjectRef.current = ref
+ createQuery({ replace: true })
+ })
+
+ useEffect(() => openQuery(), [ref, projectRef])
+
+ return <ExplorerHomeLoading />
+}
+
+const ExplorerHomeContent = () => {
const { createNotebook } = useCreateNotebook()
const { createQuery } = useCreateQuery()
const { createChat } = useCreateChat()
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerOnboarding.tsx b/apps/studio/components/interfaces/Explorer/ExplorerOnboarding.tsx
new file mode 100644
index 00000000000..ed370257255
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/ExplorerOnboarding.tsx
@@ -0,0 +1,34 @@
+import { Button } from 'ui'
+
+import { ExplorerOnboardingLearnMore } from './ExplorerOnboardingLearnMore'
+import { ExplorerHomePreference } from '@/components/interfaces/Account/Preferences/ExplorerHomePreference'
+import { useExplorerPreferences } from '@/components/interfaces/Account/Preferences/useExplorerPreferences'
+
+export const ExplorerOnboarding = () => {
+ const { home, setHome, completeOnboarding, isReady } = useExplorerPreferences()
+
+ return (
+ <div className="flex h-full min-h-0 flex-col items-center overflow-y-auto bg-surface-100 px-6">
+ <div className="my-auto w-full max-w-xl shrink-0 space-y-8 py-12">
+ <div className="space-y-3">
+ <h1 className="heading-section">Welcome to Explorer</h1>
+ <p className="text-sm leading-relaxed text-foreground-light">
+ Interact with your database and logs in one place. Run SQL, chat with Assistant, or
+ combine queries and notes in notebooks.
+ </p>
+ </div>
+
+ <div className="space-y-3">
+ <h2 className="text-sm font-medium">Choose how Explorer opens</h2>
+ <ExplorerHomePreference value={home} onValueChange={setHome} disabled={!isReady} />
+ </div>
+
+ <ExplorerOnboardingLearnMore />
+
+ <Button variant="primary" onClick={completeOnboarding} disabled={!isReady}>
+ Open Explorer
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerOnboardingLearnMore.tsx b/apps/studio/components/interfaces/Explorer/ExplorerOnboardingLearnMore.tsx
new file mode 100644
index 00000000000..dd1b616b616
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/ExplorerOnboardingLearnMore.tsx
@@ -0,0 +1,40 @@
+import { Card, CardContent } from 'ui'
+import { CollapsibleCardSection } from 'ui-patterns/CollapsibleCardSection'
+
+export const ExplorerOnboardingLearnMore = () => (
+ <Card>
+ <CardContent>
+ <CollapsibleCardSection title="Learn more">
+ <dl className="space-y-5 pt-2 text-sm">
+ <div className="space-y-1">
+ <dt className="font-medium">Where did my snippets go?</dt>
+ <dd className="leading-relaxed text-foreground-light">
+ Notebooks are intended to replace snippets over time. Your saved snippets are still
+ accessible by switching back to the SQL Editor.
+ </dd>
+ </div>
+ <div className="space-y-1">
+ <dt className="font-medium">Do notebooks replace custom reports?</dt>
+ <dd className="leading-relaxed text-foreground-light">
+ Notebooks are intended to replace custom reports over time. Your custom reports are
+ still accessible under Observability.
+ </dd>
+ </div>
+ <div className="space-y-1">
+ <dt className="font-medium">Who can see my notebooks?</dt>
+ <dd className="leading-relaxed text-foreground-light">
+ Notebooks are shared with everyone on your team by default.
+ </dd>
+ </div>
+ <div className="space-y-1">
+ <dt className="font-medium">Can AI see my data?</dt>
+ <dd className="leading-relaxed text-foreground-light">
+ Your organization’s AI settings control whether Assistant can access schema, logs, and
+ query results.
+ </dd>
+ </div>
+ </dl>
+ </CollapsibleCardSection>
+ </CardContent>
+ </Card>
+)
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerHomeTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerHomeTab.test.tsx
new file mode 100644
index 00000000000..5bf942fbdb1
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerHomeTab.test.tsx
@@ -0,0 +1,130 @@
+import { QueryClient } from '@tanstack/react-query'
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { LOCAL_STORAGE_KEYS } from 'common'
+import { StrictMode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ExplorerHomeTab } from '../ExplorerHomeTab'
+import { customRender } from '@/tests/lib/custom-render'
+import { createMockProfileContext } from '@/tests/lib/profile-helpers'
+
+const { createQuery, project } = vi.hoisted(() => ({
+ createQuery: vi.fn(),
+ project: { ref: 'default' as string | undefined },
+}))
+
+vi.mock('common', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('common')>()),
+ IS_PLATFORM: true,
+ useParams: () => ({ ref: 'default' }),
+}))
+
+vi.mock('../hooks', () => ({
+ useCreateQuery: () => ({ createQuery, projectRef: project.ref }),
+ useCreateNotebook: () => ({ createNotebook: vi.fn() }),
+ useCreateChat: () => ({ createChat: vi.fn() }),
+}))
+vi.mock('@/components/ui/AIAssistantPanel/AssistantChatForm', () => ({
+ AssistantChatForm: () => <div aria-label="Start page chat" />,
+}))
+vi.mock('@/components/ui/AIAssistantPanel/AssistantAgentHarnessFooter', () => ({
+ AssistantAgentHarnessFooter: () => null,
+}))
+
+const storageKey = LOCAL_STORAGE_KEYS.EXPLORER_PREFERENCES
+const seedPreferences = (home: 'home' | 'query', hasCompletedOnboarding = true) => {
+ localStorage.setItem(storageKey, JSON.stringify({ '1': { home, hasCompletedOnboarding } }))
+}
+const renderHome = () =>
+ customRender(
+ <StrictMode>
+ <ExplorerHomeTab />
+ </StrictMode>,
+ {
+ queryClient: new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ profileContext: createMockProfileContext(),
+ }
+ )
+
+beforeEach(() => {
+ createQuery.mockClear()
+ project.ref = 'default'
+})
+afterEach(() => localStorage.clear())
+
+describe('Explorer home onboarding', () => {
+ it('lets the user complete onboarding with the start page and does not show it on return', async () => {
+ const user = userEvent.setup()
+ const first = renderHome()
+ expect(await screen.findByRole('heading', { name: 'Welcome to Explorer' })).toBeVisible()
+ expect(screen.getByRole('radio', { name: /^Start page/ })).toBeChecked()
+ await user.click(screen.getByRole('button', { name: 'Open Explorer' }))
+ expect(await screen.findByLabelText('Start page chat')).toBeInTheDocument()
+ first.unmount()
+
+ renderHome()
+ expect(await screen.findByLabelText('Start page chat')).toBeInTheDocument()
+ expect(screen.queryByRole('heading', { name: 'Welcome to Explorer' })).not.toBeInTheDocument()
+ expect(createQuery).not.toHaveBeenCalled()
+ })
+
+ it('supports keyboard selection and waits for completion before opening a query', async () => {
+ const user = userEvent.setup()
+ renderHome()
+ const startPage = await screen.findByRole('radio', { name: /^Start page/ })
+ await user.click(startPage)
+ // Radix defers moving focus; keep the key down until that focus event selects the radio.
+ await user.keyboard('{ArrowRight>}')
+ await waitFor(() => expect(screen.getByRole('radio', { name: /^SQL query/ })).toBeChecked())
+ await user.keyboard('{/ArrowRight}')
+ expect(createQuery).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'Open Explorer' }))
+ await waitFor(() => expect(createQuery).toHaveBeenCalledExactlyOnceWith({ replace: true }))
+ })
+
+ it('shows onboarding for an unfinished query preference', async () => {
+ seedPreferences('query', false)
+ renderHome()
+ expect(await screen.findByRole('heading', { name: 'Welcome to Explorer' })).toBeVisible()
+ expect(screen.getByRole('radio', { name: /^SQL query/ })).toBeChecked()
+ expect(createQuery).not.toHaveBeenCalled()
+ })
+
+ it('opens one query for a returning user, even under Strict Mode', async () => {
+ seedPreferences('query')
+ renderHome()
+ await waitFor(() => expect(createQuery).toHaveBeenCalledExactlyOnceWith({ replace: true }))
+ expect(screen.queryByRole('heading', { name: 'Welcome to Explorer' })).not.toBeInTheDocument()
+ })
+
+ it.each([undefined, 'previous-project'])(
+ 'waits for the current project when the selected project is %s',
+ async (selectedRef) => {
+ seedPreferences('query')
+ project.ref = selectedRef
+ const { rerender } = renderHome()
+ await screen.findByRole('status', { name: 'Opening Explorer' })
+ expect(createQuery).not.toHaveBeenCalled()
+ project.ref = 'default'
+ rerender(
+ <StrictMode>
+ <ExplorerHomeTab />
+ </StrictMode>
+ )
+ await waitFor(() => expect(createQuery).toHaveBeenCalledExactlyOnceWith({ replace: true }))
+ }
+ )
+
+ it('keeps Learn more collapsed initially and supports expanding and collapsing with the keyboard', async () => {
+ const user = userEvent.setup()
+ renderHome()
+ const trigger = await screen.findByRole('button', { name: 'Learn more' })
+ expect(trigger).toHaveAttribute('aria-expanded', 'false')
+ expect(screen.queryByText('Where did my snippets go?')).not.toBeInTheDocument()
+ await user.click(trigger)
+ expect(screen.getByText('Where did my snippets go?')).toBeVisible()
+ await user.keyboard('{Enter}')
+ expect(trigger).toHaveAttribute('aria-expanded', 'false')
+ })
+})
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx
index 1d4f5662b1d..b487ee5903c 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx
@@ -7,6 +7,7 @@ const {
mockCreateChat,
mockCreateDraft,
mockPush,
+ mockReplace,
mockSelectChat,
mockSetContext,
mockWhenInitialized,
@@ -14,12 +15,15 @@ const {
mockCreateChat: vi.fn(() => 'chat-2'),
mockCreateDraft: vi.fn(),
mockPush: vi.fn(),
+ mockReplace: vi.fn(),
mockSelectChat: vi.fn(),
mockSetContext: vi.fn(),
mockWhenInitialized: vi.fn(() => Promise.resolve()),
}))
-vi.mock('next/router', () => ({ useRouter: () => ({ push: mockPush }) }))
+vi.mock('next/router', () => ({
+ useRouter: () => ({ push: mockPush, replace: mockReplace }),
+}))
vi.mock('@/hooks/misc/useSelectedProject', () => ({
useSelectedProjectQuery: () => ({
data: { ref: 'default', connectionString: 'postgres://example' },
@@ -43,6 +47,8 @@ vi.mock('@/state/ai-assistant-state', () => ({
whenAiAssistantInitialized: () => mockWhenInitialized(),
}))
+beforeEach(() => vi.clearAllMocks())
+
describe('useCreateChat', () => {
beforeEach(() => {
mockWhenInitialized.mockImplementation(() => Promise.resolve())
@@ -111,6 +117,21 @@ describe('useCreateChat', () => {
})
describe('useCreateQuery', () => {
+ it('replaces the start route when opening the preferred query on startup', () => {
+ const { result } = renderHook(() => useCreateQuery())
+
+ expect(result.current.createQuery({ replace: true })).toBe('query-new')
+ expect(mockCreateDraft).toHaveBeenCalledExactlyOnceWith({
+ id: 'query-new',
+ projectRef: 'default',
+ sql: undefined,
+ name: undefined,
+ autoRun: undefined,
+ })
+ expect(mockReplace).toHaveBeenCalledWith('/project/default/explorer/query/query-new')
+ expect(mockPush).not.toHaveBeenCalled()
+ })
+
it('creates a draft and opens it as an Explorer query tab', () => {
const { result } = renderHook(() => useCreateQuery())
diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.ts
index dd3c2d59fcb..3b3a7bb4761 100644
--- a/apps/studio/components/interfaces/Explorer/hooks.ts
+++ b/apps/studio/components/interfaces/Explorer/hooks.ts
@@ -191,16 +191,19 @@ export const useCreateQuery = () => {
sql,
name,
autoRun,
- }: { sql?: string; name?: string; autoRun?: boolean } = {}) => {
+ replace = false,
+ }: { sql?: string; name?: string; autoRun?: boolean; replace?: boolean } = {}) => {
if (!project) return console.error('Project is required')
const id = generateUuid()
querySnap.createDraft({ id, projectRef: project.ref, sql, name, autoRun })
- router.push(`/project/${project.ref}/explorer/query/${id}`)
+ const url = `/project/${project.ref}/explorer/query/${id}`
+ if (replace) router.replace(url)
+ else router.push(url)
return id
}
- return { createQuery }
+ return { createQuery, projectRef: project?.ref }
}
diff --git a/apps/studio/components/layouts/ExplorerLayout/ExplorerLayout.tsx b/apps/studio/components/layouts/ExplorerLayout/ExplorerLayout.tsx
index 4a77c9e9d5c..da87c153c7f 100644
--- a/apps/studio/components/layouts/ExplorerLayout/ExplorerLayout.tsx
+++ b/apps/studio/components/layouts/ExplorerLayout/ExplorerLayout.tsx
@@ -20,6 +20,7 @@ import { ExplorerNavChats } from './ExplorerNavChats'
import { ExplorerNavHeader } from './ExplorerNavHeader'
import { ExplorerNavHome } from './ExplorerNavHome'
import { ExplorerNavNotebooks } from './ExplorerNavNotebooks'
+import { useExplorerPreferences } from '@/components/interfaces/Account/Preferences/useExplorerPreferences'
import { ExplorerNotebookTabCoordinator } from '@/components/interfaces/Explorer/ExplorerNotebookTabCoordinator'
import { ExplorerQueryTabCoordinator } from '@/components/interfaces/Explorer/ExplorerQueryTabCoordinator'
import {
@@ -45,6 +46,8 @@ export interface ExplorerLayoutProps extends ComponentProps<typeof ProjectLayout
export const ExplorerLayout = ({ browserTitle, children, title }: ExplorerLayoutProps) => {
const { ref } = useParams()
const tabs = useTabsStateSnapshot()
+ const { home, hasCompletedOnboarding, isReady } = useExplorerPreferences()
+ const shouldShowHomeTab = isReady && (!hasCompletedOnboarding || home === 'home')
const [section, setSection] = useState<ExplorerResourceType>()
@@ -94,7 +97,7 @@ export const ExplorerLayout = ({ browserTitle, children, title }: ExplorerLayout
<div className={cn('h-10 md:min-h-(--header-height) flex items-center bg-surface-100')}>
<EditorTabs
isCollapseButtonHidden
- customTabs={<HomeTabButton />}
+ customTabs={shouldShowHomeTab ? <HomeTabButton /> : undefined}
newTabButton={<NewTabButton />}
/>
</div>
diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.ts
index d713fbe3026..134a80bb7f9 100644
--- a/packages/common/constants/local-storage.ts
+++ b/packages/common/constants/local-storage.ts
@@ -7,6 +7,7 @@ export const LOCAL_STORAGE_KEYS = {
AI_ASSISTANT_STATE: (projectRef: string | undefined) =>
`supabase-ai-assistant-state-${projectRef}`,
SIDEBAR_BEHAVIOR: 'supabase-sidebar-behavior',
+ EXPLORER_PREFERENCES: 'supabase-explorer-preferences',
PROJECTS_VIEW: 'projects-view',
PROJECTS_FILTER: 'projects-filter',
PROJECTS_SORT: 'projects-sort',
@@ -180,6 +181,7 @@ const LOCAL_STORAGE_KEYS_ALLOWLIST = [
LOCAL_STORAGE_KEYS.AI_ASSISTANT_MCP_OPT_IN,
LOCAL_STORAGE_KEYS.LINTER_SHOW_FOOTER,
LOCAL_STORAGE_KEYS.SIDEBAR_BEHAVIOR,
+ LOCAL_STORAGE_KEYS.EXPLORER_PREFERENCES,
LOCAL_STORAGE_KEYS.UI_TIMEZONE,
LOCAL_STORAGE_KEYS.UI_THEME_OVERRIDES,
]