Files
supabase/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
T
Saxon FletcherandClaude Opus 5 7880c2f079 fix(studio): explorer chat and notebook layout refinements (#50453)
Five layout fixes across Explorer chat, notebooks, and the sidebar.

### Chat

- **Conversation fade overlapped the scrollbar.** The top and bottom
gradients are positioned against the conversation's padding box, which
includes the scroll container's scrollbar gutter, so `inset-x-0` painted
them over the scrollbar. They now stop at the conversation's content
gutter, which `Conversation` owns for both the content and the fades.
- **Composer background bled past the input's radius.** The form paints
the surface behind the textarea but had no radius of its own, so its
square corners showed outside the `rounded-lg` input. It now shares the
radius.
- **Message parts used two different widths.** Wide parts come down to
`max-w-3xl` so every part shares a column, matching `AssistantQueryCell`
and `AssistantNotebookPreview`. `isWide` / `isWideMessagePart` stay in
place with both widths equal, so a part can diverge again later without
rebuilding the mechanism.

### Notebooks

- **Cell controls sat at the container edge.** Each cell centred itself
at its own max width while the grip and add-cell button stayed at the
far left of the full-width row, leaving a large gap. `SortableSection`
takes a `sectionWidth` and carries its control gutter twice — once as
the controls, once as padding on the other side — so the section stays
centred with its controls immediately beside it. Cell widths are
unchanged (prose `48rem`, query `72rem`); set them equal and the two
cell types' controls line up on their own.

The controls stay in flow rather than floating in an outside gutter, so
on a viewport narrower than the cap the row just fills the space instead
of clipping the controls into the padding.

### Sidebar

- **Search icon didn't line up with the menu row icons.** The row box
already sits flush with the search input's box, so rows moved from
`pl-3` to `pl-2` to put their icons on the same 8px offset the search
icon uses. Spacing between the input and the list now matches the 12px
side padding.

### Testing

`pnpm --filter studio run typecheck`, Prettier, and 378 tests across
`Explorer`, `ProjectHome`, `AIAssistantPanel`, and `ExplorerLayout`
pass. ESLint warning counts are unchanged from master.

These were reasoned from layout rather than checked in a browser, so
they're worth a look on a preview before merge.

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

## Summary by CodeRabbit

* **UI Improvements**
* Updated Explorer layouts with flexible, configurable widths for
notebook and query sections.
  * Refined navigation spacing and padding across Explorer views.
* Centered and standardized AI Assistant preview, query, and message
content widths.
  * Improved chat form styling with rounded corners.
* Adjusted conversation spacing and fade overlays to avoid overlapping
the scrollbar.
* Preserved full-width behavior where appropriate while keeping controls
aligned.

* **Tests**
* Updated layout tests to reflect revised width and alignment behavior.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 11:39:30 +08:00

192 lines
5.9 KiB
TypeScript

import { useRef, useState } from 'react'
import { identifyQueryType } from './AIAssistant.utils'
import {
changeAssistantQuerySource,
createAssistantQueryModel,
DEFAULT_ASSISTANT_LOGS_QUERY_TITLE,
DEFAULT_ASSISTANT_QUERY_TITLE,
getAssistantQueryDisplay,
setAssistantQuerySql,
shouldClearAssistantQueryResult,
} from './AssistantQueryCell.utils'
import { Confirm } from './Confirm'
import { type ConfirmFooterApprovalState } from './Confirm.utils'
import { QueryEditor } from '@/components/interfaces/Explorer/QueryEditor'
import { type QueryDisplay, type QueryResult } from '@/components/interfaces/Explorer/types'
import {
type QuerySourceBinding,
type QuerySourceTag,
} from '@/data/query-sources/query-source-registry'
import { useTrack } from '@/lib/telemetry/track'
import { useAiAssistantState } from '@/state/ai-assistant-state'
import { useLocalRoleImpersonationState } from '@/state/role-impersonation-state'
interface AssistantQueryCellProps {
id: string
sql: string
title?: string
initialResult?: QueryResult
source?: QuerySourceBinding
view?: 'table' | 'chart'
xAxis?: string
yAxis?: string
/** Follow incoming SQL while the assistant is still streaming the query text. */
isStreaming?: boolean
confirmState?: ConfirmFooterApprovalState
onApprove?: () => void
onDeny?: () => void
}
const DEFAULT_SOURCE: QuerySourceBinding = { _tag: 'database' }
const QUERY_OUTCOME_MESSAGES: Record<
QuerySourceTag,
{ success: string; error: string; denied: string }
> = {
database: {
success: 'Query executed',
error: 'Failed to execute SQL',
denied: 'Skipped query',
},
logs: {
success: 'Query executed',
error: 'Failed to query logs',
denied: 'Skipped query',
},
}
/** Assistant adapter around the shared QueryEditor. Local state only — nothing is persisted. */
export const AssistantQueryCell = ({
id,
sql: initialSql,
title: initialTitle,
initialResult,
source = DEFAULT_SOURCE,
view,
xAxis,
yAxis,
isStreaming = false,
confirmState,
onApprove,
onDeny,
}: AssistantQueryCellProps) => {
const track = useTrack()
const roleImpersonationState = useLocalRoleImpersonationState()
const aiAssistantState = useAiAssistantState()
const fallbackTitle =
initialTitle?.trim() ||
(source._tag === 'logs' ? DEFAULT_ASSISTANT_LOGS_QUERY_TITLE : DEFAULT_ASSISTANT_QUERY_TITLE)
const hasExplicitAxes = Boolean(xAxis || yAxis)
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)
const previousId = useRef(id)
if (previousId.current !== id) {
previousId.current = id
setTitle(fallbackTitle)
setQuery(createAssistantQueryModel(initialSql, source))
setShowQuery(true)
setResultOverride(undefined)
setLocalDisplay(undefined)
}
if (isStreaming && query.uncheckedSql !== initialSql) {
setQuery((current) => setAssistantQuerySql(current, initialSql))
}
const result = resultOverride === undefined ? initialResult : (resultOverride ?? undefined)
const display =
localDisplay ??
getAssistantQueryDisplay({
view,
xAxis,
yAxis,
sql: query.uncheckedSql,
rows: result?.rows,
})
const handleTitleChange = (value: string) => {
const nextTitle = value.trim()
if (!nextTitle) return
setTitle(nextTitle)
}
const handleSourceChange = (nextSource: QuerySourceBinding) => {
const isBackendChange = nextSource._tag !== query._tag
if (shouldClearAssistantQueryResult(query, nextSource)) setResultOverride(null)
if (isBackendChange && !hasExplicitAxes) setLocalDisplay(undefined)
setQuery((current) => changeAssistantQuerySource(current, nextSource))
}
const handleDisplayChange = (nextDisplay: QueryDisplay) => {
setLocalDisplay(nextDisplay)
}
const handleResultChange = (nextResult: QueryResult) => {
setResultOverride(nextResult)
}
const handleRun = () => {
const sql = query.uncheckedSql
const mutationType = identifyQueryType(sql)
track('assistant_suggestion_run_query_clicked', {
queryType: mutationType ? 'mutation' : 'select',
...(mutationType ? { mutationType } : {}),
})
}
const isRunDisabled =
confirmState === 'approval-requested' || confirmState === 'approval-responded'
const outcomeMessages = QUERY_OUTCOME_MESSAGES[source._tag]
return (
<Confirm
fill
className="w-full max-w-3xl mx-auto"
state={confirmState}
message="Assistant wants to run this query"
cancelLabel="Skip"
confirmLabel="Run query"
confirmLabelLoading="Running..."
successMessage={outcomeMessages.success}
errorMessage={outcomeMessages.error}
deniedMessage={outcomeMessages.denied}
onCancel={onDeny}
onConfirm={onApprove}
>
<QueryEditor
isReadOnly
id={id}
variant="viewport"
className="h-96"
title={title}
query={query}
result={result}
showQuery={showQuery}
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
display={display}
isRunDisabled={isRunDisabled}
onTitleChange={handleTitleChange}
onSqlChange={(sql) => setQuery((current) => setAssistantQuerySql(current, sql))}
onSourceChange={handleSourceChange}
onResultChange={handleResultChange}
onRowLimitChange={(rowLimit) =>
setQuery((current) => (current._tag === 'database' ? { ...current, rowLimit } : current))
}
onDisplayChange={handleDisplayChange}
onRun={handleRun}
onDebug={aiAssistantState.setInitialInput}
/>
</Confirm>
)
}