Skip to content

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

[Metabot] Inline SQL entry point (#66688)

Sloan Spargerf9b914af2be4
diff --git a/e2e/test/scenarios/metabot/metabot.cy.spec.ts b/e2e/test/scenarios/metabot/metabot.cy.spec.ts
index fc4fa6d4ffc..c336cb13ee5 100644
--- a/e2e/test/scenarios/metabot/metabot.cy.spec.ts
+++ b/e2e/test/scenarios/metabot/metabot.cy.spec.ts
@@ -159,33 +159,6 @@ d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
});
});
- it("Metabot chat should be controlled from the native editor", () => {
- H.startNewNativeQuestion();
- H.NativeEditor.get().should("be.visible");
-
- cy.findByTestId("native-query-top-bar")
- .findByLabelText("Open Metabot chat")
- .should("be.enabled")
- .click();
- H.expectUnstructuredSnowplowEvent({
- event: "metabot_chat_opened",
- triggered_from: "native_editor",
- });
-
- cy.findByTestId("native-query-top-bar")
- .findByLabelText("Close Metabot chat")
- .should("be.enabled")
- .click();
- cy.log("We don't track closing the chat");
- H.expectUnstructuredSnowplowEvent(
- {
- event: "metabot_chat_opened",
- triggered_from: "native_editor",
- },
- 1,
- );
- });
-
describe("Metabot chat", () => {
beforeEach(() => {
cy.visit("/");
diff --git a/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts b/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts
new file mode 100644
index 00000000000..85341585612
--- /dev/null
+++ b/e2e/test/scenarios/metabot/native-sql-generation.cy.spec.ts
@@ -0,0 +1,242 @@
+const { H } = cy;
+
+// Helper functions
+const isMac = Cypress.platform === "darwin";
+const metaKey = isMac ? "Meta" : "Control";
+
+const toggleInlineSQLPrompt = () =>
+ H.NativeEditor.get().realPress([metaKey, ";"]);
+
+const inlinePrompt = () => cy.findByTestId("metabot-inline-sql-prompt");
+const inlinePromptInput = () =>
+ inlinePrompt().find(".ProseMirror[contenteditable=true]");
+const generateButton = () => cy.findByTestId("metabot-inline-sql-generate");
+const cancelButton = () => cy.findByTestId("metabot-inline-sql-cancel");
+const errorMessage = () => cy.findByTestId("metabot-inline-sql-error");
+const acceptButton = () => cy.findByTestId("accept-proposed-changes-button");
+const rejectButton = () => cy.findByTestId("reject-proposed-changes-button");
+
+describe("Native SQL generation", () => {
+ describe("OSS", { tags: "@OSS" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("should not be available in OSS", () => {
+ H.startNewNativeQuestion();
+ H.NativeEditor.get().should("be.visible");
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("not.exist");
+ });
+ });
+
+ describe("ee", () => {
+ describe("single db", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ cy.intercept("POST", "/api/ee/metabot-v3/agent-streaming").as(
+ "agentReq",
+ );
+ });
+
+ it("should be able to successfully generate sql", () => {
+ H.startNewNativeQuestion({ query: "SELECT 1" });
+ H.NativeEditor.get().should("be.visible");
+
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("be.visible");
+ generateButton().should("be.disabled");
+
+ inlinePromptInput().type("select all users");
+ generateButton().should("be.enabled");
+
+ H.mockMetabotResponse({
+ body: mockCodeEditResponse("SELECT * FROM users"),
+ delay: 100,
+ });
+ generateButton().click();
+ generateButton().should("contain", "Generating...");
+ cy.wait("@metabotAgent").then(({ request }) => {
+ const codeEditor = request.body.context.user_is_viewing.find(
+ (ctx: { type: string }) => ctx.type === "code_editor",
+ );
+ expect(codeEditor).to.exist;
+ expect(codeEditor.buffers).to.have.length(1);
+ expect(codeEditor.buffers[0].source.language).to.eq("sql");
+ expect(codeEditor.buffers[0].source.databaseId).to.eq(1); // Sample Database
+ });
+
+ // should auto-close input and show diff with accept/reject buttons
+ inlinePrompt().should("not.exist");
+ acceptButton().should("be.visible");
+ rejectButton().should("be.visible");
+ H.NativeEditor.get().should("contain", "SELECT 1");
+ H.NativeEditor.get().should("contain", "SELECT * FROM users");
+
+ // should be able to accept changes
+ acceptButton().click();
+ acceptButton().should("not.exist");
+ rejectButton().should("not.exist");
+ H.NativeEditor.get().should("not.contain", "SELECT 1");
+ H.NativeEditor.get().should("contain", "SELECT * FROM users");
+ });
+
+ it("should be able to correctly control the input", () => {
+ H.startNewNativeQuestion();
+ H.NativeEditor.get().should("be.visible");
+
+ // open / close the editor via key press
+ inlinePrompt().should("not.exist");
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("be.visible");
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("not.exist");
+
+ // cancel button should close
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("be.visible");
+ cancelButton().click();
+ inlinePrompt().should("not.exist");
+
+ // cancel button should cancel inflight request
+ toggleInlineSQLPrompt();
+ inlinePromptInput().type("select all users");
+ H.mockMetabotResponse({
+ body: mockCodeEditResponse("SELECT * FROM users"),
+ delay: 1000,
+ });
+ generateButton().click();
+ generateButton().should("contain", "Generating...");
+ cancelButton().click();
+ cy.get("@metabotAgent").its("state").should("eq", "Errored");
+ inlinePrompt().should("not.exist");
+ acceptButton().should("not.exist");
+ });
+ });
+
+ describe("multi-db", () => {
+ beforeEach(() => {
+ H.restore("postgres-12");
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ cy.intercept("POST", "/api/ee/metabot-v3/agent-streaming").as(
+ "agentReq",
+ );
+ });
+
+ it("should manage conversation state correctly", () => {
+ H.startNewNativeQuestion({ query: "SELECT 1" });
+ H.NativeEditor.get().should("be.visible");
+
+ // open input, send a prompt, get suggestion back
+ toggleInlineSQLPrompt();
+ inlinePromptInput().type("select all users");
+ H.mockMetabotResponse({
+ body: mockCodeEditResponse("SELECT * FROM users"),
+ });
+ generateButton().click();
+ cy.wait("@metabotAgent");
+ acceptButton().should("be.visible");
+
+ // reject the change and open input again
+ rejectButton().click();
+ acceptButton().should("not.exist");
+ H.NativeEditor.get().should("contain", "SELECT 1");
+ H.NativeEditor.get().should("not.contain", "SELECT * FROM users");
+ H.NativeEditor.focus();
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("be.visible");
+
+ // send another message, history should contain rejection info
+ inlinePromptInput().type("try again");
+ H.mockMetabotResponse({
+ body: mockCodeEditResponse("SELECT id FROM users"),
+ });
+ generateButton().click();
+ cy.wait("@metabotAgent").then(({ request }) => {
+ expect(request.body.history).to.have.length.greaterThan(0);
+ expect(request.body.message).to.include(
+ "User rejected the following suggestion:\n\nSELECT * FROM users",
+ );
+ });
+ acceptButton().should("be.visible");
+
+ // change the selected database, should close the input
+ rejectButton().click();
+ H.NativeEditor.focus();
+ toggleInlineSQLPrompt();
+ inlinePrompt().should("be.visible");
+ H.NativeEditor.selectDataSource("QA Postgres12");
+ inlinePrompt().should("not.exist");
+
+ // open again, send a prompt, req.body.history should be empty
+ H.NativeEditor.focus();
+ toggleInlineSQLPrompt();
+ inlinePromptInput().type("select something");
+ H.mockMetabotResponse({
+ body: mockCodeEditResponse("SELECT 123"),
+ });
+ generateButton().click();
+ cy.wait("@metabotAgent").then(({ request }) => {
+ expect(request.body.history).to.have.length(0);
+ });
+
+ // should get a valid response back
+ acceptButton().should("be.visible");
+ H.NativeEditor.get().should("contain", "SELECT 123");
+
+ // leave the page, go to new SQL page and send a new prompt
+ acceptButton().click();
+ cy.visit("/");
+ H.startNewNativeQuestion();
+ H.NativeEditor.get().should("be.visible");
+ H.NativeEditor.focus();
+ toggleInlineSQLPrompt();
+ inlinePromptInput().type("new prompt");
+ H.mockMetabotResponse({
+ body: mockCodeEditResponse("SELECT 456"),
+ });
+ generateButton().click();
+ cy.wait("@metabotAgent").then(({ request }) => {
+ expect(request.body.history).to.have.length(0);
+ });
+ acceptButton().should("be.visible");
+
+ // manually editing the editor should dismiss suggestion buttons
+ H.NativeEditor.get().click();
+ H.NativeEditor.get().realPress([metaKey, "a"]);
+ H.NativeEditor.get().realPress("Backspace");
+ acceptButton().should("not.exist");
+ rejectButton().should("not.exist");
+ });
+
+ it("should show error if no code_edit is received", () => {
+ H.startNewNativeQuestion();
+ H.NativeEditor.get().should("be.visible");
+
+ toggleInlineSQLPrompt();
+ inlinePromptInput().type("do something");
+ H.mockMetabotResponse({
+ body: mockTextOnlyResponse("I can help with that!"),
+ });
+ generateButton().click();
+ cy.wait("@metabotAgent");
+
+ errorMessage().should("be.visible");
+ acceptButton().should("not.exist");
+ });
+ });
+ });
+});
+
+// Response helpers
+const mockCodeEditResponse = (sql: string) =>
+ `2:{"type":"code_edit","version":1,"value":{"bufferId":"qb","mode":"rewrite","value":"${sql}"}}
+d:{"finishReason":"stop","usage":{"promptTokens":100,"completionTokens":10}}`;
+
+const mockTextOnlyResponse = (text: string) =>
+ `0:"${text}"
+d:{"finishReason":"stop","usage":{"promptTokens":100,"completionTokens":10}}`;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts
index c4dac4cb0b0..e4b27b56e66 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts
@@ -197,7 +197,7 @@ export type AIStreamingConfig = {
onError?: (error: StreamPartValue<"error">) => void;
};
-interface ProcessedChatResponse extends AccumulatedStreamParts {
+export interface ProcessedChatResponse extends AccumulatedStreamParts {
aborted: boolean;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts
index 7f72585f043..768a89ccde4 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/schemas.ts
@@ -1,6 +1,10 @@
import * as Yup from "yup";
-import type { MetabotTodoItem, SuggestedTransform } from "metabase-types/api";
+import type {
+ MetabotCodeEdit,
+ MetabotTodoItem,
+ SuggestedTransform,
+} from "metabase-types/api";
export const dataPartSchema = Yup.object({
type: Yup.string().required(),
@@ -12,6 +16,7 @@ export const knownDataPartTypes = [
"navigate_to",
"state",
"todo_list",
+ "code_edit",
"transform_suggestion",
];
@@ -19,7 +24,8 @@ export type KnownDataPart =
| { type: "navigate_to"; version: 1; value: string }
| { type: "state"; version: 1; value: Record<string, any> }
| { type: "todo_list"; version: 1; value: MetabotTodoItem[] }
- | { type: "transform_suggestion"; version: 1; value: SuggestedTransform };
+ | { type: "transform_suggestion"; version: 1; value: SuggestedTransform }
+ | { type: "code_edit"; version: 1; value: MetabotCodeEdit };
export const toolCallPartSchema = Yup.object({
toolCallId: Yup.string().required(),
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
index 50fae83370a..238af8dcc22 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChat.tsx
@@ -85,9 +85,7 @@ export const MetabotChat = ({
<Box ref={headerRef} className={Styles.header}>
<Flex align-items="center">
<Text lh={1} fz="sm" c="text-secondary">
- {metabot.profileOverride
- ? t`Using profile: ${metabot.profileOverride}`
- : t`Metabot isn't perfect. Double-check results.`}
+ {t`Metabot isn't perfect. Double-check results.`}
</Text>
</Flex>
@@ -206,7 +204,7 @@ export const MetabotChat = ({
onChange={metabot.setPrompt}
onSubmit={handleEditorSubmit}
onStop={metabot.cancelRequest}
- suggestionModels={config.suggestionModels}
+ suggestionConfig={{ suggestionModels: config.suggestionModels }}
/>
</Paper>
</Box>
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css
index 8457dc5f743..d7fec6045d0 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.module.css
@@ -75,53 +75,3 @@
min-width: 0;
width: 100%;
}
-
-.content :global(.ProseMirror) {
- border: none;
- border-radius: 0;
- background: transparent;
- outline: none;
- width: 100%;
- padding: 0.5rem 0;
- line-height: 1.7;
- color: var(--mb-color-text-dark);
- font-size: var(--mantine-font-size-md);
- min-height: 1.7em;
- white-space: pre-wrap;
- word-break: break-word;
-
- &:focus {
- outline: none;
- }
-}
-
-.content :global(.ProseMirror p) {
- margin: 0;
-}
-
-.content :global(.is-empty:first-child:before) {
- color: var(--mb-color-text-light);
- content: attr(data-placeholder);
- height: 0;
- pointer-events: none;
- position: absolute;
-}
-
-.content.disabled :global(.ProseMirror) {
- opacity: 1;
- background: transparent;
- cursor: not-allowed;
-}
-
-.smartLink {
- display: inline-flex;
- align-items: center;
- gap: 0.25rem;
- padding: 0 0.25rem;
- background: var(--mb-color-background-hover);
- border-radius: 0.25rem;
- color: var(--mb-color-brand);
- text-decoration: none;
- font-weight: 500;
- vertical-align: baseline;
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx
index 3b0501417ff..ffefed24d81 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx
@@ -1,222 +1,64 @@
-import Document from "@tiptap/extension-document";
-import HardBreak from "@tiptap/extension-hard-break";
-import Paragraph from "@tiptap/extension-paragraph";
-import { Placeholder } from "@tiptap/extension-placeholder";
-import Text from "@tiptap/extension-text";
-import { TextSelection } from "@tiptap/pm/state";
-import type { EditorView } from "@tiptap/pm/view";
-import { EditorContent, useEditor } from "@tiptap/react";
import cx from "classnames";
-import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
-import { t } from "ttag";
+import { forwardRef } from "react";
-import { useSelector } from "metabase/lib/redux";
-import type { MetabotChatInputRef } from "metabase/metabot";
-import { createMentionSuggestion } from "metabase/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion";
-import {
- MetabotMentionExtension,
- MetabotMentionPluginKey,
-} from "metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotMentionExtension";
-import { SmartLink } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";
-import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";
-import { createSuggestionRenderer } from "metabase/rich_text_editing/tiptap/extensions/suggestionRenderer";
-import { getSetting } from "metabase/selectors/settings";
+import type { MetabotPromptInputRef } from "metabase/metabot";
import { Box, Icon, UnstyledButton } from "metabase/ui";
-import S from "./MetabotChatEditor.module.css";
import {
- parseMetabotMessageToTiptapDoc,
- serializeTiptapToMetabotMessage,
-} from "./utils";
-
-interface Props {
- value: string;
- placeholder?: string;
- autoFocus?: boolean;
- isResponding?: boolean;
- onChange: (value: string) => void;
- onSubmit: () => void;
- onStop: () => void;
- suggestionModels: SuggestionModel[];
-}
-
-export const MetabotChatEditor = forwardRef<MetabotChatInputRef | null, Props>(
- (
- {
- value,
- placeholder = t`Tell me to do something, or ask a question`,
- autoFocus = false,
- isResponding = false,
- suggestionModels,
- onChange,
- onSubmit,
- onStop,
- },
- ref,
- ) => {
- const siteUrl = useSelector((state) => getSetting(state, "site-url"));
- const serializedRef = useRef(value);
-
- const extensions = [
- Document,
- Paragraph,
- Text,
- Placeholder.configure({ placeholder }),
- HardBreak,
- SmartLink.configure({
- HTMLAttributes: { class: S.smartLink },
- siteUrl,
- }),
- MetabotMentionExtension.configure({
- suggestion: {
- render: createSuggestionRenderer(
- createMentionSuggestion({
- searchModels: suggestionModels,
- canFilterSearchModels: true,
- canBrowseAll: false,
- }),
- ),
- },
- }),
- ];
-
- const editor = useEditor({
- extensions,
- content: parseMetabotMessageToTiptapDoc(value),
- autofocus: autoFocus,
- onUpdate: ({ editor }) => {
- const jsonContent = editor.getJSON();
- serializedRef.current = serializeTiptapToMetabotMessage(jsonContent);
- onChange(serializedRef.current);
- },
- editorProps: {
- handleDOMEvents: {
- copy: (view: EditorView, e: ClipboardEvent) => {
- e.preventDefault();
- const { from, to } = view.state.selection;
- const slice = view.state.doc.slice(from, to);
- const doc = view.state.schema.topNodeType.create(
- null,
- slice.content,
- );
- const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
- e.clipboardData?.setData("text/plain", serialized);
- return true;
- },
- cut: (view: EditorView, e: ClipboardEvent) => {
- e.preventDefault();
- const { from, to } = view.state.selection;
- const slice = view.state.doc.slice(from, to);
- const doc = view.state.schema.topNodeType.create(
- null,
- slice.content,
- );
- const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
- e.clipboardData?.setData("text/plain", serialized);
-
- // Delete the selected text and position cursor at cut location
- const tr = view.state.tr.deleteRange(from, to);
- tr.setSelection(TextSelection.create(tr.doc, from));
- view.dispatch(tr);
-
- return true;
- },
- },
- handleKeyDown: (view, event) => {
- if (event.key === "Enter") {
- // Defer enter handling to mention UI if open
- const mentionState = MetabotMentionPluginKey.getState(view.state);
- if (mentionState?.active) {
- return false; // Let the suggestion system handle it
- }
-
- // Check for any modifier keys (shift, ctrl, meta, alt)
- const isModifiedKeyPress =
- event.shiftKey || event.ctrlKey || event.metaKey || event.altKey;
+ MetabotPromptInput,
+ type MetabotPromptInputProps,
+} from "../../MetabotPromptInput";
- if (!isModifiedKeyPress) {
- event.preventDefault();
- onSubmit();
- return true;
- }
- }
-
- if (event.key === "Escape") {
- event.preventDefault();
- onStop();
- return true;
- }
-
- return false;
- },
- clipboardTextSerializer: (content) => {
- return serializeTiptapToMetabotMessage(content.toJSON());
- },
- },
- });
-
- useImperativeHandle(ref, () => {
- if (!editor) {
- return null;
- }
-
- return Object.assign(editor, {
- focus: () => editor.commands.focus("end"),
- get scrollHeight() {
- return editor.view.dom.scrollHeight;
- },
- get scrollTop() {
- return editor.view.dom.scrollTop;
- },
- });
- }, [editor]);
-
- // Sync external value changes to editor
- useEffect(() => {
- if (value !== serializedRef.current) {
- editor?.commands.setContent(parseMetabotMessageToTiptapDoc(value));
- }
- }, [editor, value]);
-
- if (!editor) {
- return null;
- }
+import S from "./MetabotChatEditor.module.css";
- return (
- <Box className={S.editorContainer}>
- <Box className={S.iconContainer}>
- <Icon name="metabot" c="brand" />
- </Box>
- <Box className={S.contentWrapper}>
- <EditorContent
- data-testid="metabot-chat-input"
- editor={editor}
- className={cx(S.content, {
- [S.disabled]: isResponding,
- })}
- />
- </Box>
- <UnstyledButton
- className={cx(
- S.button,
- isResponding && S.buttonResponding,
- value.length === 0 && !isResponding && S.buttonHidden,
- )}
- onClick={isResponding ? onStop : onSubmit}
- data-testid={
- isResponding ? "metabot-stop-response" : "metabot-send-message"
- }
- >
- {isResponding ? (
- <Icon className={S.stopIcon} name="stop" />
- ) : (
- <Icon className={S.sendIcon} name="arrow_up" />
- )}
- </UnstyledButton>
+type MetabotChatEditorProps = Pick<
+ MetabotPromptInputProps,
+ | "value"
+ | "placeholder"
+ | "autoFocus"
+ | "onChange"
+ | "onSubmit"
+ | "onStop"
+ | "suggestionConfig"
+> & { isResponding?: boolean };
+
+export const MetabotChatEditor = forwardRef<
+ MetabotPromptInputRef | null,
+ MetabotChatEditorProps
+>(({ isResponding = false, ...props }, ref) => {
+ return (
+ <Box className={S.editorContainer}>
+ <Box className={S.iconContainer}>
+ <Icon name="metabot" c="brand" />
+ </Box>
+ <Box className={S.contentWrapper}>
+ <MetabotPromptInput
+ {...props}
+ ref={ref}
+ disabled={isResponding}
+ data-testid="metabot-chat-input"
+ />
</Box>
- );
- },
-);
+ <UnstyledButton
+ className={cx(
+ S.button,
+ isResponding && S.buttonResponding,
+ props.value.length === 0 && !isResponding && S.buttonHidden,
+ )}
+ onClick={isResponding ? props.onStop : props.onSubmit}
+ data-testid={
+ isResponding ? "metabot-stop-response" : "metabot-send-message"
+ }
+ >
+ {isResponding ? (
+ <Icon className={S.stopIcon} name="stop" />
+ ) : (
+ <Icon className={S.sendIcon} name="arrow_up" />
+ )}
+ </UnstyledButton>
+ </Box>
+ );
+});
// @ts-expect-error - must set a displayName
MetabotChatEditor.displayName = "MetabotChatEditor";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.unit.spec.tsx
index 6be1ef34a87..1c2b5e7abb0 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.unit.spec.tsx
@@ -22,13 +22,15 @@ const defaultProps = {
onChange: jest.fn(),
onSubmit: jest.fn(),
onStop: jest.fn(),
- suggestionModels: [
- "table",
- "database",
- "card",
- "dashboard",
- "collection",
- ] as SuggestionModel[],
+ suggestionConfig: {
+ suggestionModels: [
+ "table",
+ "database",
+ "card",
+ "dashboard",
+ "collection",
+ ] as SuggestionModel[],
+ },
};
const setup = (props = {}) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.css b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.css
new file mode 100644
index 00000000000..5a38282384e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.module.css
@@ -0,0 +1,26 @@
+.widget {
+ padding: 4px 0;
+}
+
+.container {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ padding: 0.5rem;
+ margin-bottom: 0.125rem;
+ background: var(--mb-color-bg-white);
+ border: 1px solid var(--mb-color-border);
+ border-radius: 0.5rem;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
+}
+
+.inputContainer {
+ min-height: 1.5rem;
+}
+
+.inputContainer :global(.ProseMirror) {
+ font-family: var(--mb-default-font-family), sans-serif;
+ font-size: 0.75rem;
+ min-height: 1.25rem;
+ padding: 0.25rem 0.125rem;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx
new file mode 100644
index 00000000000..fc97ef7f285
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx
@@ -0,0 +1,133 @@
+import { isFulfilled, isRejected } from "@reduxjs/toolkit";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { tinykeys } from "tinykeys";
+import { t } from "ttag";
+
+import type { MetabotPromptInputRef } from "metabase/metabot";
+import { Box, Button, Flex, Icon, Loader } from "metabase/ui";
+import { METABOT_PROFILE_OVERRIDES } from "metabase-enterprise/metabot/constants";
+import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
+import type { DatabaseId } from "metabase-types/api";
+
+import { MetabotPromptInput } from "../MetabotPromptInput";
+
+import S from "./MetabotInlineSQLPrompt.module.css";
+import { responseHasCodeEdit } from "./utils";
+
+interface MetabotInlineSQLPromptProps {
+ databaseId: DatabaseId | null;
+ onClose: () => void;
+}
+
+export const MetabotInlineSQLPrompt = ({
+ databaseId,
+ onClose,
+}: MetabotInlineSQLPromptProps) => {
+ const inputRef = useRef<MetabotPromptInputRef>(null);
+ const [value, setValue] = useState("");
+ const [hasError, setHasError] = useState(false);
+ const { isDoingScience, submitInput, cancelRequest } = useMetabotAgent("sql");
+
+ const disabled = !value.trim() || isDoingScience;
+
+ const handleSubmit = useCallback(async () => {
+ const value = inputRef.current?.getValue?.().trim() ?? "";
+ setHasError(false);
+ const action = await submitInput(value, {
+ profile: METABOT_PROFILE_OVERRIDES.SQL,
+ preventOpenSidebar: true,
+ });
+ if (
+ isRejected(action) ||
+ (isFulfilled(action) && !action.payload?.success) ||
+ !responseHasCodeEdit(action)
+ ) {
+ setHasError(true);
+ }
+ }, [submitInput]);
+
+ const handleClose = useCallback(() => {
+ cancelRequest();
+ onClose();
+ }, [cancelRequest, onClose]);
+
+ useEffect(() => {
+ return tinykeys(
+ window,
+ {
+ "$mod+Enter": (e) => {
+ if (!disabled) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ },
+ "$mod+;": (e) => {
+ e.preventDefault();
+ handleClose();
+ },
+ },
+ { capture: true },
+ );
+ }, [disabled, handleSubmit, handleClose]);
+
+ return (
+ <Box className={S.container} data-testid="metabot-inline-sql-prompt">
+ <Box className={S.inputContainer}>
+ <MetabotPromptInput
+ ref={inputRef}
+ value={value}
+ placeholder={t`Describe what SQL you want...`}
+ autoFocus
+ disabled={isDoingScience}
+ onChange={setValue}
+ onStop={handleClose}
+ suggestionConfig={{
+ suggestionModels: [
+ "dataset",
+ "metric",
+ "card",
+ "table",
+ "database",
+ ],
+ searchOptions: databaseId ? { table_db_id: databaseId } : undefined,
+ }}
+ />
+ </Box>
+ <Flex justify="flex-start" align="center" gap="xs" mt="xs">
+ <Button
+ data-testid="metabot-inline-sql-generate"
+ size="xs"
+ px="sm"
+ variant="filled"
+ onClick={handleSubmit}
+ disabled={disabled}
+ leftSection={
+ isDoingScience ? (
+ <Loader size="xs" color="text-light" />
+ ) : (
+ <Icon name="insight" />
+ )
+ }
+ >
+ {isDoingScience ? t`Generating...` : t`Generate`}
+ </Button>
+ <Button
+ data-testid="metabot-inline-sql-cancel"
+ size="xs"
+ variant="subtle"
+ onClick={handleClose}
+ >
+ {t`Cancel`}
+ </Button>
+ {hasError && (
+ <Box
+ data-testid="metabot-inline-sql-error"
+ fz="sm"
+ c="error"
+ ml="sm"
+ >{t`Something went wrong. Please try again.`}</Box>
+ )}
+ </Flex>
+ </Box>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPromptWidget.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPromptWidget.tsx
new file mode 100644
index 00000000000..b0065731af3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPromptWidget.tsx
@@ -0,0 +1,98 @@
+import { StateEffect, StateField } from "@codemirror/state";
+import {
+ Decoration,
+ type DecorationSet,
+ EditorView,
+ WidgetType,
+} from "@codemirror/view";
+
+import S from "./MetabotInlineSQLPrompt.module.css";
+
+export type PortalTarget = {
+ container: HTMLElement;
+ view: EditorView;
+};
+
+type TogglePromptPayload = {
+ view: EditorView;
+};
+
+export const toggleEffect = StateEffect.define<TogglePromptPayload>();
+export const hideEffect = StateEffect.define<void>();
+
+export class MetabotInlinePromptWidget extends WidgetType {
+ constructor(
+ private readonly onMount: (target: PortalTarget) => void,
+ private readonly onUnmount: () => void,
+ private readonly view: EditorView,
+ ) {
+ super();
+ }
+
+ toDOM() {
+ const container = document.createElement("div");
+ container.className = S.widget;
+ this.onMount({ container, view: this.view });
+ return container;
+ }
+
+ destroy() {
+ this.onUnmount();
+ }
+
+ eq() {
+ return false;
+ }
+
+ ignoreEvent() {
+ return true;
+ }
+}
+
+export function createPromptInputExtension(
+ setPortalTarget: (target: PortalTarget | null) => void,
+) {
+ return StateField.define<{
+ decorations: DecorationSet;
+ visible: boolean;
+ }>({
+ create() {
+ return { decorations: Decoration.none, visible: false };
+ },
+
+ update(state, transaction) {
+ for (const effect of transaction.effects) {
+ if (
+ (effect.is(toggleEffect) && state.visible) ||
+ effect.is(hideEffect)
+ ) {
+ return { decorations: Decoration.none, visible: false };
+ }
+
+ if (effect.is(toggleEffect)) {
+ const handleMount = setPortalTarget;
+ const handleUnmount = () => setPortalTarget(null);
+ const decoration = Decoration.widget({
+ widget: new MetabotInlinePromptWidget(
+ handleMount,
+ handleUnmount,
+ effect.value.view,
+ ),
+ block: true,
+ side: -1,
+ });
+
+ const cursorPos = transaction.state.selection.main.head;
+ const line = transaction.state.doc.lineAt(cursorPos);
+ return {
+ decorations: Decoration.set([decoration.range(line.from)]),
+ visible: true,
+ };
+ }
+ }
+ return state;
+ },
+
+ provide: (f) => EditorView.decorations.from(f, (s) => s.decorations),
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/index.tsx
new file mode 100644
index 00000000000..b880c1b0e34
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/index.tsx
@@ -0,0 +1,2 @@
+export * from "./MetabotInlineSQLPrompt";
+export * from "./useInlineSQLPrompt";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
new file mode 100644
index 00000000000..7708fed6375
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
@@ -0,0 +1,210 @@
+import type { EditorView } from "@codemirror/view";
+import { EditorView as EV, keymap } from "@codemirror/view";
+import type { Extension } from "@uiw/react-codemirror";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { createPortal } from "react-dom";
+
+import { useRegisterMetabotContextProvider } from "metabase/metabot/context";
+import {
+ useMetabotDispatch,
+ useMetabotSelector,
+} from "metabase-enterprise/metabot/hooks/use-metabot-store";
+import {
+ addDeveloperMessage,
+ getMetabotSuggestedCodeEdit,
+ removeSuggestedCodeEdit,
+ resetConversation,
+} from "metabase-enterprise/metabot/state";
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+import type { DatabaseId, DatasetQuery } from "metabase-types/api";
+
+import { MetabotInlineSQLPrompt } from "./MetabotInlineSQLPrompt";
+import {
+ type PortalTarget,
+ createPromptInputExtension,
+ hideEffect,
+ toggleEffect,
+} from "./MetabotInlineSQLPromptWidget";
+import { extractMetabotBufferContext } from "./utils";
+
+function useRegisterCodeEditorMetabotContext(
+ buffer: EditorView | undefined,
+ databaseId: DatabaseId | null,
+ bufferId: string,
+): void {
+ useRegisterMetabotContextProvider(
+ async () =>
+ buffer
+ ? {
+ user_is_viewing: [
+ {
+ type: "code_editor",
+ buffers: [
+ extractMetabotBufferContext(buffer, databaseId, bufferId),
+ ],
+ },
+ ],
+ }
+ : {},
+ [buffer],
+ );
+}
+
+export interface UseInlineSqlEditResult {
+ portalElement: React.ReactPortal | null;
+ extensions: Extension[];
+ proposedQuestion: Question | undefined;
+ handleAcceptProposed?: (datasetQuery: DatasetQuery) => void;
+ handleRejectProposed?: () => void;
+}
+
+export function useInlineSQLPrompt(
+ question: Question,
+ bufferId: string,
+): UseInlineSqlEditResult {
+ const [portalTarget, setPortalTarget] = useState<PortalTarget | null>(null);
+
+ useRegisterCodeEditorMetabotContext(
+ portalTarget?.view,
+ question.databaseId(),
+ bufferId,
+ );
+
+ const dispatch = useMetabotDispatch();
+ const generatedSql = useMetabotSelector((state) =>
+ getMetabotSuggestedCodeEdit(state, bufferId),
+ )?.value;
+
+ const hideInput = useCallback(() => {
+ portalTarget?.view.dispatch({ effects: hideEffect.of() });
+ portalTarget?.view.focus();
+ }, [portalTarget?.view]);
+
+ const hideInputRef = useRef(hideInput);
+ useLayoutEffect(() => {
+ hideInputRef.current = hideInput;
+ });
+
+ useEffect(
+ function autoCloseOnResult() {
+ if (generatedSql) {
+ hideInput();
+ }
+ },
+ [generatedSql, hideInput],
+ );
+
+ const generatedSqlRef = useRef(generatedSql);
+ generatedSqlRef.current = generatedSql;
+
+ const clearSuggestion = useCallback(() => {
+ dispatch(removeSuggestedCodeEdit(bufferId));
+ }, [dispatch, bufferId]);
+
+ const clearSuggestionRef = useRef(clearSuggestion);
+ useEffect(() => {
+ clearSuggestionRef.current = clearSuggestion;
+ }, [clearSuggestion]);
+
+ const databaseId = question.databaseId();
+ useEffect(
+ function resetOnDbChangeAndUnmount() {
+ return () => {
+ hideInputRef.current();
+ dispatch(removeSuggestedCodeEdit(bufferId));
+ dispatch(resetConversation({ agentId: "sql" }));
+ };
+ },
+ [dispatch, databaseId, bufferId],
+ );
+
+ const resetInput = useCallback(() => {
+ dispatch(removeSuggestedCodeEdit(bufferId));
+ hideInput();
+ }, [dispatch, hideInput, bufferId]);
+
+ // NOTE: ref is needed for the extension to not be recalculated in the useMemo
+ // below, while still being able to reset the suggestion state on close
+ const resetInputRef = useRef(resetInput);
+ useEffect(() => {
+ resetInputRef.current = resetInput;
+ }, [resetInput]);
+
+ const proposedQuestion = useMemo(
+ () =>
+ generatedSql
+ ? question.setQuery(Lib.withNativeQuery(question.query(), generatedSql))
+ : undefined,
+ [generatedSql, question],
+ );
+
+ const handleRejectProposed = generatedSql
+ ? () => {
+ resetInput();
+ dispatch(
+ addDeveloperMessage({
+ agentId: "sql",
+ message: `User rejected the following suggestion:\n\n${generatedSql}`,
+ }),
+ );
+ }
+ : undefined;
+
+ const handleAcceptProposed = generatedSql ? resetInput : undefined;
+
+ const extensions = useMemo(
+ () => [
+ createPromptInputExtension(setPortalTarget),
+ keymap.of([
+ {
+ key: "Mod-;",
+ run: (view) => {
+ 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();
+ }
+ }),
+ ],
+ [],
+ );
+
+ return {
+ extensions,
+ portalElement: portalTarget
+ ? createPortal(
+ <MetabotInlineSQLPrompt
+ databaseId={databaseId}
+ onClose={hideInput}
+ />,
+ portalTarget.container,
+ )
+ : null,
+ proposedQuestion,
+ handleRejectProposed,
+ handleAcceptProposed,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/utils.ts b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/utils.ts
new file mode 100644
index 00000000000..c9c77e88e3e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotInlineSQLPrompt/utils.ts
@@ -0,0 +1,66 @@
+import type { EditorView } from "@codemirror/view";
+import { isFulfilled } from "@reduxjs/toolkit";
+
+import type { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
+import type {
+ DatabaseId,
+ MetabotCodeEditorBufferContext,
+} from "metabase-types/api";
+
+type SubmitInputResult = Awaited<
+ ReturnType<ReturnType<typeof useMetabotAgent>["submitInput"]>
+>;
+
+export const responseHasCodeEdit = (action: SubmitInputResult) => {
+ return (
+ isFulfilled(action) &&
+ action.payload.data?.processedResponse.data.some(
+ (dp) =>
+ typeof dp === "object" &&
+ dp !== null &&
+ "type" in dp &&
+ (dp as { type: string }).type === "code_edit",
+ )
+ );
+};
+
+export function extractMetabotBufferContext(
+ view: EditorView,
+ databaseId: DatabaseId | null,
+ bufferId: string,
+): MetabotCodeEditorBufferContext {
+ const state = view.state;
+ const selection = state.selection.main;
+ const cursorLine = state.doc.lineAt(selection.head);
+
+ const buffer: MetabotCodeEditorBufferContext = {
+ id: bufferId,
+ source: {
+ language: "sql",
+ databaseId,
+ },
+ cursor: {
+ line: cursorLine.number,
+ column: cursorLine.from,
+ },
+ };
+
+ if (!selection.empty) {
+ const startLine = state.doc.lineAt(selection.from);
+ const endLine = state.doc.lineAt(selection.to);
+
+ buffer.selection = {
+ text: state.sliceDoc(selection.from, selection.to),
+ start: {
+ line: startLine.number,
+ column: selection.from - startLine.from,
+ },
+ end: {
+ line: endLine.number,
+ column: selection.to - endLine.from,
+ },
+ };
+ }
+
+ return buffer;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/MetabotPromptInput.module.css b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/MetabotPromptInput.module.css
new file mode 100644
index 00000000000..ca66bcc6d89
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/MetabotPromptInput.module.css
@@ -0,0 +1,49 @@
+.content :global(.ProseMirror) {
+ border: none;
+ border-radius: 0;
+ background: transparent;
+ outline: none;
+ width: 100%;
+ padding: 0.5rem 0;
+ line-height: 1.7;
+ color: var(--mb-color-text-dark);
+ font-size: var(--mantine-font-size-md);
+ min-height: 1.7em;
+ white-space: pre-wrap;
+ word-break: break-word;
+
+ &:focus {
+ outline: none;
+ }
+}
+
+.content :global(.ProseMirror p) {
+ margin: 0;
+}
+
+.content :global(.is-empty:first-child:before) {
+ color: var(--mb-color-text-light);
+ content: attr(data-placeholder);
+ height: 0;
+ pointer-events: none;
+ position: absolute;
+}
+
+.content.disabled :global(.ProseMirror) {
+ opacity: 1;
+ background: transparent;
+ cursor: not-allowed;
+}
+
+.smartLink {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25rem;
+ padding: 0 0.25rem;
+ background: var(--mb-color-background-hover);
+ border-radius: 0.25rem;
+ color: var(--mb-color-brand);
+ text-decoration: none;
+ font-weight: 500;
+ vertical-align: baseline;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx
new file mode 100644
index 00000000000..3162b9921c9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx
@@ -0,0 +1,207 @@
+import Document from "@tiptap/extension-document";
+import HardBreak from "@tiptap/extension-hard-break";
+import Paragraph from "@tiptap/extension-paragraph";
+import { Placeholder } from "@tiptap/extension-placeholder";
+import Text from "@tiptap/extension-text";
+import { TextSelection } from "@tiptap/pm/state";
+import type { EditorView } from "@tiptap/pm/view";
+import { EditorContent, useEditor } from "@tiptap/react";
+import cx from "classnames";
+import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
+import { t } from "ttag";
+
+import { useSelector } from "metabase/lib/redux";
+import type { MetabotPromptInputRef } from "metabase/metabot";
+import { createMentionSuggestion } from "metabase/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion";
+import {
+ MetabotMentionExtension,
+ MetabotMentionPluginKey,
+} from "metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotMentionExtension";
+import { SmartLink } from "metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode";
+import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";
+import type { EntitySearchOptions } from "metabase/rich_text_editing/tiptap/extensions/shared/useEntitySearch";
+import { createSuggestionRenderer } from "metabase/rich_text_editing/tiptap/extensions/suggestionRenderer";
+import { getSetting } from "metabase/selectors/settings";
+
+import S from "./MetabotPromptInput.module.css";
+import {
+ parseMetabotMessageToTiptapDoc,
+ serializeTiptapToMetabotMessage,
+} from "./utils";
+
+export interface MetabotPromptInputProps {
+ value: string;
+ placeholder?: string;
+ autoFocus?: boolean;
+ disabled: boolean;
+ onChange: (value: string) => void;
+ onSubmit?: () => void;
+ onStop: () => void;
+ suggestionConfig: {
+ suggestionModels: SuggestionModel[];
+ searchOptions?: EntitySearchOptions;
+ };
+}
+export const MetabotPromptInput = forwardRef<
+ MetabotPromptInputRef | null,
+ MetabotPromptInputProps
+>(
+ (
+ {
+ value,
+ placeholder = t`Tell me to do something, or ask a question`,
+ autoFocus,
+ disabled,
+ suggestionConfig,
+ onChange,
+ onSubmit,
+ onStop,
+ ...props
+ },
+ ref,
+ ) => {
+ const siteUrl = useSelector((state) => getSetting(state, "site-url"));
+ const serializedRef = useRef(value);
+
+ const extensions = [
+ Document,
+ Paragraph,
+ Text,
+ Placeholder.configure({ placeholder }),
+ HardBreak,
+ SmartLink.configure({
+ HTMLAttributes: { class: S.smartLink },
+ siteUrl,
+ }),
+ MetabotMentionExtension.configure({
+ suggestion: {
+ render: createSuggestionRenderer(
+ createMentionSuggestion({
+ searchModels: suggestionConfig.suggestionModels,
+ searchOptions: suggestionConfig.searchOptions,
+ canFilterSearchModels: true,
+ canBrowseAll: false,
+ }),
+ ),
+ },
+ }),
+ ];
+
+ const editor = useEditor({
+ extensions,
+ content: parseMetabotMessageToTiptapDoc(value),
+ autofocus: autoFocus,
+ onUpdate: ({ editor }) => {
+ const jsonContent = editor.getJSON();
+ serializedRef.current = serializeTiptapToMetabotMessage(jsonContent);
+ onChange(serializedRef.current);
+ },
+ editorProps: {
+ handleDOMEvents: {
+ copy: (view: EditorView, e: ClipboardEvent) => {
+ e.preventDefault();
+ const { from, to } = view.state.selection;
+ const slice = view.state.doc.slice(from, to);
+ const doc = view.state.schema.topNodeType.create(
+ null,
+ slice.content,
+ );
+ const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
+ e.clipboardData?.setData("text/plain", serialized);
+ return true;
+ },
+ cut: (view: EditorView, e: ClipboardEvent) => {
+ e.preventDefault();
+ const { from, to } = view.state.selection;
+ const slice = view.state.doc.slice(from, to);
+ const doc = view.state.schema.topNodeType.create(
+ null,
+ slice.content,
+ );
+ const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
+ e.clipboardData?.setData("text/plain", serialized);
+
+ // Delete the selected text and position cursor at cut location
+ const tr = view.state.tr.deleteRange(from, to);
+ tr.setSelection(TextSelection.create(tr.doc, from));
+ view.dispatch(tr);
+
+ return true;
+ },
+ },
+ handleKeyDown: (view, event) => {
+ if (event.key === "Enter") {
+ // Defer enter handling to mention UI if open
+ const mentionState = MetabotMentionPluginKey.getState(view.state);
+ if (mentionState?.active) {
+ return false; // Let the suggestion system handle it
+ }
+
+ // Check for any modifier keys (shift, ctrl, meta, alt)
+ const isModifiedKeyPress =
+ event.shiftKey || event.ctrlKey || event.metaKey || event.altKey;
+
+ if (!isModifiedKeyPress && onSubmit) {
+ event.preventDefault();
+ onSubmit();
+ return true;
+ }
+ }
+
+ if (event.key === "Escape") {
+ event.preventDefault();
+ onStop();
+ return true;
+ }
+
+ return false;
+ },
+ clipboardTextSerializer: (content) => {
+ return serializeTiptapToMetabotMessage(content.toJSON());
+ },
+ },
+ });
+
+ useImperativeHandle(ref, () => {
+ if (!editor) {
+ return null;
+ }
+
+ return Object.assign(editor, {
+ focus: () => editor.commands.focus("end"),
+ clear: () => editor.commands.clearContent(),
+ getValue: () => serializeTiptapToMetabotMessage(editor.getJSON()),
+ get scrollHeight() {
+ return editor.view.dom.scrollHeight;
+ },
+ get scrollTop() {
+ return editor.view.dom.scrollTop;
+ },
+ });
+ }, [editor]);
+
+ // Sync external value changes to editor
+ useEffect(() => {
+ if (value !== serializedRef.current) {
+ editor?.commands.setContent(parseMetabotMessageToTiptapDoc(value));
+ }
+ }, [editor, value]);
+
+ if (!editor) {
+ return null;
+ }
+
+ return (
+ <EditorContent
+ {...props}
+ editor={editor}
+ className={cx(S.content, {
+ [S.disabled]: disabled,
+ })}
+ />
+ );
+ },
+);
+
+// @ts-expect-error - must set a displayName
+MetabotPromptInput.displayName = "MetabotPromptInput";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/index.tsx
new file mode 100644
index 00000000000..2274100d704
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/index.tsx
@@ -0,0 +1 @@
+export * from "./MetabotPromptInput";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/utils.ts b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/utils.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/utils.ts
rename to enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/utils.ts
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/utils.unit.spec.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotChat/MetabotChatEditor/utils.unit.spec.ts
rename to enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotPromptInput/utils.unit.spec.ts
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx
deleted file mode 100644
index cc5258c9603..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotToggleButton.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { t } from "ttag";
-
-import { Button, Icon, Tooltip } from "metabase/ui";
-import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
-
-import { trackMetabotChatOpened } from "../analytics";
-
-interface MetabotToggleButtonProps {
- className?: string;
-}
-
-export function MetabotToggleButton({ className }: MetabotToggleButtonProps) {
- const metabot = useMetabotAgent("omnibot");
-
- const handleClick = () => {
- if (!metabot.visible) {
- trackMetabotChatOpened("native_editor");
- }
-
- metabot.setVisible(!metabot.visible);
- };
-
- const label = metabot.visible ? t`Close Metabot chat` : t`Open Metabot chat`;
-
- return (
- <Tooltip label={label}>
- <Button
- className={className}
- variant="subtle"
- p={0}
- h="fit-content"
- bd="none"
- leftSection={<Icon name="metabot" />}
- aria-label={label}
- onClick={handleClick}
- />
- </Tooltip>
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts b/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts
index ddaea93bff0..b79844e2072 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts
@@ -17,6 +17,11 @@ export const FIXED_METABOT_ENTITY_IDS = {
EMBEDDED: "embeddedmetabotmetabo" as const,
};
+export const METABOT_PROFILE_OVERRIDES = {
+ DEFAULT: undefined,
+ SQL: "sql",
+};
+
export const METABOT_ERR_MSG = {
get default() {
return t`Sorry, I ran into an error. Could you please try that again?`;
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx
index ffc4bdbac36..40c81c60a59 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx
@@ -6,14 +6,15 @@ import _ from "underscore";
import { useStore } from "metabase/lib/redux";
import type {
ChatContextProviderFn,
- MetabotChatInputRef,
MetabotContext as MetabotCtx,
+ MetabotPromptInputRef,
} from "metabase/metabot";
import {
canUserCreateNativeQueries,
canUserCreateQueries,
getUserIsAdmin,
} from "metabase/selectors/user";
+import type { MetabotChatContext } from "metabase-types/api";
export const defaultContext = {
prompt: "",
@@ -24,13 +25,25 @@ export const defaultContext = {
Promise.resolve({
user_is_viewing: [],
current_time_with_timezone: dayjs.tz(dayjs()).format(),
+ capabilities: [],
}),
registerChatContextProvider: () => () => {},
};
-export const MetabotContext = createContext<MetabotCtx>(defaultContext);
+const mergeCtx = (
+ ctx: MetabotChatContext,
+ partialCtx: Partial<MetabotChatContext>,
+): MetabotChatContext => {
+ return {
+ ...ctx,
+ ...partialCtx,
+ user_is_viewing: partialCtx.user_is_viewing
+ ? [...ctx.user_is_viewing, ...partialCtx.user_is_viewing]
+ : ctx.user_is_viewing,
+ };
+};
-export type MetabotPromptInputRef = { focus: () => void };
+export const MetabotContext = createContext<MetabotCtx>(defaultContext);
export const MetabotProvider = ({
children,
@@ -39,7 +52,7 @@ export const MetabotProvider = ({
}) => {
/* Metabot input */
const [prompt, setPrompt] = useState("");
- const promptInputRef = useRef<MetabotChatInputRef>(null);
+ const promptInputRef = useRef<MetabotPromptInputRef>(null);
/* Metabot context */
const providerFnsRef = useRef<Set<ChatContextProviderFn>>(new Set());
@@ -53,7 +66,7 @@ export const MetabotProvider = ({
const hasDataAccess = canUserCreateQueries(state);
const hasNativeWrite = canUserCreateNativeQueries(state);
- const ctx = {
+ let ctx: MetabotChatContext = {
user_is_viewing: [],
current_time_with_timezone: dayjs.tz(dayjs()).format(),
capabilities: _.compact([
@@ -61,13 +74,15 @@ export const MetabotProvider = ({
hasDataAccess && "permission:save_questions",
hasNativeWrite && "permission:write_sql_queries",
isAdmin && "permission:write_transforms",
- ]),
+ ]) as string[],
};
for (const providerFn of providerFns) {
try {
const partialCtx = await providerFn(state);
- return Object.assign(ctx, partialCtx);
+ if (partialCtx) {
+ ctx = mergeCtx(ctx, partialCtx);
+ }
} catch (err) {
console.error("A metabot chat context provider failed:", err);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
index f2f20f156ac..09d931e8d0c 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
@@ -15,8 +15,8 @@ import { MetabotTrialPage } from "./components/MetabotAdmin/MetabotTrialPage";
import { MetabotAppBarButton } from "./components/MetabotAppBarButton";
import MetabotThinkingStyles from "./components/MetabotChat/MetabotThinking.module.css";
import { MetabotDataStudioButton } from "./components/MetabotDataStudioButton";
+import { useInlineSQLPrompt } from "./components/MetabotInlineSQLPrompt";
import { getMetabotQuickLinks } from "./components/MetabotQuickLinks";
-import { MetabotToggleButton } from "./components/MetabotToggleButton";
import { MetabotContext, MetabotProvider, defaultContext } from "./context";
import { getMetabotVisible, metabotReducer } from "./state";
@@ -63,7 +63,6 @@ export function initializePlugin() {
PLUGIN_METABOT.getMetabotVisible =
getMetabotVisible as unknown as typeof PLUGIN_METABOT.getMetabotVisible;
- PLUGIN_METABOT.MetabotToggleButton = MetabotToggleButton;
PLUGIN_METABOT.MetabotAppBarButton = MetabotAppBarButton;
PLUGIN_METABOT.MetabotDataStudioButton = MetabotDataStudioButton;
PLUGIN_METABOT.MetabotDataStudioSidebar = MetabotDataStudioSidebar;
@@ -104,4 +103,5 @@ export function initializePlugin() {
useLazyMetabotGenerateContentQuery;
PLUGIN_METABOT.MetabotThinkingStyles = MetabotThinkingStyles;
}
+ PLUGIN_METABOT.useInlineSQLPrompt = useInlineSQLPrompt;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
index c785c083dfc..0fe1310d201 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
@@ -16,6 +16,7 @@ import {
aiStreamingQuery,
findMatchingInflightAiStreamingRequests,
} from "metabase-enterprise/api/ai-streaming";
+import type { ProcessedChatResponse } from "metabase-enterprise/api/ai-streaming/process-stream";
import type {
MetabotAgentRequest,
MetabotAgentResponse,
@@ -31,6 +32,7 @@ import {
getAgentErrorMessages,
getAgentRequestMetadata,
getDebugMode,
+ getDeveloperMessage,
getHistory,
getIsProcessing,
getLastMessage,
@@ -59,12 +61,13 @@ export const {
addAgentTextDelta,
addAgentMessage,
addAgentErrorMessage,
+ addDeveloperMessage,
addUserMessage,
setIsProcessing,
setNavigateToPath,
+ setProfileOverride,
toolCallStart,
toolCallEnd,
- setProfileOverride,
setMetabotReqIdOverride,
setDebugMode,
addSuggestedTransform,
@@ -72,6 +75,8 @@ export const {
deactivateSuggestedTransform,
createAgent,
destroyAgent,
+ addSuggestedCodeEdit,
+ removeSuggestedCodeEdit,
} = metabot.actions;
type PromptErrorOutcome = {
@@ -159,9 +164,14 @@ export const executeSlashCommand = createAsyncThunk<
);
export type MetabotPromptSubmissionResult =
- | { prompt: string; success: true; shouldRetry?: void }
- | { prompt: string; success: false; shouldRetry: false }
- | { prompt: string; success: false; shouldRetry: true };
+ | {
+ prompt: string;
+ success: true;
+ shouldRetry?: void;
+ data?: SendAgentRequestResult;
+ }
+ | { prompt: string; success: false; shouldRetry: false; data?: void }
+ | { prompt: string; success: false; shouldRetry: true; data?: void };
export const submitInput = createAsyncThunk<
MetabotPromptSubmissionResult,
@@ -217,6 +227,7 @@ export const submitInput = createAsyncThunk<
// altering it by adding the current message the user is wanting to send
const agentMetadata = getAgentRequestMetadata(getState(), agentId);
const messageId = createMessageId();
+ const promptWithDevMessage = getDeveloperMessage(state, agentId) + prompt;
dispatch(
addUserMessage({
id: messageId,
@@ -229,7 +240,7 @@ export const submitInput = createAsyncThunk<
const sendMessageRequestPromise = dispatch(
sendAgentRequest({
...data,
- message: prompt,
+ message: promptWithDevMessage,
agentId,
conversation_id: convo.conversationId,
...agentMetadata,
@@ -241,18 +252,21 @@ export const submitInput = createAsyncThunk<
const result = await sendMessageRequestPromise;
- if (isRejected(result) && result.payload?.type === "error") {
- dispatch(
- stopProcessingAndNotify({
- agentId,
- message: result.payload?.errorMessage,
- }),
- );
- return {
- prompt,
- success: false,
- shouldRetry: result.payload?.shouldRetry ?? false,
- };
+ if (isRejected(result)) {
+ if (result.payload?.type === "error") {
+ dispatch(
+ stopProcessingAndNotify({
+ agentId,
+ message: result.payload?.errorMessage,
+ }),
+ );
+ }
+ const shouldRetry =
+ (result.payload &&
+ "shouldRetry" in result.payload &&
+ (result.payload?.shouldRetry ?? {})) ??
+ false;
+ return { prompt: rawPrompt, success: false, shouldRetry };
}
return { prompt, success: true, data: result.payload };
@@ -272,8 +286,12 @@ type SendAgentRequestError =
unresolved_tool_calls: { toolCallId: string; toolName: string }[];
} & MetabotAgentResponse);
+type SendAgentRequestResult = MetabotAgentResponse & {
+ processedResponse: ProcessedChatResponse;
+};
+
export const sendAgentRequest = createAsyncThunk<
- MetabotAgentResponse,
+ SendAgentRequestResult,
MetabotAgentRequest & { agentId: MetabotAgentId },
{ rejectValue: SendAgentRequestError }
>(
@@ -314,6 +332,9 @@ export const sendAgentRequest = createAsyncThunk<
dispatch(addAgentMessage({ ...message, agentId }));
})
+ .with({ type: "code_edit" }, (part) => {
+ dispatch(addSuggestedCodeEdit({ ...part.value, active: true }));
+ })
.with({ type: "navigate_to" }, (part) => {
dispatch(setNavigateToPath(part.value));
@@ -387,6 +408,7 @@ export const sendAgentRequest = createAsyncThunk<
conversation_id: request.conversation_id,
history: [...getHistory(getState(), agentId), ...response.history],
state,
+ processedResponse: response,
});
} catch (error) {
console.error(error);
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts
index ded5b9c3e5d..e7f8c01855e 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer-utils.ts
@@ -42,8 +42,8 @@ export const getRequestConversation = (
const agentOverridesByAgentId: Partial<
Record<MetabotAgentId, Partial<MetabotConverstationState>>
> = {
- inline_sql: {
- profileOverride: "inline_sql",
+ sql: {
+ profileOverride: "sql",
},
};
@@ -82,6 +82,9 @@ export const resetReactionState = (
state.reactions.navigateToPath = null;
state.reactions.suggestedTransforms = [];
})
+ .with("sql", () => {
+ state.reactions.suggestedCodeEdits = {};
+ })
.otherwise(() => {});
};
@@ -122,10 +125,11 @@ export const getMetabotInitialState = (): MetabotState => {
return {
conversations: {
omnibot: createConversation("omnibot"),
- inline_sql: createConversation("inline_sql"),
+ sql: createConversation("sql"),
},
reactions: {
navigateToPath: null,
+ suggestedCodeEdits: {},
// NOTE: suggestedTransforms should be folded into suggestedCodeEdits eventually
suggestedTransforms: [],
},
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
index b1cb316a1ce..ad1ee7b2ac1 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/reducer.ts
@@ -3,7 +3,7 @@ import { castDraft } from "immer";
import _ from "underscore";
import { logout } from "metabase/auth/actions";
-import type { SuggestedTransform } from "metabase-types/api";
+import type { MetabotCodeEdit, SuggestedTransform } from "metabase-types/api";
import { TOOL_CALL_MESSAGES } from "../constants";
@@ -53,6 +53,12 @@ export const metabot = createSlice({
setDebugMode: (state, action: PayloadAction<boolean>) => {
state.debugMode = action.payload;
},
+ // CONVERSATION REDUCERS
+ addDeveloperMessage: convoReducer(
+ (convo, action: ConvoPayloadAction<{ message: string }>) => {
+ convo.experimental.developerMessage = `HIDDEN DEVELOPER MESSAGE: ${action.payload.message}\n\n`;
+ },
+ ),
addUserMessage: convoReducer(
(
convo,
@@ -240,6 +246,18 @@ export const metabot = createSlice({
}
});
},
+ addSuggestedCodeEdit: (
+ state,
+ { payload: codeEdit }: PayloadAction<MetabotCodeEdit>,
+ ) => {
+ state.reactions.suggestedCodeEdits[codeEdit.bufferId] = codeEdit;
+ },
+ removeSuggestedCodeEdit: (
+ state,
+ action: PayloadAction<MetabotCodeEdit["bufferId"]>,
+ ) => {
+ delete state.reactions.suggestedCodeEdits[action.payload];
+ },
},
extraReducers: (builder) => {
builder
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
index 835da8d1bf7..3ecc280edab 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/selectors.ts
@@ -122,6 +122,11 @@ export const getMessages = createSelector(
},
);
+export const getDeveloperMessage = createSelector(
+ getMetabotConversation,
+ (convo) => convo.experimental.developerMessage,
+);
+
export const getActiveToolCalls = createSelector(
getMetabotConversation,
(convo) => convo.activeToolCalls,
@@ -216,3 +221,13 @@ export const getAgentRequestMetadata = createSelector(
...(profileOverride ? { profile_id: profileOverride } : {}),
}),
);
+
+export const getMetabotSuggestedCodeEdits = createSelector(
+ getMetabotReactionsState,
+ (reactionsState) => reactionsState.suggestedCodeEdits,
+);
+
+export const getMetabotSuggestedCodeEdit = createSelector(
+ [getMetabotSuggestedCodeEdits, (_, bufferId: string) => bufferId],
+ (suggestedCodeEdits, bufferId) => suggestedCodeEdits[bufferId],
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts
index 7fcb10f3697..94f25ee7184 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/types.ts
@@ -1,6 +1,7 @@
import type { EnterpriseSharedState } from "metabase-enterprise/shared/reducer";
import type { EnterpriseState } from "metabase-enterprise/shared/types";
import type {
+ MetabotCodeEdit,
MetabotHistory,
MetabotTodoItem,
MetabotTransformInfo,
@@ -94,6 +95,9 @@ export type MetabotSuggestedTransform = SuggestedTransform & {
export type MetabotReactionsState = {
navigateToPath: string | null;
+ suggestedCodeEdits: Partial<
+ Record<MetabotCodeEdit["bufferId"], MetabotCodeEdit>
+ >;
suggestedTransforms: MetabotSuggestedTransform[];
};
@@ -113,7 +117,7 @@ export interface MetabotConverstationState {
};
}
-export const fixedMetabotAgentIds = ["omnibot", "inline_sql"] as const;
+export const fixedMetabotAgentIds = ["omnibot", "sql"] as const;
type FixedMetabotAgentId = (typeof fixedMetabotAgentIds)[number];
export type MetabotAgentId = FixedMetabotAgentId | `test_${number}`;
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx
index d58898406b6..2acbd40ee84 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/tests/multi-convo.unit.spec.tsx
@@ -24,7 +24,7 @@ function setup(
agentIds: MetabotAgentId[];
} | void,
) {
- const { agentIds = ["omnibot", "inline_sql"] } = options || {};
+ const { agentIds = ["omnibot", "sql"] } = options || {};
const settings = mockSettings({
"token-features": createMockTokenFeatures({
@@ -68,6 +68,7 @@ const input: Input = {
context: {
user_is_viewing: [],
current_time_with_timezone: "",
+ capabilities: [],
},
};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts
index 7c054430cb3..ec72b0e5d1a 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/tests/reducer.unit.spec.ts
@@ -62,6 +62,7 @@ describe("metabot reducer", () => {
const store = createTestStore({
reactions: {
navigateToPath: null,
+ suggestedCodeEdits: {},
suggestedTransforms: [existingTransform],
},
});
@@ -108,6 +109,7 @@ describe("metabot reducer", () => {
const store = createTestStore({
reactions: {
navigateToPath: null,
+ suggestedCodeEdits: {},
suggestedTransforms: [transform1, transform2, transform3],
},
});
@@ -143,6 +145,7 @@ describe("metabot reducer", () => {
const store = createTestStore({
reactions: {
navigateToPath: null,
+ suggestedCodeEdits: {},
suggestedTransforms: [newTransform],
},
});
@@ -182,6 +185,7 @@ describe("metabot reducer", () => {
const store = createTestStore({
reactions: {
navigateToPath: null,
+ suggestedCodeEdits: {},
suggestedTransforms: [transform1, transform2, transform3],
},
});
@@ -214,6 +218,7 @@ describe("metabot reducer", () => {
const store = createTestStore({
reactions: {
navigateToPath: null,
+ suggestedCodeEdits: {},
suggestedTransforms: [newTransform],
},
});
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index 00de7c70814..7f3a9839c85 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -21,9 +21,34 @@ export type MetabotFeedbackType =
/* Metabot v3 - Base Types */
+export type MetabotCodeEditorBufferContext = {
+ id: string;
+ source: Record<string, unknown> & {
+ language: "sql";
+ databaseId: number | null;
+ };
+ cursor: { line: number; column: number };
+ selection?: {
+ text: string;
+ start: { line: number; column: number };
+ end: { line: number; column: number };
+ };
+};
+
+export type MetabotCodeEditorContext = {
+ type: "code_editor";
+ buffers: MetabotCodeEditorBufferContext[];
+};
+
+export type MetabotUserIsViewingContext = Array<
+ MetabotEntityInfo | MetabotCodeEditorContext
+>;
+
export type MetabotChatContext = {
- user_is_viewing: MetabotEntityInfo[];
+ user_is_viewing: MetabotUserIsViewingContext;
current_time_with_timezone: string;
+ capabilities: string[];
+ code_editor?: MetabotCodeEditorContext;
};
export type MetabotTool = {
@@ -136,6 +161,13 @@ export type MetabotEntityInfo =
| MetabotDocumentInfo
| MetabotTransformInfo;
+export type MetabotCodeEdit = {
+ bufferId: string;
+ mode: "rewrite";
+ value: string;
+ active?: boolean;
+};
+
/* Metabot v3 - API Request Types */
export type MetabotAgentRequest = {
diff --git a/frontend/src/metabase/metabot/context.ts b/frontend/src/metabase/metabot/context.ts
index ebd8c18a303..6ea29be9aee 100644
--- a/frontend/src/metabase/metabot/context.ts
+++ b/frontend/src/metabase/metabot/context.ts
@@ -11,8 +11,9 @@ export type ChatContextProviderFn = (
export type DeregisterChatContextProviderFn = () => void;
// internal type so we can support tiptap editor and textarea as inputs
-export type MetabotChatInputRef = {
+export type MetabotPromptInputRef = {
focus: () => void;
+ getValue?: () => string;
scrollHeight: number;
scrollTop: number;
};
@@ -20,7 +21,7 @@ export type MetabotChatInputRef = {
export interface MetabotContext {
prompt: string;
setPrompt: (prompt: string) => void;
- promptInputRef: RefObject<MetabotChatInputRef> | undefined;
+ promptInputRef: RefObject<MetabotPromptInputRef> | undefined;
getChatContext: () => Promise<MetabotChatContext>;
registerChatContextProvider: (
diff --git a/frontend/src/metabase/plugins/oss/ai.ts b/frontend/src/metabase/plugins/oss/ai.ts
index ffa8f57535d..a0e2b5c7ce6 100644
--- a/frontend/src/metabase/plugins/oss/ai.ts
+++ b/frontend/src/metabase/plugins/oss/ai.ts
@@ -1,5 +1,6 @@
import type { BaseQueryFn } from "@reduxjs/toolkit/query";
import type { TypedUseLazyQuery } from "@reduxjs/toolkit/src/query/react/buildHooks";
+import type { Extension } from "@uiw/react-codemirror";
import type { ComponentType } from "react";
import React from "react";
@@ -8,6 +9,7 @@ import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder
import type Question from "metabase-lib/v1/Question";
import type {
DashCardId,
+ DatasetQuery,
MetabotGenerateContentRequest,
MetabotGenerateContentResponse,
SearchModel,
@@ -71,6 +73,16 @@ type PluginMetabotType = {
MetabotAdminAppBarButton: ComponentType;
MetabotDataStudioButton: ComponentType;
MetabotDataStudioSidebar: ComponentType;
+ useInlineSQLPrompt: (
+ question: Question,
+ bufferId: string,
+ ) => {
+ portalElement: React.ReactPortal | null;
+ extensions: Extension[];
+ proposedQuestion: Question | undefined;
+ handleAcceptProposed?: (datasetQuery: DatasetQuery) => void;
+ handleRejectProposed?: () => void;
+ } | void;
useLazyMetabotGenerateContentQuery: TypedUseLazyQuery<
MetabotGenerateContentResponse,
MetabotGenerateContentRequest,
@@ -130,6 +142,7 @@ const getDefaultPluginMetabot = (): PluginMetabotType => ({
MetabotAdminAppBarButton: PluginPlaceholder,
MetabotDataStudioButton: PluginPlaceholder,
MetabotDataStudioSidebar: PluginPlaceholder,
+ useInlineSQLPrompt: () => {},
useLazyMetabotGenerateContentQuery:
(() => []) as unknown as PluginMetabotType["useLazyMetabotGenerateContentQuery"],
MetabotThinkingStyles: {},
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/CodeMirrorEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/CodeMirrorEditor.tsx
index 89e71065981..67c5d0a20a9 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/CodeMirrorEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/CodeMirrorEditor.tsx
@@ -1,3 +1,4 @@
+import type { Extension } from "@codemirror/state";
import type { ViewUpdate } from "@uiw/react-codemirror";
import {
forwardRef,
@@ -19,12 +20,21 @@ import type { CardId } from "metabase-types/api";
import type { SelectionRange } from "../types";
+import S from "./CodeMirrorEditor.module.css";
+import { useExtensions } from "./extensions";
+import {
+ getPlaceholderText,
+ getSelectedRanges,
+ matchCardIdAtCursor,
+} from "./util";
+
export type CodeMirrorEditorProps = {
query: Lib.Query;
proposedQuery?: Lib.Query;
highlightedLineNumbers?: number[];
placeholder?: string;
readOnly?: boolean;
+ extensions?: Extension[];
onChange?: (queryText: string) => void;
onFormatQuery?: () => void;
onRunQuery?: () => void;
@@ -38,14 +48,6 @@ export interface CodeMirrorEditorRef {
getSelectionTarget: () => Element | null;
}
-import S from "./CodeMirrorEditor.module.css";
-import { useExtensions } from "./extensions";
-import {
- getPlaceholderText,
- getSelectedRanges,
- matchCardIdAtCursor,
-} from "./util";
-
export const CodeMirrorEditor = forwardRef<
CodeMirrorEditorRef,
CodeMirrorEditorProps
@@ -56,6 +58,7 @@ export const CodeMirrorEditor = forwardRef<
highlightedLineNumbers,
placeholder = getPlaceholderText(Lib.engine(query)),
readOnly,
+ extensions: customExtensions,
onChange,
onRunQuery,
onSelectionChange,
@@ -66,12 +69,19 @@ export const CodeMirrorEditor = forwardRef<
ref,
) {
const editorRef = useRef<CodeMirrorRef>(null);
- const extensions = useExtensions({
+ const baseExtensions = useExtensions({
query,
diff: !!proposedQuery,
onRunQuery,
});
+ const extensions = useMemo(() => {
+ if (customExtensions?.length) {
+ return [...baseExtensions, ...customExtensions];
+ }
+ return baseExtensions;
+ }, [baseExtensions, customExtensions]);
+
useImperativeHandle(ref, () => {
return {
focus() {
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.tsx
index d20468d02e0..188cc8e89b5 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.tsx
@@ -3,6 +3,7 @@ import { createSelector } from "@reduxjs/toolkit";
import { shallowEqual } from "react-redux";
import { t } from "ttag";
+import { METAKEY } from "metabase/lib/browser";
import { getEngineNativeType } from "metabase/lib/engine";
import { isNotNull } from "metabase/lib/types";
import { PLUGIN_METABOT } from "metabase/plugins";
@@ -264,10 +265,8 @@ export const getPlaceholderText = (engine?: string | null): string => {
const engineType = getEngineNativeType(engine);
- if (PLUGIN_METABOT.isEnabled()) {
- if (engineType === "sql") {
- return t`Write your SQL here, or have Metabot help you`;
- }
+ if (PLUGIN_METABOT.isEnabled() && engineType === "sql") {
+ return t`Write your SQL here, or press ${METAKEY} + ; to have SQL generated for you.`;
}
switch (true) {
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.unit.spec.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.unit.spec.tsx
index c68af5f9423..b053db707f2 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/util.unit.spec.tsx
@@ -187,7 +187,7 @@ describe("getPlaceholderText", () => {
it("should return metabot placeholder text for sql", () => {
expect(getPlaceholderText("sql")).toBe(
- "Write your SQL here, or have Metabot help you",
+ "Write your SQL here, or press Ctrl + ; to have SQL generated for you.",
);
});
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
index db3eb381af7..bc64e8e42a8 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
@@ -239,7 +239,6 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
snippets: true,
promptInput: true,
formatQuery: true,
- aiGeneration: true,
},
hasTopBar = true,
hasEditingSidebar = true,
@@ -261,6 +260,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
runQuery,
highlightedLineNumbers,
placeholder,
+ extensions,
} = this.props;
const dragHandle = resizable ? (
@@ -354,6 +354,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {
readOnly={readOnly}
placeholder={placeholder}
highlightedLineNumbers={highlightedLineNumbers}
+ extensions={extensions}
onChange={this.onChange}
onRunQuery={runQuery}
onSelectionChange={setNativeEditorSelectedRange}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
index 2ade3ad073b..1be58d487e4 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorActionButtons/NativeQueryEditorActionButtons.tsx
@@ -1,6 +1,5 @@
import { t } from "ttag";
-import { PLUGIN_METABOT } from "metabase/plugins";
import { DataReferenceButton } from "metabase/query_builder/components/view/DataReferenceButton";
import { NativeVariablesButton } from "metabase/query_builder/components/view/NativeVariablesButton";
import { PreviewQueryButton } from "metabase/query_builder/components/view/PreviewQueryButton";
@@ -57,8 +56,6 @@ export const NativeQueryEditorActionButtons = (
// Default to true if not explicitly set to false
const showFormatButton = features.formatQuery !== false;
- const showAiGeneration =
- features.aiGeneration !== false && PLUGIN_METABOT.isEnabled();
return (
<Flex
@@ -95,7 +92,6 @@ export const NativeQueryEditorActionButtons = (
/>
</Tooltip>
)}
- {showAiGeneration && <PLUGIN_METABOT.MetabotToggleButton />}
</Flex>
);
};
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx
index dec58fb3315..4ef023c1f87 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/types.tsx
@@ -14,5 +14,4 @@ export type SidebarFeatures = {
snippets?: boolean;
promptInput?: boolean;
formatQuery?: boolean;
- aiGeneration?: boolean;
};
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 32f74fd6600..bf1236d0b87 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
@@ -1,6 +1,7 @@
import type { ResizableBoxProps } from "react-resizable";
import { useSelector } from "metabase/lib/redux";
+import { PLUGIN_METABOT } from "metabase/plugins";
import NativeQueryEditor from "metabase/query_builder/components/NativeQueryEditor";
import type {
SelectionRange,
@@ -86,6 +87,8 @@ export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {
getHighlightedNativeQueryLineNumbers,
);
+ const inlineSQLPrompt = PLUGIN_METABOT.useInlineSQLPrompt(question, "qb");
+
// Normally, when users open native models,
// they open an ad-hoc GUI question using the model as a data source
// (using the `/dataset` endpoint instead of the `/card/:id/query`)
@@ -108,7 +111,12 @@ export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {
isInitiallyOpen={isNativeEditorOpen}
datasetQuery={card && card.dataset_query}
onSetDatabaseId={onSetDatabaseId}
+ extensions={inlineSQLPrompt?.extensions}
+ proposedQuestion={inlineSQLPrompt?.proposedQuestion}
+ onAcceptProposed={inlineSQLPrompt?.handleAcceptProposed}
+ onRejectProposed={inlineSQLPrompt?.handleRejectProposed}
/>
+ {inlineSQLPrompt?.portalElement}
</Box>
);
};
diff --git a/frontend/src/metabase/query_builder/selectors.js b/frontend/src/metabase/query_builder/selectors.js
index 0f2ab6e41f8..afbd24e4c93 100644
--- a/frontend/src/metabase/query_builder/selectors.js
+++ b/frontend/src/metabase/query_builder/selectors.js
@@ -480,7 +480,7 @@ export const getIsResultDirty = createSelector(
getTableMetadata,
],
(
- question,
+ currentQuestion,
originalQuestion,
lastRunQuestion,
lastParameters,
@@ -489,15 +489,15 @@ export const getIsResultDirty = createSelector(
) => {
const haveParametersChanged = !_.isEqual(lastParameters, nextParameters);
const isEditable =
- !!question && Lib.queryDisplayInfo(question.query()).isEditable;
-
+ !!currentQuestion &&
+ Lib.queryDisplayInfo(currentQuestion.query()).isEditable;
return (
haveParametersChanged ||
(isEditable &&
!areQueriesEquivalent({
originalQuestion,
lastRunQuestion,
- currentQuestion: question,
+ currentQuestion,
tableMetadata,
}))
);
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
index b402ad8db5c..c22ae328175 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
@@ -34,7 +34,6 @@ const NATIVE_EDITOR_SIDEBAR_FEATURES = {
formatQuery: true,
variables: false,
promptInput: false,
- aiGeneration: false,
};
type QueryEditorBodyProps = {
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion.tsx
index 983d8dc66a8..05238e172bb 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Mention/MentionSuggestion.tsx
@@ -12,6 +12,7 @@ import type { SearchResult } from "metabase-types/api";
import { EntitySearchSection } from "../shared/EntitySearchSection";
import type { SuggestionModel } from "../shared/types";
+import type { EntitySearchOptions } from "../shared/useEntitySearch";
import { useEntitySuggestions } from "../shared/useEntitySuggestions";
import type { MentionCommandProps } from "./MentionExtension";
@@ -23,6 +24,7 @@ export interface MentionSuggestionProps {
range: Range;
query: string;
searchModels?: SuggestionModel[];
+ searchOptions?: EntitySearchOptions;
canFilterSearchModels?: boolean;
canBrowseAll?: boolean;
}
@@ -42,6 +44,7 @@ const MentionSuggestionComponent = forwardRef<
range,
query,
searchModels,
+ searchOptions,
canFilterSearchModels = false,
canBrowseAll = true,
},
@@ -79,6 +82,7 @@ const MentionSuggestionComponent = forwardRef<
editor,
range,
searchModels,
+ searchOptions,
onSelectEntity,
canFilterSearchModels,
canBrowseAll,
@@ -117,27 +121,16 @@ const MentionSuggestionComponent = forwardRef<
export const MentionSuggestion = MentionSuggestionComponent;
-export const createMentionSuggestion = ({
- searchModels,
- canFilterSearchModels,
- canBrowseAll,
-}: {
- searchModels: SuggestionModel[];
- canFilterSearchModels?: boolean;
- canBrowseAll?: boolean;
-}) => {
+export const createMentionSuggestion = (
+ outerProps: Pick<
+ MentionSuggestionProps,
+ "searchModels" | "searchOptions" | "canFilterSearchModels" | "canBrowseAll"
+ >,
+) => {
return forwardRef<
SuggestionRef,
Omit<MentionSuggestionProps, "searchModels">
>(function MentionSuggestionWrapper(props, ref) {
- return (
- <MentionSuggestion
- {...props}
- ref={ref}
- searchModels={searchModels}
- canFilterSearchModels={canFilterSearchModels}
- canBrowseAll={canBrowseAll}
- />
- );
+ return <MentionSuggestion {...props} ref={ref} {...outerProps} />;
});
};
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx
index f81ebf6732a..8346f6bc95f 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.tsx
@@ -494,6 +494,7 @@ export const SmartLinkComponent = memo(
href={entityUrl || "#"}
target="_blank"
rel="noreferrer"
+ tabIndex={-1}
onMouseUp={(e) => {
// Stop tiptap from opening this link twice
e.stopPropagation();
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx
index 2b66b48dd39..97572d525f0 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx
@@ -48,7 +48,6 @@ const MODAL_SIDEBAR_FEATURES = {
snippets: false,
promptInput: false,
formatQuery: false,
- aiGeneration: false,
} as const;
const getRunQueryShortcut = () => (isMac() ? t`⌘ + return` : t`Ctrl + enter`);
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySearch.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySearch.ts
index e32be281ccd..24874406065 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySearch.ts
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySearch.ts
@@ -10,6 +10,7 @@ import type {
MentionableUser,
RecentItem,
SearchModel,
+ SearchRequest,
SearchResult,
} from "metabase-types/api";
@@ -27,6 +28,8 @@ import {
filterRecents,
} from "./suggestionUtils";
+export type EntitySearchOptions = Omit<SearchRequest, "q" | "models" | "limit">;
+
interface UseEntitySearchOptions {
query: string;
onSelectRecent: (item: RecentItem) => void;
@@ -35,6 +38,7 @@ interface UseEntitySearchOptions {
enabled?: boolean;
shouldFetchRecents?: boolean;
searchModels?: SuggestionModel[];
+ searchOptions?: EntitySearchOptions;
}
interface UseEntitySearchResult {
@@ -51,6 +55,7 @@ export function useEntitySearch({
enabled = true,
shouldFetchRecents = true,
searchModels = LINK_SEARCH_MODELS,
+ searchOptions = {},
}: UseEntitySearchOptions): UseEntitySearchResult {
const { data: recents = [], isLoading: isRecentsLoading } =
useListRecentsQuery(undefined, {
@@ -75,6 +80,7 @@ export function useEntitySearch({
(model): model is SearchModel => model !== "user",
),
limit: LINK_SEARCH_LIMIT,
+ ...searchOptions,
},
{
skip: !enabled || shouldFetchRecents,
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts
index 876968a84f1..3b57f61e827 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/useEntitySuggestions.ts
@@ -16,7 +16,7 @@ import {
getBrowseAllItemIndex,
} from "./suggestionUtils";
import type { SuggestionModel } from "./types";
-import { useEntitySearch } from "./useEntitySearch";
+import { type EntitySearchOptions, useEntitySearch } from "./useEntitySearch";
interface UseEntitySuggestionsOptions {
query: string;
@@ -30,6 +30,7 @@ interface UseEntitySuggestionsOptions {
}) => void;
enabled?: boolean;
searchModels?: SuggestionModel[];
+ searchOptions?: EntitySearchOptions;
canFilterSearchModels: boolean;
canBrowseAll: boolean;
canCreateNewQuestion?: boolean;
@@ -65,6 +66,7 @@ export function useEntitySuggestions({
onSelectEntity,
enabled = true,
searchModels,
+ searchOptions,
canFilterSearchModels,
canBrowseAll = false,
canCreateNewQuestion = false,
@@ -178,6 +180,7 @@ export function useEntitySuggestions({
!isInModelSelectionMode &&
!selectedSearchModel,
searchModels: effectiveSearchModels,
+ searchOptions,
});
const menuItems = useMemo(() => {