Skip to content

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

feat(studio): refine notebook query cell layout (#49350)

Saxon Fletcherd93defe1e020
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
index 69b05ad8388..6d8c727b674 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
@@ -19,6 +19,7 @@ export const ExplorerQueryTab = () => {
const querySnap = useExplorerQueryStateSnapshot()
const [restoredQueryKey, setRestoredQueryKey] = useState<string>()
+ const [showQuery, setShowQuery] = useState(true)
const stateDraft = id ? querySnap.drafts[id] : undefined
const draft = stateDraft?.projectRef === ref ? stateDraft : undefined
@@ -38,6 +39,7 @@ export const ExplorerQueryTab = () => {
useEffect(() => {
if (!id || !ref) return
+ setShowQuery(true)
const restored = explorerQueryState.restoreDraft({ id, projectRef: ref })
const restoredDraft = explorerQueryState.drafts[id]
if (restored && restoredDraft) {
@@ -102,6 +104,8 @@ export const ExplorerQueryTab = () => {
title={draft.name}
query={query}
result={result}
+ showQuery={showQuery}
+ onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
const name = value.trim() || 'Untitled query'
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
index 5293f0f3ecc..8692f526bf2 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
@@ -40,6 +40,8 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function
const roleImpersonationState = useLocalRoleImpersonationState()
const title = cell.title ?? 'Untitled query'
+ const showQuery =
+ snap.cellLocalState.get(cell._id)?.showQuery ?? currentNotebook?.status === 'new'
/**
* Applies an update to this cell. The updater runs against the cell as the store holds
@@ -54,7 +56,10 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function
snap.updateCell({
id: notebookId,
cellId: cell._id,
- updater: (candidate) => (isQueryCell(candidate) ? updater(candidate) : candidate),
+ updater: (candidate) => {
+ if (!isQueryCell(candidate)) return candidate
+ return updater(candidate)
+ },
})
}
@@ -101,6 +106,8 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function
title={title}
query={toQueryModel(cell, sql)}
result={result}
+ showQuery={showQuery}
+ onShowQueryChange={(showQuery) => snap.setQueryVisibility({ cellId: cell._id, showQuery })}
roleImpersonationState={roleImpersonationState}
display={getCellDisplay(cell)}
onTitleChange={handleTitleChange}
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index 15fd6e59fc6..8285eb878f0 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -109,6 +109,8 @@ type QueryEditorProps = {
display?: QueryDisplay
toolbarActions?: ReactNode
className?: string
+ showQuery: boolean
+ onShowQueryChange: (showQuery: boolean) => void
/** When true, toolbar and editor run actions are disabled. */
isRunDisabled?: boolean
onTitleChange: (title: string) => void
@@ -137,6 +139,8 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
display,
toolbarActions,
className,
+ showQuery,
+ onShowQueryChange,
isRunDisabled = false,
onTitleChange,
onSqlChange,
@@ -162,7 +166,6 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const rowLimit = query._tag === 'database' ? query.rowLimit : undefined
const databaseIdentifier = query._tag === 'database' ? query.database_identifier : undefined
- const [showQuery, setShowQuery] = useState(true)
const [promptInput, setPromptInput] = useState('')
const [pendingProposal, setPendingProposal] = useState<PendingProposal | null>(null)
const pendingProposalRef = useLatest(pendingProposal)
@@ -307,7 +310,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
}, [promptState?.isOpen])
return (
- <Shell className={cn(variant === 'embedded' && 'mx-auto max-w-4xl', className)}>
+ <Shell className={cn(variant === 'embedded' && 'mx-auto max-w-6xl', className)}>
<ExplorerToolbar>
<ExplorerToolbarIcon>
<CodeSquare size={14} />
@@ -341,7 +344,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
icon={showQuery ? <EyeOff /> : <Eye />}
disabled={pendingProposal !== null}
tooltip={showQuery ? 'Hide query' : 'Show query'}
- onClick={() => setShowQuery((value) => !value)}
+ onClick={() => onShowQueryChange(!showQuery)}
/>
<ExplorerToolbarAction
loading={isExecuting}
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
index 389e07dcaf8..9b23ad6fce4 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
@@ -8,7 +8,7 @@ import { ExplorerNotebookTab } from '../ExplorerNotebookTab'
import { createMarkdownCellSkeleton, createQueryCellSkeleton } from '../utils'
import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
import { notebooksState } from '@/state/notebooks/notebooks-state'
-import type { Notebook, StateNotebook } from '@/state/notebooks/types'
+import type { Notebook } from '@/state/notebooks/types'
import { createTabsState, TabsStateContext } from '@/state/tabs'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
@@ -52,12 +52,9 @@ const logCell = {
}
const markdownCell = createMarkdownCellSkeleton()
-/**
- * Assigns directly into the store rather than going through `setNotebook` — that helper
- * no-ops when a notebook with content already exists, which would make reseeding between
- * tests (or within one, for the empty-notebook case) silently keep the previous cells.
- */
-const seedNotebook = (cells: Notebooks.Cell[]) => {
+/** Clears any prior fixture so seeding exercises the same store-loading path as the app. */
+const seedNotebook = (cells: Notebooks.Cell[], status: 'new' | 'saved' = 'saved') => {
+ delete notebooksState.notebooks[NOTEBOOK_ID]
const notebook: Notebook = {
id: NOTEBOOK_ID,
type: 'notebook',
@@ -68,8 +65,8 @@ const seedNotebook = (cells: Notebooks.Cell[]) => {
project_id: 1,
content: { schema_version: 1, cells },
}
- const stateNotebook: StateNotebook = { projectRef: 'default', notebook, status: 'saved' }
- notebooksState.notebooks[NOTEBOOK_ID] = stateNotebook
+ if (status === 'new') notebooksState.addNotebook({ projectRef: 'default', notebook })
+ else notebooksState.setNotebook({ projectRef: 'default', notebook })
}
const renderNotebookTab = () =>
@@ -90,10 +87,43 @@ beforeEach(() => {
afterEach(() => {
notebooksState.needsSaving.clear()
+ notebooksState.cellLocalState.clear()
safeLocalStorage.removeItem(LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE)
})
describe('ExplorerNotebookTab', () => {
+ it('hides SQL by default for saved notebooks and caps query cells at 6xl', () => {
+ renderNotebookTab()
+
+ const queryCells = Array.from(document.querySelectorAll('[data-slot="explorer-query"]'))
+ expect(queryCells).toHaveLength(2)
+ queryCells.forEach((cell) => expect(cell).toHaveClass('max-w-6xl'))
+
+ expect(screen.queryByRole('textbox', { name: 'SQL editor' })).not.toBeInTheDocument()
+ })
+
+ it('shows SQL by default for a new notebook', async () => {
+ seedNotebook([databaseCell, logCell, markdownCell], 'new')
+
+ renderNotebookTab()
+
+ expect(await screen.findAllByRole('textbox', { name: 'SQL editor' })).toHaveLength(2)
+ })
+
+ it('keeps query visibility when the notebook tab remounts', async () => {
+ const view = renderNotebookTab()
+
+ const showQueryButton = document.querySelector('.lucide-eye')?.closest('button')
+ expect(showQueryButton).toBeInstanceOf(HTMLButtonElement)
+ await userEvent.click(showQueryButton as HTMLButtonElement)
+ expect(await screen.findAllByRole('textbox', { name: 'SQL editor' })).toHaveLength(1)
+
+ view.unmount()
+ renderNotebookTab()
+
+ expect(await screen.findAllByRole('textbox', { name: 'SQL editor' })).toHaveLength(1)
+ })
+
it('runs every database and log cell, and skips markdown cells, on "Run notebook"', async () => {
// `useAddDefinitions` fires its own background keywords/functions/schemas/table-columns
// fetches against this same generic pg-meta query endpoint (differentiated by the `key`
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
index 10df1e3a58e..6036059820a 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
@@ -62,6 +62,7 @@ export const AssistantQueryCell = ({
const [title, setTitle] = useState(fallbackTitle)
const [query, setQuery] = useState(() => createAssistantQueryModel(initialSql, source))
+ const [showQuery, setShowQuery] = useState(true)
// undefined uses the tool output; null intentionally clears it after changing source.
const [resultOverride, setResultOverride] = useState<QueryResult | null>()
const [localDisplay, setLocalDisplay] = useState<QueryDisplay | undefined>(undefined)
@@ -71,6 +72,7 @@ export const AssistantQueryCell = ({
previousId.current = id
setTitle(fallbackTitle)
setQuery(createAssistantQueryModel(initialSql, source))
+ setShowQuery(true)
setResultOverride(undefined)
setLocalDisplay(undefined)
}
@@ -140,6 +142,8 @@ export const AssistantQueryCell = ({
title={title}
query={query}
result={result}
+ showQuery={showQuery}
+ onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
display={display}
isRunDisabled={isConfirming}
diff --git a/apps/studio/state/notebooks/notebooks-state.test.ts b/apps/studio/state/notebooks/notebooks-state.test.ts
index 7619736810f..388c12172fa 100644
--- a/apps/studio/state/notebooks/notebooks-state.test.ts
+++ b/apps/studio/state/notebooks/notebooks-state.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'
import { notebooksState } from './notebooks-state'
import type { Notebook } from './types'
+import type { Notebooks } from '@/types'
function makeNotebook(id: string, overrides: Partial<Notebook> = {}): Notebook {
return {
@@ -25,6 +26,7 @@ describe('notebooksState', () => {
delete notebooksState.notebooks[id]
}
notebooksState.needsSaving.clear()
+ notebooksState.cellLocalState.clear()
})
it('addNotebook marks a locally-created notebook as new', () => {
@@ -39,6 +41,30 @@ describe('notebooksState', () => {
expect(notebooksState.notebooks['notebook-1'].status).toBe('saved')
})
+ it('keeps query visibility in session state without marking the notebook as edited', () => {
+ const queryCell = {
+ _tag: 'database_cell' as const,
+ _id: 'cell-1',
+ unchecked_sql: '' as Notebooks.DatabaseCell['unchecked_sql'],
+ row_limit: 100,
+ view: 'table' as const,
+ }
+ notebooksState.setNotebook({
+ projectRef: 'ref',
+ notebook: makeNotebook('notebook-1', {
+ content: { schema_version: 1, cells: [queryCell] },
+ }),
+ })
+
+ expect(notebooksState.cellLocalState.has('cell-1')).toBe(false)
+
+ notebooksState.setQueryVisibility({ cellId: 'cell-1', showQuery: true })
+
+ expect(notebooksState.cellLocalState.get('cell-1')).toEqual({ showQuery: true })
+ expect(notebooksState.notebooks['notebook-1'].status).toBe('saved')
+ expect(notebooksState.needsSaving.has('notebook-1')).toBe(false)
+ })
+
it('editing a loaded (saved) notebook transitions it to unsaved and queues it for saving', () => {
notebooksState.setNotebook({ projectRef: 'ref', notebook: makeNotebook('notebook-1') })
diff --git a/apps/studio/state/notebooks/notebooks-state.ts b/apps/studio/state/notebooks/notebooks-state.ts
index 8591de569a4..48534a5ae4e 100644
--- a/apps/studio/state/notebooks/notebooks-state.ts
+++ b/apps/studio/state/notebooks/notebooks-state.ts
@@ -6,6 +6,7 @@ import { proxy, snapshot, useSnapshot, type Snapshot } from 'valtio'
import { proxyMap } from 'valtio/utils'
import type { Notebook, StateNotebook } from './types'
+import { isQueryCell } from '@/data/content/notebooks/notebook-schema'
import type { SnippetStatus } from '@/data/content/snippet-status'
import type { Notebooks } from '@/types'
@@ -13,9 +14,15 @@ function statusOnEdit(status: SnippetStatus): SnippetStatus {
return status === 'saved' ? 'unsaved' : status
}
+type NotebookCellLocalState = {
+ showQuery?: boolean
+}
+
export const notebooksState = proxy({
notebooks: {} as Record<string, StateNotebook>,
needsSaving: proxyMap<string, boolean>([]),
+ /** Session-only UI state keyed by cell ID; never persisted with notebook content. */
+ cellLocalState: proxyMap<string, NotebookCellLocalState>([]),
/**
* Load notebook into the Valtio store. No-ops if already present.
@@ -58,11 +65,13 @@ export const notebooksState = proxy({
/**
* Remove notebook from the store, and optionally remove it from the sync
- * saving queue. Also clears any cached query-cell results for this notebook
- * from the ephemeral session store.
+ * saving queue. Also clears its session-only query-cell UI state.
*/
removeNotebook: ({ id, skipSave = false }: { id: string; skipSave?: boolean }) => {
const { [id]: notebook, ...otherNotebooks } = notebooksState.notebooks
+ notebook?.notebook.content?.cells.forEach((cell) =>
+ notebooksState.cellLocalState.delete(cell._id)
+ )
notebooksState.notebooks = otherNotebooks
if (!skipSave) notebooksState.needsSaving.delete(id)
},
@@ -113,6 +122,7 @@ export const notebooksState = proxy({
const insertAt = cellId ? cells.findIndex((c) => c._id === cellId) : -1
const nextCells = [...cells]
nextCells.splice(insertAt === -1 ? cells.length : insertAt + 1, 0, cell)
+ if (isQueryCell(cell)) notebooksState.cellLocalState.set(cell._id, { showQuery: true })
notebooksState.updateCells({ id, cells: nextCells })
},
@@ -141,6 +151,12 @@ export const notebooksState = proxy({
notebooksState.updateCells({ id, cells: nextCells })
},
+ setQueryVisibility: ({ cellId, showQuery }: { cellId: string; showQuery: boolean }) =>
+ notebooksState.cellLocalState.set(cellId, {
+ ...notebooksState.cellLocalState.get(cellId),
+ showQuery,
+ }),
+
/**
* Remove a single cell from a notebook's cell array.
*/
@@ -149,6 +165,7 @@ export const notebooksState = proxy({
if (!stateNotebook?.notebook.content) return
const nextCells = stateNotebook.notebook.content.cells.filter((c) => c._id !== cellId)
+ notebooksState.cellLocalState.delete(cellId)
notebooksState.updateCells({ id, cells: nextCells })
},