Skip to content

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

Joshenlim/fe 4221 explorer tab behaviours to mimic sql editor (#49386)

Joshen Lim5c6ef8ae3d37
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerChatTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerChatTab.tsx
index e2b2ef248c6..21552016d2c 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerChatTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerChatTab.tsx
@@ -25,19 +25,9 @@ export const ExplorerChatTab = () => {
const tabId = id ? createTabId('chat', { id }) : undefined
const shortcutsEnabled = activeSidebar?.id !== SIDEBAR_KEYS.AI_ASSISTANT
- const syncChatTab = useEffectEvent(() => {
+ const ensureChatInstance = useEffectEvent(() => {
if (!id || !chat) return
-
aiAssistantState.ensureChatInstance(id)
- const nextTabId = createTabId('chat', { id })
- tabs.addTab({
- id: nextTabId,
- type: 'chat',
- label: chat.name,
- metadata: { chatId: id },
- isPreview: false,
- })
- tabs.updateTab(nextTabId, { label: chat.name })
})
const removeDeletedChatTab = useEffectEvent(() => {
@@ -51,7 +41,7 @@ export const ExplorerChatTab = () => {
})
})
- useEffect(() => syncChatTab(), [id, chat?.name])
+ useEffect(() => ensureChatInstance(), [id, chat])
useEffect(() => {
if (aiAssistant.isInitialized && id && !chat) removeDeletedChatTab()
@@ -95,6 +85,7 @@ export const ExplorerChatTab = () => {
onNewChat={() => createChat()}
onSelectChat={openChat}
onBranchChat={handleBranchChat}
+ onInputChange={() => tabs.makeTabPermanent(createTabId('chat', { id }))}
renderHeader={(headerProps) => (
<ExplorerChatToolbar {...headerProps} chatId={id} shortcutsEnabled={shortcutsEnabled} />
)}
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index 1a05d963027..086575bdfb7 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -98,10 +98,17 @@ export const ExplorerNotebookTab = () => {
>(null)
const [skipMutatingCells, setSkipMutatingCells] = useState(false)
const queryCellRefs = useRef(new Map<string, QueryEditorHandle>())
+ const savedContentRef = useRef<typeof content>(undefined)
const { mutate: updateNotebook, isPending: isUpdating } = useUpsertNotebookMutation({
- onSuccess: () => toast.success('Successfully saved notebook!'),
+ onSuccess: () => {
+ if (id && content === savedContentRef.current) {
+ snap.markSaved({ id })
+ toast.success('Successfully saved notebook!')
+ }
+ },
})
+
const { mutate: deleteNotebook, isPending: isDeleting } = useContentDeleteMutation({
onSuccess: () => {
toast.success('Successfully deleted notebook')
@@ -120,7 +127,15 @@ export const ExplorerNotebookTab = () => {
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
)
+ const persistNotebookTab = () => {
+ const notebookId = currentNotebook?.notebook.id
+ if (!notebookId) return
+
+ tabs.makeTabPermanent(createTabId('notebook', { id: notebookId }))
+ }
+
const handleSaveTitle = (titleValue: string) => {
+ persistNotebookTab()
const trimmedName = titleValue.trim()
if (id && trimmedName && trimmedName !== name) {
snap.renameNotebook({ id, name: trimmedName })
@@ -135,7 +150,9 @@ export const ExplorerNotebookTab = () => {
cellIdsToRun: string[]
force?: boolean
}) => {
+ persistNotebookTab()
setIsRunningNotebook(true)
+
try {
await Promise.allSettled(
cellIdsToRun.map((cellId) => queryCellRefs.current.get(cellId)?.run(force))
@@ -179,6 +196,8 @@ export const ExplorerNotebookTab = () => {
const notebookId = currentNotebook?.notebook.id
if (!ref || !notebookId || !name || !content) return
+ persistNotebookTab()
+
const writableContent: WritableNotebook = {
schema_version: content.schema_version,
cells: content.cells.map((cell): WritableCell => {
@@ -205,6 +224,11 @@ export const ExplorerNotebookTab = () => {
}),
}
+ // [Joshen] For tracking if a notebook is updated while being saved, so that we do not
+ // incorrectly show the saved toast if it's subsequently then saved once again while
+ // the initial save is midflight
+ savedContentRef.current = content
+
updateNotebook({
projectRef: ref,
id: notebookId,
@@ -220,6 +244,8 @@ export const ExplorerNotebookTab = () => {
}
const handleDragEnd = (event: DragEndEvent) => {
+ persistNotebookTab()
+
const { active, over } = event
if (!id || !over || active.id === over.id) return
@@ -227,6 +253,8 @@ export const ExplorerNotebookTab = () => {
}
const onSelectAddCell = (type: 'markdown' | 'query') => {
+ persistNotebookTab()
+
const notebookId = currentNotebook?.notebook.id
if (!notebookId) return
@@ -342,13 +370,14 @@ export const ExplorerNotebookTab = () => {
<QueryCell
key={cell._id}
cell={cell}
+ onEdit={persistNotebookTab}
ref={(instance) => {
if (instance) queryCellRefs.current.set(cell._id, instance)
else queryCellRefs.current.delete(cell._id)
}}
/>
) : (
- <MarkdownCell key={cell._id} cell={cell} />
+ <MarkdownCell key={cell._id} cell={cell} onEdit={persistNotebookTab} />
)
)}
</div>
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx
index 9e1c723c4ac..ee7337f0889 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx
@@ -3,17 +3,35 @@ import { useParams } from 'common'
import { useContext, useEffect } from 'react'
import { contentKeys } from '@/data/content/keys'
-import { notebooksState } from '@/state/notebooks/notebooks-state'
-import { TabsStateContext } from '@/state/tabs'
+import { notebooksState, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
+import { hasUnsavedChanges } from '@/state/sql-editor/sql-editor-lifecycle'
+import { TabsStateContext, type Tab } from '@/state/tabs'
+
+const NotebookTabStatusIndicator = ({ tab }: { tab: Tab }) => {
+ const notebooksSnap = useNotebooksStateSnapshot()
+ const notebookId = tab.metadata?.notebookId
+ const stateNotebook = notebookId ? notebooksSnap.notebooks[notebookId] : undefined
+ if (!hasUnsavedChanges(stateNotebook?.status)) return null
+
+ // A never-persisted notebook with no cells has nothing worth flagging as unsaved.
+ const isEmptyNewNotebook =
+ stateNotebook?.status === 'new' && (stateNotebook.notebook.content?.cells.length ?? 0) === 0
+ if (isEmptyNewNotebook) return null
+
+ return (
+ <span
+ role="img"
+ aria-label="Unsaved changes"
+ className="block size-2 shrink-0 rounded-full bg-warning"
+ />
+ )
+}
/**
* Evicts a notebook's content from the valtio store and the React Query cache
* when its tab closes, so reopening it always refetches instead of showing
- * whatever was last loaded. Only applies to notebooks with no unsaved edits —
- * a dirty notebook is left in the store untouched, same as today, since there's
- * no autosave or discard-confirmation flow for notebooks yet.
- *
- * [Joshen] We'll address discard confirmation separately
+ * whatever was last loaded. Unsaved edits are discarded the same way — safe
+ * because `confirmClose` below has already asked the user to confirm.
*/
export const ExplorerNotebookTabCoordinator = () => {
const { ref } = useParams()
@@ -26,12 +44,39 @@ export const ExplorerNotebookTabCoordinator = () => {
const notebookId = tab.metadata?.notebookId
if (!ref || !notebookId) return
- const stateNotebook = notebooksState.notebooks[notebookId]
- if (stateNotebook?.status !== 'saved') return
+ if (notebooksState.notebooks[notebookId]) {
+ notebooksState.removeNotebook({ id: notebookId })
+ }
notebooksState.removeNotebook({ id: notebookId })
queryClient.removeQueries({ queryKey: contentKeys.resource(ref, notebookId) })
},
+ confirmClose: (notebookTabs) => {
+ const dirtyCount = notebookTabs.filter((tab) => {
+ const notebookId = tab.metadata?.notebookId
+ if (!notebookId) return false
+
+ const stateNotebook = notebooksState.notebooks[notebookId]
+ if (!hasUnsavedChanges(stateNotebook?.status)) return false
+
+ // A never-persisted notebook with no cells has nothing worth confirming before discarding.
+ const isEmptyNewNotebook =
+ stateNotebook?.status === 'new' &&
+ (stateNotebook.notebook.content?.cells.length ?? 0) === 0
+ return !isEmptyNewNotebook
+ }).length
+
+ if (dirtyCount === 0) return null
+
+ return {
+ title: 'Unsaved changes',
+ description:
+ dirtyCount === 1
+ ? 'You have unsaved changes in this notebook. Closing it will discard them.'
+ : `You have unsaved changes in ${dirtyCount} notebooks. Closing them will discard those changes.`,
+ }
+ },
+ StatusIndicator: NotebookTabStatusIndicator,
})
}, [ref, tabs, queryClient])
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
index 6d8c727b674..75e54ee251a 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
@@ -40,19 +40,9 @@ export const ExplorerQueryTab = () => {
if (!id || !ref) return
setShowQuery(true)
- const restored = explorerQueryState.restoreDraft({ id, projectRef: ref })
- const restoredDraft = explorerQueryState.drafts[id]
- if (restored && restoredDraft) {
- tabs.addTab({
- id: createTabId('query', { id }),
- type: 'query',
- label: restoredDraft.name,
- metadata: { queryId: id },
- isPreview: false,
- })
- }
+ explorerQueryState.restoreDraft({ id, projectRef: ref })
setRestoredQueryKey(`${ref}:${id}`)
- }, [id, ref, tabs])
+ }, [id, ref])
if (!queryKey || restoredQueryKey !== queryKey) {
return (
@@ -88,6 +78,8 @@ export const ExplorerQueryTab = () => {
})
}
+ const persistTab = () => tabs.makeTabPermanent(createTabId('query', { id }))
+
const query: ExplorerQueryModel =
draft._tag === 'logs'
? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }
@@ -108,14 +100,24 @@ export const ExplorerQueryTab = () => {
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
+ persistTab()
const name = value.trim() || 'Untitled query'
explorerQueryState.updateDraft({ id, name })
tabs.updateTab(createTabId('query', { id }), { label: name })
}}
- onSqlChange={(sql) => explorerQueryState.updateDraft({ id, sql })}
- onSourceChange={(source) => explorerQueryState.updateDraft({ id, source })}
+ onSqlChange={(sql) => {
+ persistTab()
+ explorerQueryState.updateDraft({ id, sql })
+ }}
+ onSourceChange={(source) => {
+ persistTab()
+ explorerQueryState.updateDraft({ id, source })
+ }}
+ onRowLimitChange={(rowLimit) => {
+ persistTab()
+ explorerQueryState.updateDraft({ id, rowLimit })
+ }}
onResultChange={handleResultChange}
- onRowLimitChange={(rowLimit) => explorerQueryState.updateDraft({ id, rowLimit })}
/>
)
}
diff --git a/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx b/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx
index df8dc8860f8..c2629d153bf 100644
--- a/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx
+++ b/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx
@@ -14,11 +14,12 @@ import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks
interface MarkdownCellProps {
cell: MarkdownCellSchema
+ onEdit?: () => void
}
// [Joshen] handleUpdateMarkdown could be shifted into notebook-state as a updateCell action
-export const MarkdownCell = ({ cell }: MarkdownCellProps) => {
+export const MarkdownCell = ({ cell, onEdit }: MarkdownCellProps) => {
const snap = useNotebooksStateSnapshot()
const currentNotebook = useCurrentNotebook()
const cells = currentNotebook?.notebook.content?.cells ?? []
@@ -41,6 +42,7 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {
const notebookId = currentNotebook?.notebook.id
if (!notebookId) return
+ onEdit?.()
const nextCells = cells.map((c) => (c._id === cellId ? { ...c, text } : c))
snap.updateCells({ id: notebookId, cells: nextCells })
setIsEditing(false)
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
index 8692f526bf2..ae7a7159344 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
@@ -25,11 +25,12 @@ import { useLocalRoleImpersonationState } from '@/state/role-impersonation-state
interface QueryCellProps {
cell: Snapshot<QueryCellSchema>
+ onEdit?: () => void
}
/** Notebook adapter around the shared QueryEditor. */
export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function QueryCell(
- { cell },
+ { cell, onEdit },
ref
) {
const snap = useNotebooksStateSnapshot()
@@ -53,6 +54,7 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function
const notebookId = currentNotebook?.notebook.id
if (!notebookId) return
+ onEdit?.()
snap.updateCell({
id: notebookId,
cellId: cell._id,
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerChatTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerChatTab.test.tsx
index 6db1c54e004..7171a783204 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerChatTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerChatTab.test.tsx
@@ -5,14 +5,13 @@ import { ExplorerChatTab } from '../ExplorerChatTab'
import { customRender } from '@/tests/lib/custom-render'
const mocks = vi.hoisted(() => ({
- addTab: vi.fn(),
createBranch: vi.fn(),
createChat: vi.fn(),
ensureChatInstance: vi.fn(),
handleTabClose: vi.fn(),
+ makeTabPermanent: vi.fn(),
openChat: vi.fn(),
push: vi.fn(),
- updateTab: vi.fn(),
useParams: vi.fn(),
assistantSnapshot: vi.fn(),
}))
@@ -35,10 +34,9 @@ vi.mock('@/state/tabs', async (importOriginal) => {
return {
...actual,
useTabsStateSnapshot: () => ({
- addTab: mocks.addTab,
handleTabClose: mocks.handleTabClose,
+ makeTabPermanent: mocks.makeTabPermanent,
openTabs: ['chat-chat-1'],
- updateTab: mocks.updateTab,
}),
}
})
@@ -59,13 +57,23 @@ vi.mock('@/components/ui/AIAssistantPanel/AssistantChat', () => ({
AssistantChat: ({
chatId,
onSelectChat,
+ onInputChange,
}: {
chatId: string
onSelectChat: (id: string) => void
+ onInputChange?: (value: string) => void
}) => (
- <button type="button" tabIndex={0} data-chat-id={chatId} onClick={() => onSelectChat('chat-2')}>
- Assistant
- </button>
+ <>
+ <button
+ type="button"
+ tabIndex={0}
+ data-chat-id={chatId}
+ onClick={() => onSelectChat('chat-2')}
+ >
+ Assistant
+ </button>
+ <textarea aria-label="Chat input" onChange={(e) => onInputChange?.(e.target.value)} />
+ </>
),
}))
@@ -80,7 +88,7 @@ describe('ExplorerChatTab', () => {
})
})
- it('renders and registers the routed chat without changing sidebar selection', () => {
+ it('renders the routed chat and ensures its instance without changing sidebar selection', () => {
customRender(<ExplorerChatTab />)
expect(mocks.ensureChatInstance).toHaveBeenCalledWith('chat-1')
@@ -88,13 +96,6 @@ describe('ExplorerChatTab', () => {
'data-chat-id',
'chat-1'
)
- expect(mocks.addTab).toHaveBeenCalledWith({
- id: 'chat-chat-1',
- type: 'chat',
- label: 'Investigate errors',
- metadata: { chatId: 'chat-1' },
- isPreview: false,
- })
})
it('routes shared chat navigation through Explorer', () => {
@@ -105,6 +106,16 @@ describe('ExplorerChatTab', () => {
expect(mocks.openChat).toHaveBeenCalledWith('chat-2')
})
+ it('persists the tab once the user starts typing in the chat input', () => {
+ customRender(<ExplorerChatTab />)
+
+ fireEvent.change(screen.getByRole('textbox', { name: 'Chat input' }), {
+ target: { value: 'How do I' },
+ })
+
+ expect(mocks.makeTabPermanent).toHaveBeenCalledWith('chat-chat-1')
+ })
+
it('removes an orphaned tab only after chat hydration completes', () => {
mocks.assistantSnapshot.mockReturnValue({
isInitialized: true,
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
index cad2ac83fad..3e7d3522ceb 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
@@ -11,7 +11,7 @@ import { isQueryCell } from '@/data/content/notebooks/notebook-schema'
import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
import { notebooksState } from '@/state/notebooks/notebooks-state'
import type { Notebook } from '@/state/notebooks/types'
-import { createTabsState, TabsStateContext } from '@/state/tabs'
+import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
@@ -81,9 +81,9 @@ const seedNotebook = (cells: Notebooks.Cell[], status: 'new' | 'saved' = 'saved'
else notebooksState.setNotebook({ projectRef: 'default', notebook })
}
-const renderNotebookTab = () =>
+const renderNotebookTab = (tabsState = createTabsState('default')) =>
customRender(
- <TabsStateContext.Provider value={createTabsState('default')}>
+ <TabsStateContext.Provider value={tabsState}>
<ExplorerNotebookTab />
</TabsStateContext.Provider>
)
@@ -336,4 +336,56 @@ describe('ExplorerNotebookTab', () => {
await waitFor(() => expect(readPersistedValue()).toBe(!initialValue))
})
+
+ it('persists the preview tab when saving the notebook', async () => {
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: () => HttpResponse.json({ id: NOTEBOOK_ID }),
+ })
+
+ const tabsState = createTabsState('default')
+ const tabId = createTabId('notebook', { id: NOTEBOOK_ID })
+ tabsState.addTab({ id: tabId, type: 'notebook', metadata: { notebookId: NOTEBOOK_ID } })
+ expect(tabsState.tabsMap[tabId]?.isPreview).toBe(true)
+
+ renderNotebookTab(tabsState)
+
+ const saveButton = await screen.findByRole('button', { name: 'Save changes' })
+ await userEvent.click(saveButton)
+
+ await waitFor(() => expect(tabsState.tabsMap[tabId]?.isPreview).toBe(false))
+ })
+
+ it('does not mark a newer edit as saved when an earlier save resolves after it', async () => {
+ let resolveSave: (() => void) | undefined
+ const savePromise = new Promise<void>((resolve) => {
+ resolveSave = resolve
+ })
+ addAPIMock({
+ method: 'put',
+ path: '/platform/projects/:ref/content',
+ response: async () => {
+ await savePromise
+ return HttpResponse.json({ id: NOTEBOOK_ID })
+ },
+ })
+
+ renderNotebookTab()
+
+ const saveButton = await screen.findByRole('button', { name: 'Save changes' })
+ await userEvent.click(saveButton)
+ await waitFor(() => expect(saveButton).toBeDisabled())
+
+ // Edit the notebook while the save request above is still in flight.
+ notebooksState.insertCellAfter({ id: NOTEBOOK_ID, cell: createMarkdownCellSkeleton() })
+ expect(notebooksState.notebooks[NOTEBOOK_ID]?.status).toBe('unsaved')
+
+ resolveSave?.()
+ await waitFor(() => expect(saveButton).toBeEnabled())
+
+ // The in-flight save only persisted the older content, so the notebook must still be
+ // considered unsaved rather than clobbered back to 'saved' by the stale response.
+ expect(notebooksState.notebooks[NOTEBOOK_ID]?.status).toBe('unsaved')
+ })
})
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx
index 8ea127fcb3d..26e9377f308 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx
@@ -2,11 +2,13 @@ import { QueryClient } from '@tanstack/react-query'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ExplorerNotebookTabCoordinator } from '../ExplorerNotebookTabCoordinator'
+import { createQueryCellSkeleton } from '../utils'
import { contentKeys } from '@/data/content/keys'
import { notebooksState } from '@/state/notebooks/notebooks-state'
import type { Notebook } from '@/state/notebooks/types'
import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'
import { customRender } from '@/tests/lib/custom-render'
+import type { Notebooks } from '@/types'
vi.mock('common', async (importOriginal) => {
const actual = await importOriginal<typeof import('common')>()
@@ -18,7 +20,7 @@ vi.mock('common', async (importOriginal) => {
const NOTEBOOK_ID = 'notebook-coordinator-test'
-const seedNotebook = (status: 'new' | 'saved') => {
+const seedNotebook = (status: 'new' | 'saved', cells: Notebooks.Cell[] = []) => {
delete notebooksState.notebooks[NOTEBOOK_ID]
const notebook: Notebook = {
id: NOTEBOOK_ID,
@@ -28,7 +30,7 @@ const seedNotebook = (status: 'new' | 'saved') => {
favorite: false,
owner_id: 1,
project_id: 1,
- content: { schema_version: 1, cells: [] },
+ content: { schema_version: 1, cells },
}
if (status === 'new') notebooksState.addNotebook({ projectRef: 'default', notebook })
else notebooksState.setNotebook({ projectRef: 'default', notebook })
@@ -67,17 +69,39 @@ describe('ExplorerNotebookTabCoordinator', () => {
expect(queryClient.getQueryData(contentKeys.resource('default', NOTEBOOK_ID))).toBeUndefined()
})
- it('leaves an unsaved notebook in the store on close', () => {
- seedNotebook('new')
+ it('discards an unsaved notebook from the store and cache on confirmed close', () => {
+ seedNotebook('new', [createQueryCellSkeleton()])
const queryClient = new QueryClient()
queryClient.setQueryData(contentKeys.resource('default', NOTEBOOK_ID), { id: NOTEBOOK_ID })
const { tabsState, tabId } = renderCoordinator(queryClient)
tabsState.closeTabs([tabId])
- expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeDefined()
- expect(queryClient.getQueryData(contentKeys.resource('default', NOTEBOOK_ID))).toEqual({
- id: NOTEBOOK_ID,
+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()
+ expect(queryClient.getQueryData(contentKeys.resource('default', NOTEBOOK_ID))).toBeUndefined()
+ })
+
+ it('asks for confirmation before closing a notebook with unsaved changes', () => {
+ seedNotebook('new', [createQueryCellSkeleton()])
+ const { tabsState, tabId } = renderCoordinator(new QueryClient())
+
+ expect(tabsState.getCloseConfirmation([tabId])).toEqual({
+ title: 'Unsaved changes',
+ description: 'You have unsaved changes in this notebook. Closing it will discard them.',
})
})
+
+ it('does not ask for confirmation when closing a saved notebook with no local edits', () => {
+ seedNotebook('saved')
+ const { tabsState, tabId } = renderCoordinator(new QueryClient())
+
+ expect(tabsState.getCloseConfirmation([tabId])).toBeNull()
+ })
+
+ it('does not ask for confirmation when closing an empty, never-persisted notebook', () => {
+ seedNotebook('new', [])
+ const { tabsState, tabId } = renderCoordinator(new QueryClient())
+
+ expect(tabsState.getCloseConfirmation([tabId])).toBeNull()
+ })
})
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
index 1801ffd177c..620f468f417 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ExplorerQueryTab } from '../ExplorerQueryTab'
import type { ReadReplicasData } from '@/data/read-replicas/replicas-query'
import { explorerQueryState } from '@/state/explorer-query'
-import { createTabsState, TabsStateContext } from '@/state/tabs'
+import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
@@ -27,8 +27,18 @@ vi.mock('common', async (importOriginal) => {
})
vi.mock('@/components/ui/CodeEditor/CodeEditor', () => ({
- CodeEditor: ({ value }: { value: string }) => (
- <textarea aria-label="SQL editor" value={value} readOnly />
+ CodeEditor: ({
+ value,
+ onInputChange,
+ }: {
+ value: string
+ onInputChange?: (value: string | undefined) => void
+ }) => (
+ <textarea
+ aria-label="SQL editor"
+ value={value}
+ onChange={(e) => onInputChange?.(e.target.value)}
+ />
),
}))
@@ -46,9 +56,9 @@ vi.mock('../QueryEditor/QuerySourceMenu', () => ({
),
}))
-const renderQueryTab = () =>
+const renderQueryTab = (tabsState = createTabsState('default')) =>
customRender(
- <TabsStateContext.Provider value={createTabsState('default')}>
+ <TabsStateContext.Provider value={tabsState}>
<ExplorerQueryTab />
</TabsStateContext.Provider>
)
@@ -214,6 +224,22 @@ describe('QueryTab execution', () => {
})
})
+ it('persists the preview tab once typing starts in the SQL editor', async () => {
+ createDraft({ _tag: 'database' })
+
+ const tabsState = createTabsState('default')
+ const tabId = createTabId('query', { id: 'query-test' })
+ tabsState.addTab({ id: tabId, type: 'query', metadata: { queryId: 'query-test' } })
+ expect(tabsState.tabsMap[tabId]?.isPreview).toBe(true)
+
+ renderQueryTab(tabsState)
+
+ const sqlEditor = await screen.findByRole('textbox', { name: 'SQL editor' })
+ await userEvent.type(sqlEditor, ' where true')
+
+ await waitFor(() => expect(tabsState.tabsMap[tabId]?.isPreview).toBe(false))
+ })
+
it('blocks a destructive query behind a confirmation modal, then runs it once confirmed', async () => {
createDraft({ _tag: 'database' }, 'delete from foo')
const executedQueries: string[] = []
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
index ea02bd93971..0b94d8cdb68 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
@@ -78,6 +78,7 @@ interface AssistantChatProps {
onBranchChat: (messageId: string) => void
composerContext?: AssistantChatComposerContext
renderHeader?: (props: AssistantChatHeaderProps) => ReactNode
+ onInputChange?: (value: string) => void
}
export const AssistantChat = ({
@@ -89,6 +90,7 @@ export const AssistantChat = ({
onBranchChat,
composerContext,
renderHeader,
+ onInputChange,
}: AssistantChatProps) => {
const { id: entityId } = useParams()
const { data: project } = useSelectedProjectQuery()
@@ -683,7 +685,10 @@ export const AssistantChat = ({
: 'Chat to Postgres...'
}
value={value}
- onValueChange={(e) => setValue(e.target.value)}
+ onValueChange={(e) => {
+ setValue(e.target.value)
+ onInputChange?.(e.target.value)
+ }}
onSubmit={(finalMessage) => {
sendMessageToAssistant(finalMessage)
}}
diff --git a/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx b/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx
index fc3ed737ed9..ed7f38d4018 100644
--- a/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx
+++ b/apps/studio/pages/project/[ref]/explorer/chat/[id].tsx
@@ -1,9 +1,37 @@
+import { useParams } from 'common'
+import { useEffect, useEffectEvent } from 'react'
+
import { ExplorerChatTab } from '@/components/interfaces/Explorer/ExplorerChatTab'
import { DefaultLayout } from '@/components/layouts/DefaultLayout'
import { ExplorerLayout } from '@/components/layouts/ExplorerLayout/ExplorerLayout'
+import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
+import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
import type { NextPageWithLayout } from '@/types'
-const ChatPage: NextPageWithLayout = () => <ExplorerChatTab />
+const ChatPage: NextPageWithLayout = () => {
+ const { id } = useParams()
+ const tabs = useTabsStateSnapshot()
+ const aiAssistant = useAiAssistantStateSnapshot()
+ const chat = id ? aiAssistant.chats[id] : undefined
+
+ const registerTab = useEffectEvent(() => {
+ if (!id || !chat) return
+
+ const nextTabId = createTabId('chat', { id })
+ tabs.addTab({
+ id: nextTabId,
+ type: 'chat',
+ label: chat.name,
+ metadata: { chatId: id },
+ isPreview: true,
+ })
+ tabs.updateTab(nextTabId, { label: chat.name })
+ })
+
+ useEffect(() => registerTab(), [id, chat?.name])
+
+ return <ExplorerChatTab />
+}
ChatPage.getLayout = (page) => (
<DefaultLayout>
diff --git a/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx b/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx
index ad8503778ce..6996a42ee48 100644
--- a/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx
+++ b/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx
@@ -24,7 +24,7 @@ const NotebookPage: NextPageWithLayout = () => {
type: 'notebook',
label: name ?? 'New Notebook',
metadata: { notebookId: id },
- isPreview: false,
+ isPreview: true,
})
})
diff --git a/apps/studio/pages/project/[ref]/explorer/query/[id].tsx b/apps/studio/pages/project/[ref]/explorer/query/[id].tsx
index 8e7ab7df1a8..9a5b4b0e8af 100644
--- a/apps/studio/pages/project/[ref]/explorer/query/[id].tsx
+++ b/apps/studio/pages/project/[ref]/explorer/query/[id].tsx
@@ -1,9 +1,35 @@
+import { useParams } from 'common'
+import { useEffect, useEffectEvent } from 'react'
+
import { ExplorerQueryTab } from '@/components/interfaces/Explorer/ExplorerQueryTab'
import { DefaultLayout } from '@/components/layouts/DefaultLayout'
import { ExplorerLayout } from '@/components/layouts/ExplorerLayout/ExplorerLayout'
+import { explorerQueryState } from '@/state/explorer-query'
+import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
import type { NextPageWithLayout } from '@/types'
const QueryPage: NextPageWithLayout = () => {
+ const { id, ref } = useParams()
+ const tabs = useTabsStateSnapshot()
+
+ const registerTab = useEffectEvent(() => {
+ if (!id || !ref) return
+
+ const restored = explorerQueryState.restoreDraft({ id, projectRef: ref })
+ const draft = explorerQueryState.drafts[id]
+ if (restored && draft) {
+ tabs.addTab({
+ id: createTabId('query', { id }),
+ type: 'query',
+ label: draft.name,
+ metadata: { queryId: id },
+ isPreview: true,
+ })
+ }
+ })
+
+ useEffect(() => registerTab(), [id, ref])
+
return <ExplorerQueryTab />
}
diff --git a/apps/studio/state/notebooks/notebooks-state.ts b/apps/studio/state/notebooks/notebooks-state.ts
index 48534a5ae4e..2bde7a7fc83 100644
--- a/apps/studio/state/notebooks/notebooks-state.ts
+++ b/apps/studio/state/notebooks/notebooks-state.ts
@@ -52,6 +52,18 @@ export const notebooksState = proxy({
}
},
+ /**
+ * Marks a notebook as persisted after its first successful save. Every
+ * later save cycle is covered by `updateCells`'s `statusOnEdit` ('saved' ->
+ * 'unsaved' -> ...), but the one-time 'new' -> 'saved' transition has no
+ * other trigger — the resource query that would otherwise pick it up is
+ * disabled while the notebook is still 'new'.
+ */
+ markSaved: ({ id }: { id: string }) => {
+ const stateNotebook = notebooksState.notebooks[id]
+ if (stateNotebook) stateNotebook.status = 'saved'
+ },
+
/**
* Rename follows its own async save directly at the call site rather than going
* through needsSaving/the debounced scheduler.