Skip to content

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

feat(studio): show recent notebooks on the project homepage (#50825)

Saxon Fletcherd3f3903b69a8
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index 576f44c1866..e5cfe360dd5 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -61,7 +61,7 @@ import {
ExplorerToolbarIcon,
ExplorerToolbarTitle,
} from './ExplorerToolbar'
-import { useCreateChat, useLoadNotebook } from './hooks'
+import { useAnalyzeNotebook, useLoadNotebook } from './hooks'
import { MarkdownCell } from './MarkdownCell'
import { QueryCell } from './QueryCell'
import { type QueryEditorHandle } from './QueryEditor'
@@ -97,7 +97,7 @@ export const ExplorerNotebookTab = () => {
const tabs = useTabsStateSnapshot()
const snap = useNotebooksStateSnapshot()
const queryClient = useQueryClient()
- const { createChat, isCreating } = useCreateChat()
+ const { analyzeNotebook, isCreating } = useAnalyzeNotebook()
const { onSelectDelete } = useExplorerDeleteItem()
const [isIntellisenseEnabled, setIsIntellisenseEnabled] = useLocalStorageQuery(
@@ -296,12 +296,7 @@ export const ExplorerNotebookTab = () => {
}
}
- const handleAnalyze = () => {
- createChat({
- name: `Analyze ${name} notebook`,
- initialMessage: `Run the notebook "${name}" (id: ${id}) and analyze the results. Summarize the key findings per cell, calling out anomalies or trends, and use any markdown cells for context. Skip or flag any cell that would mutate data rather than running it.`,
- })
- }
+ const handleAnalyze = () => analyzeNotebook({ id, name })
const handleClickAnalyze = () => {
if (hasDiscardableChanges(currentNotebook)) {
diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.ts
index ebceaa7b0c8..279b026b62f 100644
--- a/apps/studio/components/interfaces/Explorer/hooks.ts
+++ b/apps/studio/components/interfaces/Explorer/hooks.ts
@@ -182,6 +182,19 @@ export const useCreateChat = () => {
return { createChat, openChat, isCreating }
}
+/** Opens a new Explorer chat that asks the assistant to run a saved notebook and summarize its results */
+export const useAnalyzeNotebook = () => {
+ const { createChat, isCreating } = useCreateChat()
+
+ const analyzeNotebook = ({ id, name }: { id?: string; name?: string }) =>
+ createChat({
+ name: `Analyze ${name} notebook`,
+ initialMessage: `Run the notebook "${name}" (id: ${id}) and analyze the results. Summarize the key findings per cell, calling out anomalies or trends, and use any markdown cells for context. Skip or flag any cell that would mutate data rather than running it.`,
+ })
+
+ return { analyzeNotebook, isCreating }
+}
+
export const useCreateQuery = () => {
const router = useRouter()
const { data: project } = useSelectedProjectQuery()
diff --git a/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx b/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx
index e1539c9bd02..ab0cc097140 100644
--- a/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx
+++ b/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx
@@ -1,11 +1,21 @@
import { useFlag, useParams } from 'common'
import { Shield } from 'lucide-react'
import { useCallback, useMemo } from 'react'
-import { AiIconAnimation, Badge, Button, Card, CardContent, CardHeader, CardTitle, cn } from 'ui'
+import {
+ AiIconAnimation,
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
import { Row } from 'ui-patterns/Row'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { Markdown } from '../Markdown'
+import { HomeCard } from './HomeCard'
import { LINTER_LEVELS } from '@/components/interfaces/Linter/Linter.constants'
import { createLintSummaryPrompt } from '@/components/interfaces/Linter/Linter.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
@@ -21,7 +31,8 @@ import {
sortAdvisorItems,
} from '@/components/ui/AdvisorPanel/AdvisorPanel.utils'
import { useAdvisorSignals } from '@/components/ui/AdvisorPanel/useAdvisorSignals'
-import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
+import CopyButton from '@/components/ui/CopyButton'
import { useProjectHealthLintsQuery } from '@/data/lint/health-lints-query'
import { useProjectLintsQuery } from '@/data/lint/lint-query'
import { useTrack } from '@/lib/telemetry/track'
@@ -157,42 +168,36 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: bo
: ''
return (
- <Card
+ <HomeCard
key={`${item.source}-${item.id}`}
- className={cn(
- 'min-h-full flex flex-col items-stretch cursor-pointer h-64',
- cardClasses
- )}
- onClick={() => {
- handleCardClick(item)
- }}
- >
- <CardHeader className="border-b-0 shrink-0 flex flex-row gap-2 space-y-0 justify-between items-center">
- <div className="flex flex-row items-center gap-3">
- <CategoryIcon
- size={16}
- strokeWidth={1.5}
- className={severityColorClasses[item.severity]}
- />
- <CardTitle className="text-foreground-light">{categoryLabel}</CardTitle>
- </div>
- <div className="flex items-center gap-2">
+ className={cardClasses}
+ onClick={() => handleCardClick(item)}
+ icon={
+ <CategoryIcon
+ size={16}
+ strokeWidth={1.5}
+ className={severityColorClasses[item.severity]}
+ />
+ }
+ label={categoryLabel}
+ title={title}
+ description={
+ description && <Markdown>{description.replace(/\\`/g, '`')}</Markdown>
+ }
+ actions={
+ <>
<Badge variant={severityBadgeVariants[item.severity]} className="w-fit">
{item.severity.toUpperCase()}
</Badge>
{isLint && (
- <div
- onClick={(e) => {
- e.stopPropagation()
- e.preventDefault()
- }}
- >
- <AiAssistantDropdown
- label="Ask Assistant"
- iconOnly
- tooltip="Help me fix this issue"
- buildPrompt={() => createLintSummaryPrompt(item.original)}
- onOpenAssistant={() => {
+ <>
+ <ButtonTooltip
+ variant="text"
+ className="w-7 h-7 px-1.5"
+ icon={<AiIconAnimation size={16} />}
+ aria-label="Ask Assistant"
+ tooltip={{ content: { text: 'Ask Assistant to fix this issue' } }}
+ onClick={() => {
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
snap.newChat({
name: 'Summarise lint',
@@ -205,21 +210,27 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: bo
advisorLevel: item.original.level,
})
}}
- telemetrySource="advisor_section"
- variant="text"
- className="w-7 h-7"
/>
- </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <CopyButton
+ iconOnly
+ variant="text"
+ className="w-7 h-7"
+ aria-label="Copy prompt"
+ asyncText={() => createLintSummaryPrompt(item.original)}
+ onClick={() =>
+ track('ai_prompt_copied', { source: 'advisor_section' })
+ }
+ />
+ </TooltipTrigger>
+ <TooltipContent>Copy prompt</TooltipContent>
+ </Tooltip>
+ </>
)}
- </div>
- </CardHeader>
- <CardContent className="p-6 pt-16 flex flex-col justify-end flex-1 overflow-auto">
- <h3 className="mb-1">{title}</h3>
- <Markdown className="leading-6 text-sm text-foreground-light">
- {description && description.replace(/\\`/g, '`')}
- </Markdown>
- </CardContent>
- </Card>
+ </>
+ }
+ />
)
})}
</Row>
diff --git a/apps/studio/components/interfaces/ProjectHome/Home.tsx b/apps/studio/components/interfaces/ProjectHome/Home.tsx
index 2935c876955..679fb9eacbc 100644
--- a/apps/studio/components/interfaces/ProjectHome/Home.tsx
+++ b/apps/studio/components/interfaces/ProjectHome/Home.tsx
@@ -21,8 +21,10 @@ import { AdvisorSection } from './AdvisorSection'
import { ConnectSection } from './ConnectSection'
import { CustomReportSection } from './CustomReportSection'
import { DEFAULT_SECTION_ORDER, mergeSectionOrder } from './Home.utils'
+import { NotebooksSection } from './NotebooksSection'
import { ProjectUsageSection } from './ProjectUsageSection'
import { ProjectUsageSectionDeltas } from './ProjectUsageSectionDeltas'
+import { useIsExplorerEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { TopSection } from '@/components/interfaces/ProjectHome/TopSection'
import { ProjectNeedsSecuring } from '@/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring'
import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'
@@ -42,6 +44,7 @@ export const ProjectHome = () => {
const track = useTrack()
const showHomepageUsageDeltas = useFlag('newHomepageUsageDeltas')
+ const isExplorerEnabled = useIsExplorerEnabled()
const isMatureProject = dayjs(project?.inserted_at).isBefore(dayjs().subtract(10, 'day'))
@@ -151,13 +154,14 @@ export const ProjectHome = () => {
)
}
if (IS_PLATFORM && id === 'custom-report') {
+ // Notebooks take over the reports slot (and its saved position) under the Explorer preview
return (
<div
key={id}
className={cn(isComingUp && 'opacity-60 pointer-events-none')}
>
<SortableSection gripClassName={SORT_GRIP_CLASS} id={id}>
- <CustomReportSection />
+ {isExplorerEnabled ? <NotebooksSection /> : <CustomReportSection />}
</SortableSection>
</div>
)
diff --git a/apps/studio/components/interfaces/ProjectHome/HomeCard.tsx b/apps/studio/components/interfaces/ProjectHome/HomeCard.tsx
new file mode 100644
index 00000000000..b4fc24c19c4
--- /dev/null
+++ b/apps/studio/components/interfaces/ProjectHome/HomeCard.tsx
@@ -0,0 +1,63 @@
+import Link from 'next/link'
+import type { ReactNode } from 'react'
+import { Card, CardContent, CardHeader, CardTitle, cn } from 'ui'
+
+// Stretches the title's link/button over the whole card so the card is clickable without
+// nesting the header actions inside an interactive element
+const STRETCHED_TARGET_CLASS =
+ 'block w-full truncate text-left outline-hidden after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-1 focus-visible:after:ring-foreground-muted'
+
+type HomeCardTarget = { href: string; onClick?: never } | { onClick: () => void; href?: never }
+
+type HomeCardProps = HomeCardTarget & {
+ icon: ReactNode
+ label: string
+ title: string
+ /** Rendered on the right of the header, above the card's click target */
+ actions?: ReactNode
+ description?: ReactNode
+ meta?: ReactNode
+ className?: string
+}
+
+/** Fixed-height card used by the project homepage rows, with its content anchored to the bottom */
+export const HomeCard = ({
+ href,
+ onClick,
+ icon,
+ label,
+ title,
+ actions,
+ description,
+ meta,
+ className,
+}: HomeCardProps) => (
+ <Card className={cn('relative h-64 flex flex-col', className)}>
+ <CardHeader className="border-b-0 shrink-0 flex flex-row gap-2 space-y-0 justify-between items-center">
+ <div className="flex flex-row items-center gap-3">
+ {icon}
+ <CardTitle className="text-foreground-light">{label}</CardTitle>
+ </div>
+ {actions && <div className="relative z-10 flex items-center gap-1">{actions}</div>}
+ </CardHeader>
+ <CardContent className="pt-0 flex flex-col justify-end flex-1 min-h-0">
+ <h3 className="mb-1">
+ {href !== undefined ? (
+ <Link href={href} className={STRETCHED_TARGET_CLASS}>
+ {title}
+ </Link>
+ ) : (
+ <button type="button" tabIndex={0} onClick={onClick} className={STRETCHED_TARGET_CLASS}>
+ {title}
+ </button>
+ )}
+ </h3>
+ {description && (
+ <div className="text-sm text-muted-foreground line-clamp-3 [&_a]:relative [&_a]:z-10">
+ {description}
+ </div>
+ )}
+ {meta && <p className="mt-3 text-sm text-foreground-lighter">{meta}</p>}
+ </CardContent>
+ </Card>
+)
diff --git a/apps/studio/components/interfaces/ProjectHome/NotebooksSection.tsx b/apps/studio/components/interfaces/ProjectHome/NotebooksSection.tsx
new file mode 100644
index 00000000000..e176f993a9e
--- /dev/null
+++ b/apps/studio/components/interfaces/ProjectHome/NotebooksSection.tsx
@@ -0,0 +1,140 @@
+import { useParams } from 'common'
+import dayjs from 'dayjs'
+import { NotebookText, Plus } from 'lucide-react'
+import { AiIconAnimation, Badge, Button } from 'ui'
+import { Row } from 'ui-patterns/Row'
+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
+
+import { HomeCard } from './HomeCard'
+import { useAnalyzeNotebook, useCreateNotebook } from '@/components/interfaces/Explorer/hooks'
+import { AlertError } from '@/components/ui/AlertError'
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
+import {
+ useNotebooksInfiniteQuery,
+ type NotebookRow,
+} from '@/data/content/notebooks/notebooks-infinite-query'
+
+const MAX_HOMEPAGE_NOTEBOOKS = 4
+
+export const NotebooksSection = () => {
+ const { ref: projectRef } = useParams()
+ const { createNotebook } = useCreateNotebook()
+
+ const { data, error, isPending, isError, isSuccess, refetch } = useNotebooksInfiniteQuery({
+ projectRef,
+ limit: MAX_HOMEPAGE_NOTEBOOKS,
+ sort: 'inserted_at',
+ })
+ // The content endpoint can return more rows than `limit`, so cap the row here too
+ const notebooks = (data?.pages[0]?.content ?? []).slice(0, MAX_HOMEPAGE_NOTEBOOKS)
+
+ return (
+ <div>
+ {isPending && (
+ <>
+ <ShimmeringLoader className="w-96 mb-6" />
+ <div className="flex flex-col gap-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ </>
+ )}
+
+ {!isPending && (
+ <div className="flex justify-between items-center mb-6">
+ <h2>Notebooks</h2>
+ <Button icon={<Plus />} onClick={() => createNotebook()}>
+ New notebook
+ </Button>
+ </div>
+ )}
+
+ {isError && (
+ <AlertError
+ error={error instanceof Error ? error : null}
+ subject="Failed to retrieve notebooks"
+ projectRef={projectRef}
+ additionalActions={
+ <Button variant="default" onClick={() => refetch()}>
+ Retry
+ </Button>
+ }
+ />
+ )}
+
+ {isSuccess && notebooks.length === 0 && (
+ <EmptyState onCreateNotebook={() => createNotebook()} />
+ )}
+
+ {isSuccess && notebooks.length > 0 && (
+ <Row maxColumns={4} minWidth={280}>
+ {notebooks.map((notebook) => (
+ <NotebookCard key={notebook.id} notebook={notebook} projectRef={projectRef} />
+ ))}
+ </Row>
+ )}
+ </div>
+ )
+}
+
+function NotebookCard({
+ notebook,
+ projectRef,
+}: {
+ notebook: NotebookRow
+ projectRef: string | undefined
+}) {
+ const { analyzeNotebook, isCreating } = useAnalyzeNotebook()
+
+ const cellCount = notebook.content?.cells?.length
+ // Treat an unknown cell count as empty so Analyze is never offered on a notebook with no cells
+ const isEmpty = !cellCount
+
+ return (
+ <HomeCard
+ href={`/project/${projectRef}/explorer/notebook/${notebook.id}`}
+ icon={<NotebookText size={16} strokeWidth={1.5} className="text-foreground-light" />}
+ label="NOTEBOOK"
+ title={notebook.name}
+ description={notebook.description?.trim()}
+ meta={`Created ${dayjs(notebook.inserted_at).fromNow()}`}
+ actions={
+ <>
+ {cellCount !== undefined && (
+ <Badge className="w-fit">
+ {cellCount} {cellCount === 1 ? 'CELL' : 'CELLS'}
+ </Badge>
+ )}
+ <ButtonTooltip
+ variant="text"
+ className="w-7 h-7 px-1.5"
+ icon={<AiIconAnimation size={16} loading={isCreating} />}
+ disabled={isEmpty}
+ onClick={() => analyzeNotebook({ id: notebook.id, name: notebook.name })}
+ aria-label="Analyze"
+ tooltip={{
+ content: {
+ text: isEmpty ? 'Add a cell to the notebook to analyze it' : 'Analyze',
+ },
+ }}
+ />
+ </>
+ }
+ />
+ )
+}
+
+function EmptyState({ onCreateNotebook }: { onCreateNotebook: () => void }) {
+ return (
+ <div className="h-64 flex flex-col items-center justify-center rounded-sm border-2 border-dashed p-16">
+ <h4>Create a notebook</h4>
+ <p className="text-sm text-foreground-light mb-4">
+ Save queries and notes together to revisit and share
+ </p>
+ <Button iconRight={<Plus size={14} />} onClick={onCreateNotebook}>
+ Create your first notebook
+ </Button>
+ </div>
+ )
+}