Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

[Metabot] Add prompt toggle button to the SQL editor header (#80379)

Sloan Sparger185e6d787867
diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
index 0d98c12299d..7f216c25324 100644
--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
@@ -1,5 +1,5 @@
import type { EditorView } from "@codemirror/view";
-import { EditorView as EV, keymap } from "@codemirror/view";
+import { EditorView as EV, ViewPlugin, keymap } from "@codemirror/view";
import type { Extension } from "@uiw/react-codemirror";
import {
useCallback,
@@ -51,6 +51,8 @@ export interface UseInlineSqlEditResult {
proposedQuestion: Question | undefined;
handleAcceptProposed?: (datasetQuery: DatasetQuery) => void;
handleRejectProposed?: () => void;
+ togglePrompt: () => void;
+ isPromptOpen: boolean;
}
export function useInlineSQLPrompt(
@@ -63,9 +65,15 @@ export function useInlineSQLPrompt(
const databaseId = question.databaseId();
const [portalTarget, setPortalTarget] = useState<PortalTarget | null>(null);
+ const [isPromptOpen, setIsPromptOpen] = useState(false);
const [promptValue, setPromptValue] = useState("");
const onGenerated = useCallback(() => setPromptValue(""), []);
+ const viewRef = useRef<EditorView | null>(null);
+
+ const hasAccessRef = useRef(hasSqlGenerationAccess);
+ hasAccessRef.current = hasSqlGenerationAccess;
+
useRegisterCodeEditorMetabotContext(
portalTarget?.view ?? undefined,
databaseId,
@@ -85,8 +93,8 @@ export function useInlineSQLPrompt(
} = useMetabotSQLSuggestion({ databaseId, bufferId, onGenerated });
const getSourceSql = useCallback(() => {
- return portalTarget?.view?.state.doc.toString() ?? "";
- }, [portalTarget?.view]);
+ return viewRef.current?.state.doc.toString() ?? "";
+ }, []);
const generatedSqlRef = useRef(generatedSource);
generatedSqlRef.current = generatedSource;
@@ -97,9 +105,9 @@ export function useInlineSQLPrompt(
}, [clearSuggestion]);
const hideInput = useCallback(() => {
- portalTarget?.view.dispatch({ effects: hideEffect.of() });
- portalTarget?.view.focus();
- }, [portalTarget?.view]);
+ viewRef.current?.dispatch({ effects: hideEffect.of() });
+ viewRef.current?.focus();
+ }, []);
const hideInputRef = useRef(hideInput);
useLayoutEffect(() => {
@@ -138,6 +146,33 @@ export function useInlineSQLPrompt(
hideInput();
}, [clearSuggestion, hideInput]);
+ const togglePrompt = useCallback(() => {
+ const view = viewRef.current;
+ if (!view || !hasAccessRef.current) {
+ return;
+ }
+ if (isPromptOpen) {
+ hideInput();
+ return;
+ }
+ if (generatedSqlRef.current) {
+ resetInput();
+ }
+
+ view.dispatch({ effects: toggleEffect.of({ view }) });
+ // wait until input has mounted before scrolling it into view so scroll calculations are correct
+ view.scrollDOM.addEventListener(
+ "focusin",
+ () => {
+ view.dispatch({
+ effects: EV.scrollIntoView(view.state.selection.main.head),
+ });
+ view.dom.scrollIntoView?.({ block: "nearest", behavior: "smooth" });
+ },
+ { once: true },
+ );
+ }, [isPromptOpen, hideInput, resetInput]);
+
const handleClose = () => {
hideInput();
};
@@ -168,42 +203,59 @@ export function useInlineSQLPrompt(
const handleAcceptProposed = generatedSource ? resetInput : undefined;
- const extensions = useMemo(
- () =>
- hasSqlGenerationAccess
- ? [
- createPromptInputExtension(setPortalTarget),
- keymap.of([
- {
- key: `Mod-Shift-i`,
- run: (view) => {
- if (generatedSqlRef.current) {
- resetInputRef.current();
- }
- view.dispatch({ effects: toggleEffect.of({ view }) });
- return true;
- },
- },
- ]),
- EV.updateListener.of((update) => {
- if (!update.docChanged || !generatedSqlRef.current) {
- return;
- }
- // Only clear suggestion if change was from user input, not programmatic
- const isUserEdit = update.transactions.some(
- (tr) =>
- tr.isUserEvent("input") ||
- tr.isUserEvent("delete") ||
- tr.isUserEvent("move"),
- );
- if (isUserEdit) {
- clearSuggestionRef.current();
- }
- }),
- ]
- : [],
- [hasSqlGenerationAccess],
- );
+ const extensions = useMemo(() => {
+ const promptField = createPromptInputExtension(setPortalTarget);
+ return [
+ promptField,
+ ViewPlugin.define((view) => {
+ viewRef.current = view;
+ return {
+ destroy: () => {
+ if (viewRef.current === view) {
+ viewRef.current = null;
+ }
+ },
+ };
+ }),
+ keymap.of([
+ {
+ key: `Mod-Shift-i`,
+ run: (view) => {
+ if (!hasAccessRef.current) {
+ return false;
+ }
+ if (generatedSqlRef.current) {
+ resetInputRef.current();
+ }
+ view.dispatch({ effects: toggleEffect.of({ view }) });
+ return true;
+ },
+ },
+ ]),
+ EV.updateListener.of((update) => {
+ const promptState = update.state.field(promptField, false);
+ const isVisible = promptState?.visible ?? false;
+ setIsPromptOpen(isVisible);
+ if (!isVisible) {
+ setPortalTarget(null);
+ }
+
+ if (!update.docChanged || !generatedSqlRef.current) {
+ return;
+ }
+ // Only clear suggestion if change was from user input, not programmatic
+ const isUserEdit = update.transactions.some(
+ (tr) =>
+ tr.isUserEvent("input") ||
+ tr.isUserEvent("delete") ||
+ tr.isUserEvent("move"),
+ );
+ if (isUserEdit) {
+ clearSuggestionRef.current();
+ }
+ }),
+ ];
+ }, []);
return {
extensions,
@@ -232,5 +284,7 @@ export function useInlineSQLPrompt(
handleAcceptProposed: canUseSqlGeneration
? handleAcceptProposed
: undefined,
+ togglePrompt,
+ isPromptOpen,
};
}
diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.unit.spec.tsx
new file mode 100644
index 00000000000..e7499485837
--- /dev/null
+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.unit.spec.tsx
@@ -0,0 +1,141 @@
+jest.unmock("@uiw/react-codemirror");
+
+import userEvent from "@testing-library/user-event";
+
+import { setupEnterprisePlugins } from "__support__/enterprise";
+import {
+ setupCollectionsEndpoints,
+ setupNativeQuerySnippetEndpoints,
+ setupUserMetabotPermissionsEndpoint,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { createMockEntitiesState } from "__support__/store";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { MetabotProvider } from "metabase/metabot/context";
+import { NativeQueryEditor } from "metabase/querying/components/NativeQueryEditor/NativeQueryEditor";
+import { createMockState } from "metabase/redux/store/mocks";
+import { getMetadata } from "metabase/selectors/metadata";
+import { checkNotNull } from "metabase/utils/types";
+import type Question from "metabase-lib/v1/Question";
+import {
+ createMockCard,
+ createMockNativeDatasetQuery,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+
+import { useInlineSQLPrompt } from "./useInlineSQLPrompt";
+
+jest.mock(
+ "metabase/querying/components/NativeQueryEditor/use-notebook-screen-size",
+ () => ({
+ useNotebookScreenSize: jest.fn(() => "large"),
+ }),
+);
+
+const TEST_DB = createSampleDatabase();
+
+const TEST_CARD = createMockCard({
+ dataset_query: createMockNativeDatasetQuery({
+ database: TEST_DB.id,
+ native: { query: "SELECT 1" },
+ }),
+});
+
+function TestEditor({ question }: { question: Question }) {
+ const { extensions, portalElement, togglePrompt, isPromptOpen } =
+ useInlineSQLPrompt(question, "qb");
+ const query = checkNotNull(question.legacyNativeQuery());
+
+ return (
+ <>
+ <NativeQueryEditor
+ question={question}
+ query={query}
+ setDatasetQuery={jest.fn()}
+ isNativeEditorOpen
+ isInitiallyOpen
+ extensions={extensions}
+ isPromptInputOpen={isPromptOpen}
+ onTogglePromptInput={togglePrompt}
+ >
+ <NativeQueryEditor.TopBar>
+ <NativeQueryEditor.Sidebar />
+ </NativeQueryEditor.TopBar>
+ </NativeQueryEditor>
+ {portalElement}
+ </>
+ );
+}
+
+function setup({ isMetabotEnabled = true } = {}) {
+ setupEnterprisePlugins();
+ setupUserMetabotPermissionsEndpoint();
+ setupCollectionsEndpoints({ collections: [] });
+ setupNativeQuerySnippetEndpoints();
+
+ const state = createMockState({
+ settings: mockSettings({
+ "metabot-enabled?": isMetabotEnabled,
+ "llm-metabot-configured?": true,
+ }),
+ currentUser: createMockUser(),
+ entities: createMockEntitiesState({
+ databases: [TEST_DB],
+ questions: [TEST_CARD],
+ }),
+ });
+ const question = checkNotNull(getMetadata(state).question(TEST_CARD.id));
+
+ renderWithProviders(
+ <MetabotProvider>
+ <TestEditor question={question} />
+ </MetabotProvider>,
+ { storeInitialState: state },
+ );
+}
+
+describe("useInlineSQLPrompt", () => {
+ it("toggles the inline prompt open and closed", async () => {
+ setup();
+
+ expect(await screen.findByText("SELECT")).toBeInTheDocument();
+ const button = await screen.findByLabelText("Ask Metabot");
+ expect(button).toHaveAttribute("aria-pressed", "false");
+ expect(
+ screen.queryByTestId("metabot-inline-sql-prompt"),
+ ).not.toBeInTheDocument();
+
+ await userEvent.click(button);
+ expect(
+ await screen.findByTestId("metabot-inline-sql-prompt"),
+ ).toBeInTheDocument();
+ expect(button).toHaveAttribute("aria-pressed", "true");
+
+ await userEvent.click(button);
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("metabot-inline-sql-prompt"),
+ ).not.toBeInTheDocument();
+ });
+ expect(button).toHaveAttribute("aria-pressed", "false");
+
+ await userEvent.click(button);
+ await userEvent.click(
+ await screen.findByTestId("metabot-inline-sql-cancel"),
+ );
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("metabot-inline-sql-prompt"),
+ ).not.toBeInTheDocument();
+ });
+ expect(button).toHaveAttribute("aria-pressed", "false");
+ });
+
+ it("does not render when metabot is not enabled", async () => {
+ setup({ isMetabotEnabled: false });
+
+ expect(await screen.findByLabelText("Auto-format")).toBeInTheDocument();
+ expect(screen.queryByLabelText("Ask Metabot")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx
index 6fd02f738fc..343abcde29a 100644
--- a/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx
@@ -103,6 +103,8 @@ export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {
proposedQuestion={inlineSQLPrompt?.proposedQuestion}
onAcceptProposed={inlineSQLPrompt?.handleAcceptProposed}
onRejectProposed={inlineSQLPrompt?.handleRejectProposed}
+ isPromptInputOpen={inlineSQLPrompt?.isPromptOpen}
+ onTogglePromptInput={inlineSQLPrompt?.togglePrompt}
>
<NativeQueryEditor.TopBar>
<NativeQueryEditor.ParametersList />
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/MetabotPromptButton.module.css b/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/MetabotPromptButton.module.css
new file mode 100644
index 00000000000..726dcbd0093
--- /dev/null
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/MetabotPromptButton.module.css
@@ -0,0 +1,12 @@
+.button {
+ color: var(--mb-color-text-primary);
+ transition: color 0.3s linear;
+
+ &:hover {
+ color: var(--mb-color-core-brand);
+ }
+
+ &.isSelected {
+ color: var(--mb-color-core-brand);
+ }
+}
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/MetabotPromptButton.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/MetabotPromptButton.tsx
new file mode 100644
index 00000000000..9b31bc3bd32
--- /dev/null
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/MetabotPromptButton.tsx
@@ -0,0 +1,45 @@
+import cx from "classnames";
+import { t } from "ttag";
+
+import { IconButtonWrapper } from "metabase/common/components/IconButtonWrapper";
+import { useUserMetabotPermissions } from "metabase/metabot/hooks";
+import { useSetting } from "metabase/settings";
+import { Icon, Tooltip } from "metabase/ui";
+
+import S from "./MetabotPromptButton.module.css";
+
+interface MetabotPromptButtonProps {
+ size: number;
+ isPromptInputOpen?: boolean;
+ onClick?: () => void;
+}
+
+export const MetabotPromptButton = ({
+ size,
+ isPromptInputOpen,
+ onClick,
+}: MetabotPromptButtonProps) => {
+ const { hasSqlGenerationAccess } = useUserMetabotPermissions();
+ const metabotName = useSetting("metabot-name");
+
+ if (!hasSqlGenerationAccess) {
+ return null;
+ }
+
+ const label = t`Ask ${metabotName}`;
+
+ return (
+ <Tooltip label={label}>
+ <IconButtonWrapper
+ aria-label={label}
+ aria-pressed={isPromptInputOpen}
+ className={cx(S.button, {
+ [S.isSelected]: isPromptInputOpen,
+ })}
+ onClick={onClick}
+ >
+ <Icon name="metabot" size={size} />
+ </IconButtonWrapper>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/index.ts b/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/index.ts
new file mode 100644
index 00000000000..06abe63bf40
--- /dev/null
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/MetabotPromptButton/index.ts
@@ -0,0 +1 @@
+export * from "./MetabotPromptButton";
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
index 3091803c5d7..5cf48e84ef2 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
@@ -1,6 +1,7 @@
import { t } from "ttag";
import { DataReferenceButton } from "metabase/querying/components/NativeQueryEditor/DataReferenceButton";
+import { MetabotPromptButton } from "metabase/querying/components/NativeQueryEditor/MetabotPromptButton";
import { NativeVariablesButton } from "metabase/querying/components/NativeQueryEditor/NativeVariablesButton";
import { PreviewQueryButton } from "metabase/querying/components/NativeQueryEditor/PreviewQueryButton";
import { SnippetSidebarButton } from "metabase/querying/components/NativeQueryEditor/SnippetSidebarButton";
@@ -22,6 +23,8 @@ interface NativeQueryEditorActionButtonsProps {
isRunnable: boolean;
isRunning: boolean;
isResultDirty: boolean;
+ isPromptInputOpen?: boolean;
+ onTogglePromptInput?: () => void;
isShowingDataReference: boolean;
isShowingTemplateTagsEditor: boolean;
isShowingSnippetSidebar: boolean;
@@ -42,6 +45,8 @@ export const NativeQueryEditorActionButtons = (
snippetCollections,
snippets,
features,
+ isPromptInputOpen,
+ onTogglePromptInput,
toggleDataReference,
toggleTemplateTagsEditor,
onFormatQuery,
@@ -65,6 +70,13 @@ export const NativeQueryEditorActionButtons = (
gap="lg"
align="center"
>
+ {features.promptInput && onTogglePromptInput && (
+ <MetabotPromptButton
+ size={ICON_SIZE}
+ isPromptInputOpen={isPromptInputOpen}
+ onClick={onTogglePromptInput}
+ />
+ )}
{PreviewQueryButton.shouldRender({ question }) && (
<PreviewQueryButton {...props} />
)}
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
index 091ad901066..67c1bffb368 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
@@ -85,6 +85,7 @@ export type NativeQueryEditorCoreProps = Omit<
isResultDirty?: boolean;
isRunnable?: boolean;
isRunning?: boolean;
+ isPromptInputOpen?: boolean;
isShowingDataReference?: boolean;
isShowingSnippetSidebar?: boolean;
isShowingTemplateTagsEditor?: boolean;
@@ -98,6 +99,7 @@ export type NativeQueryEditorCoreProps = Omit<
onOpenModal?: (modalType: QueryModalType) => void;
onRejectProposed?: () => void;
onSetDatabaseId?: (id: DatabaseId) => void;
+ onTogglePromptInput?: () => void;
openDataReferenceAtQuestion?: (id: CardId) => void;
openSnippetModalWithSelectedText?: () => void;
placeholder?: string;
@@ -143,6 +145,7 @@ export const NativeQueryEditorRoot = forwardRef<
insertSnippet,
isNativeEditorOpen,
isInitiallyOpen,
+ isPromptInputOpen = false,
isResultDirty = false,
isRunnable = false,
isRunning = false,
@@ -156,6 +159,7 @@ export const NativeQueryEditorRoot = forwardRef<
onOpenModal,
onRejectProposed,
onSetDatabaseId,
+ onTogglePromptInput,
openDataReferenceAtQuestion,
openSnippetModalWithSelectedText,
placeholder,
@@ -310,6 +314,8 @@ export const NativeQueryEditorRoot = forwardRef<
nativeEditorSelectedText,
snippets,
snippetCollections,
+ isPromptInputOpen,
+ onTogglePromptInput,
isShowingDataReference,
isShowingSnippetSidebar,
isShowingTemplateTagsEditor,
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx
index dcac28b56b6..0f1dedf4fb5 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx
@@ -50,6 +50,8 @@ export interface NativeQueryEditorContextValue {
snippets: NativeQuerySnippet[];
snippetCollections: Collection[];
+ isPromptInputOpen?: boolean;
+ onTogglePromptInput?: () => void;
isShowingDataReference: boolean;
isShowingSnippetSidebar: boolean;
isShowingTemplateTagsEditor: boolean;
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/slots/Sidebar.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/slots/Sidebar.tsx
index a25dc23500c..1422ff12ac9 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/slots/Sidebar.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/slots/Sidebar.tsx
@@ -30,6 +30,7 @@ export function Sidebar({ features = DEFAULT_FEATURES }: SidebarProps) {
isRunnable,
isRunning,
isResultDirty,
+ isPromptInputOpen,
isShowingDataReference,
isShowingTemplateTagsEditor,
isShowingSnippetSidebar,
@@ -38,6 +39,7 @@ export function Sidebar({ features = DEFAULT_FEATURES }: SidebarProps) {
toggleTemplateTagsEditor,
onOpenModal,
onFormatQuery,
+ onTogglePromptInput,
} = useNativeQueryEditorContext();
if (!isNativeEditorOpen || readOnly) {
@@ -54,6 +56,8 @@ export function Sidebar({ features = DEFAULT_FEATURES }: SidebarProps) {
isRunnable={isRunnable}
isRunning={isRunning}
isResultDirty={isResultDirty}
+ isPromptInputOpen={isPromptInputOpen}
+ onTogglePromptInput={onTogglePromptInput}
isShowingDataReference={isShowingDataReference}
isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}
isShowingSnippetSidebar={isShowingSnippetSidebar}