Files
supabase/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx
Pamela ChiaandJoshen Lim 4a941518e3 feat(studio): track Explorer runs and saves (#51004)
I added outcome events for Explorer query runs and successful manual
notebook saves. Existing page visits and preview toggles do not show
whether users complete queries or persist notebooks.

**Changed:**
- **Query usage:** Accepted runs from query tabs and notebook cells emit
submitted and terminal outcome events with a shared run ID. Canceled
confirmations emit no run events.
- **Notebook adoption:** Successful manual saves emit created or updated
events. Recreated notebooks count as creations. Unsaved drafts and
failed saves emit neither.
- **Event metadata:** Explorer action events use `Explorer` as their
page title.

**Note:** Assistant-generated saves are outside this PR. Custom
properties omit SQL and notebook content. Page visits still carry the
browser title, which can include a notebook name.

## To test

Tested on the staging preview:
- [x] Run valid and invalid SQL from an Explorer query tab. Each run
emits one submitted event and one matching completed or failed event
with the same run ID.
- [x] Run database and Logs notebook query cells, then add a markdown
cell. The query cells emit matching event pairs; the markdown cell emits
no query event.
- [x] Save a new notebook, then edit and save it again. The successful
saves emit created and updated events.
- [x] Cancel a guarded query. It emits no query run event.
- [ ] Recreate a notebook deleted on the server after local edits. A
successful save emits created, not updated.
- [x] Inspect an Explorer action event request. Its page title is
`Explorer`; page visits still use the browser title.
- [ ] Force a notebook save failure. It should emit no save event. This
case was not tested manually.

## Linear
- fixes GROWTH-1298


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Analytics**
* Explorer query runs are tracked for database and log queries,
including whether they complete or fail.
* Query activity is associated with its location in Explorer, such as a
query tab or notebook cell.
  * Successful notebook saves are tracked as creations or updates.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-09-29 13:54:13 -07:00

207 lines
7.1 KiB
TypeScript

import { type Hotkey } from '@tanstack/react-hotkeys'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { AlignLeft, Check, Keyboard, Loader2, MoreVertical, SquareCode } from 'lucide-react'
import { useRouter } from 'next/router'
import { useCallback, useContext, useEffect, useRef, useState } from 'react'
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
KeyboardShortcut,
} from 'ui'
import { ExplorerToolbarAction } from './ExplorerToolbar'
import { QueryEditor, type ExplorerQueryModel, type QueryEditorHandle } from './QueryEditor'
import { SaveQueryDropdown } from './SaveQueryDropdown'
import { type QueryDisplay, type QueryResult } from './types'
import { toQuerySourceBinding } from '@/data/query-sources/query-source-registry'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { explorerQueryState, useExplorerQueryStateSnapshot } from '@/state/explorer-query'
import { useControlledRoleImpersonationState } from '@/state/role-impersonation-state'
import { hotkeyToKeys } from '@/state/shortcuts/formatShortcut'
import { SHORTCUT_DEFINITIONS, SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { createTabId, TabsStateContext } from '@/state/tabs'
/** Query-tab lifecycle adapter around the shared QueryEditor. */
export const ExplorerQueryTab = () => {
const router = useRouter()
const { id, ref } = useParams()
const tabs = useContext(TabsStateContext)
const querySnap = useExplorerQueryStateSnapshot()
const [isIntellisenseEnabled, setIsIntellisenseEnabled] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
true
)
const queryEditorRef = useRef<QueryEditorHandle>(null)
const hotkeySequnece: Hotkey | undefined =
SHORTCUT_DEFINITIONS[SHORTCUT_IDS.SQL_EDITOR_FORMAT].sequence[0]
const formatKeys = hotkeySequnece ? hotkeyToKeys(hotkeySequnece) : undefined
const [restoredQueryKey, setRestoredQueryKey] = useState<string>()
const [showQuery, setShowQuery] = useState(true)
const stateDraft = id ? querySnap.drafts[id] : undefined
const draft = stateDraft?.projectRef === ref ? stateDraft : undefined
const result = draft && id ? querySnap.results[id] : undefined
const queryKey = id && ref ? `${ref}:${id}` : undefined
const isDraftReady = !!queryKey && restoredQueryKey === queryKey
const roleImpersonationState = useControlledRoleImpersonationState(
draft?._tag === 'database' ? draft.role : undefined,
useCallback(
(role) => {
if (id) explorerQueryState.setRole({ id, role })
},
[id]
)
)
useEffect(() => {
if (!id || !ref) return
setShowQuery(true)
explorerQueryState.restoreDraft({ id, projectRef: ref })
setRestoredQueryKey(`${ref}:${id}`)
}, [id, ref])
useEffect(() => {
if (!id || !isDraftReady || !draft?.pendingAutoRun) return
queryEditorRef.current?.run()
explorerQueryState.clearPendingAutoRun({ id })
}, [id, isDraftReady, draft?.pendingAutoRun])
if (!queryKey || restoredQueryKey !== queryKey) {
return (
<div
role="status"
aria-label="Loading query"
className="flex h-full items-center justify-center bg-surface-100"
>
<Loader2 className="animate-spin text-foreground-muted" size={18} />
</div>
)
}
if (!id || !draft) {
return (
<div className="flex h-full flex-col items-center justify-center gap-3 bg-surface-100">
<SquareCode className="text-foreground-muted" size={24} />
<div className="text-center">
<p className="text-sm font-medium">Query draft not found</p>
<p className="text-sm text-foreground-lighter">
This local draft may have been closed or cleared from this browser.
</p>
</div>
<Button variant="primary" onClick={() => router.push(`/project/${ref}/explorer`)}>
Back to Explorer
</Button>
</div>
)
}
const display: QueryDisplay = {
view: draft.view,
chart: draft.chart ? { ...draft.chart, y_series: [...draft.chart.y_series] } : undefined,
}
const query: ExplorerQueryModel =
draft._tag === 'logs'
? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }
: {
...toQuerySourceBinding(draft),
uncheckedSql: draft.uncheckedSql,
rowLimit: draft.rowLimit,
}
const persistTab = () => tabs.makeTabPermanent(createTabId('query', { id }))
const handleResultChange = (nextResult: QueryResult) => {
explorerQueryState.setResult({
id,
result: { ...nextResult, executedAt: Date.now() },
})
}
return (
<QueryEditor
ref={queryEditorRef}
id={id}
location={{ surface: 'query_tab', queryId: id }}
variant="viewport"
title={draft.name}
query={query}
result={result}
display={display}
showQuery={showQuery}
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
persistTab()
const name = value.trim() || 'Run SQL'
explorerQueryState.updateDraft({ id, name })
tabs.updateTab(createTabId('query', { id }), { label: name })
}}
onSqlChange={(sql) => {
persistTab()
explorerQueryState.updateDraft({ id, sql })
}}
onSourceChange={(source) => {
persistTab()
explorerQueryState.updateDraft({ id, source })
}}
onRowLimitChange={(rowLimit) => {
persistTab()
explorerQueryState.updateDraft({ id, rowLimit })
}}
onResultChange={handleResultChange}
onDisplayChange={(display) => {
persistTab()
explorerQueryState.setDisplay({ id, display })
}}
toolbarActions={
<>
<SaveQueryDropdown
query={{ title: draft.name, sql: draft.uncheckedSql }}
source={toQuerySourceBinding(draft)}
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<ExplorerToolbarAction icon={<MoreVertical size={16} strokeWidth={2} />} />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-48" align="end">
<DropdownMenuItem
className="justify-between"
onClick={() => setIsIntellisenseEnabled(!isIntellisenseEnabled)}
>
<div className="flex items-center gap-x-2">
<Keyboard size={14} />
<span>Intellisense enabled</span>
</div>
{isIntellisenseEnabled && <Check className="text-primary" size={16} />}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="justify-between"
onClick={() => queryEditorRef.current?.prettify()}
>
<span className="flex items-center gap-x-2">
<AlignLeft size={14} />
Prettify SQL
</span>
{formatKeys && <KeyboardShortcut keys={formatKeys} />}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
}
/>
)
}