Skip to content

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

Make metabot system prompt textareas fill the viewport (#73908)

Andrei Chernykhe0814e782c6c
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts
index 137e68883fc..441403d35e3 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts
@@ -7,22 +7,24 @@ import type {
EnterpriseSettings,
} from "metabase-types/api";
+type StringSettingKey = {
+ [K in EnterpriseSettingKey]: EnterpriseSettings[K] extends
+ | string
+ | null
+ | undefined
+ ? K
+ : never;
+}[EnterpriseSettingKey];
+
/**
- * Persists a setting on blur and on unmount instead of on every keystroke.
- * For text settings whose saves shouldn't be debounced (e.g. Metabot system
- * prompts, where each save changes LLM behavior and the audit log).
- *
- * Dirty check uses `===` - safe for primitive setting values only.
+ * Persists a text setting on blur and on unmount. Suited for settings whose
+ * saves shouldn't be debounced (e.g. Metabot system prompts).
*/
-export function useAdminSettingWithBlurInput<K extends EnterpriseSettingKey>(
- settingName: K,
-) {
+export function useAdminSettingWithBlurInput(settingName: StringSettingKey) {
const { value: settingValue, updateSetting } = useAdminSetting(settingName);
- const [inputValue, setInputValue] =
- useState<EnterpriseSettings[K]>(settingValue);
- const lastSavedRef = useRef<EnterpriseSettings[K] | undefined>(undefined);
+ const [inputValue, setInputValue] = useState(settingValue);
+ const lastSavedRef = useRef(settingValue);
- // `lastSavedRef.current === undefined` is the "not yet initialized" sentinel.
useEffect(() => {
if (lastSavedRef.current === undefined && settingValue !== undefined) {
setInputValue(settingValue);
@@ -30,43 +32,31 @@ export function useAdminSettingWithBlurInput<K extends EnterpriseSettingKey>(
}
}, [settingValue]);
- const isDirty = inputValue !== lastSavedRef.current;
+ const trimmedInput = (inputValue ?? "").trim();
+ const trimmedSaved = (lastSavedRef.current ?? "").trim();
+ const isDirty = trimmedInput !== trimmedSaved;
+
+ useBeforeUnload(isDirty);
const save = useCallback(() => {
if (!isDirty) {
return;
}
- lastSavedRef.current = inputValue;
- updateSetting({
- key: settingName,
- value: inputValue,
- });
- }, [isDirty, inputValue, settingName, updateSetting]);
+ lastSavedRef.current = trimmedInput;
+ updateSetting({ key: settingName, value: trimmedInput });
+ }, [isDirty, trimmedInput, settingName, updateSetting]);
- // Mirror `save` so blur / unmount can read the latest closure without
- // re-binding handlers on every keystroke.
+ // Track the latest `save` so the unmount cleanup can fire it. Browser back
+ // doesn't fire blur on the focused textarea, so the cleanup is what saves.
const saveRef = useRef(save);
- useEffect(() => {
- saveRef.current = save;
- }, [save]);
-
- // Browsers won't wait for async saves during unload, so prompt the user.
- useBeforeUnload(isDirty);
-
- const handleBlur = useCallback(() => {
- saveRef.current();
- }, []);
+ saveRef.current = save;
// Persist a pending edit on SPA navigation away.
- useEffect(() => {
- return () => {
- saveRef.current();
- };
- }, []);
+ useEffect(() => () => saveRef.current(), []);
return {
inputValue,
handleInputChange: setInputValue,
- handleBlur,
+ handleBlur: save,
};
}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css
index 62c01dc04f9..825e92c2f6c 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css
@@ -1,6 +1,25 @@
+/*
+ * 8rem accounts for the admin layout chrome above this wrapper (nav header +
+ * page top padding) plus a small gap below so the content doesn't touch the
+ * viewport edge.
+ */
+.wrapper {
+ height: calc(100dvh - 8rem);
+ overflow: hidden;
+}
+
+.textareaRoot {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+}
+
.textareaWrapper {
- textarea {
- line-height: 1.25rem;
- min-height: 400px;
- }
+ flex: 1;
+ display: flex;
+}
+
+.textareaInput {
+ height: 100%;
+ line-height: 1.25rem;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
index 476c6c23741..3b9bc23077d 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
@@ -1,12 +1,9 @@
import { t } from "ttag";
-import {
- SettingsPageWrapper,
- SettingsSection,
-} from "metabase/admin/components/SettingsSection";
+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
-import { Text, Textarea } from "metabase/ui";
+import { Textarea } from "metabase/ui";
import { useAdminSettingWithBlurInput } from "metabase-enterprise/ai-controls/hooks";
import S from "./MetabotSystemPromptsPage.module.css";
@@ -28,20 +25,24 @@ function SystemPromptPage(props: SystemPromptPageProps) {
useAdminSettingWithBlurInput(settingKey);
return (
- <SettingsPageWrapper title={title} mt="sm">
- <SettingsSection>
- <Text c="text-secondary" size="md" mb="lg">
- {description}
- </Text>
- <Textarea
- aria-label={title}
- className={S.textareaWrapper}
- onChange={(e) => handleInputChange(e.target.value)}
- onBlur={handleBlur}
- placeholder={getPlaceholder()}
- value={inputValue || ""}
- />
- </SettingsSection>
+ <SettingsPageWrapper
+ title={title}
+ description={description}
+ className={S.wrapper}
+ >
+ <Textarea
+ aria-label={title}
+ autosize={false}
+ classNames={{
+ root: S.textareaRoot,
+ wrapper: S.textareaWrapper,
+ input: S.textareaInput,
+ }}
+ onBlur={handleBlur}
+ onChange={(e) => handleInputChange(e.target.value)}
+ placeholder={getPlaceholder()}
+ value={inputValue || ""}
+ />
</SettingsPageWrapper>
);
}
@@ -54,14 +55,6 @@ const getPlaceholder = () => {
"\n" +
t`2. And this` +
"\n" +
- t`3. And lastly, this` +
- "\n\n" +
- t`# Here's another section` +
- "\n" +
- t`1. Do this` +
- "\n" +
- t`2. And this` +
- "\n" +
t`3. And lastly, this`
);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx
index c7803e882d4..2649d86af3b 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx
@@ -21,16 +21,38 @@ import {
SqlGenerationPromptPage,
} from "./MetabotSystemPromptsPage";
-function setup({
+type SystemPromptSettingKey =
+ | "metabot-chat-system-prompt"
+ | "metabot-nlq-system-prompt"
+ | "metabot-sql-system-prompt";
+
+const PAGES = [
+ {
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt" as const,
+ title: "AI chat prompt instructions",
+ },
+ {
+ Component: NaturalLanguagePromptPage,
+ settingKey: "metabot-nlq-system-prompt" as const,
+ title: "Natural language query prompt instructions",
+ },
+ {
+ Component: SqlGenerationPromptPage,
+ settingKey: "metabot-sql-system-prompt" as const,
+ title: "SQL generation prompt instructions",
+ },
+];
+
+async function setup({
Component,
settingKey,
+ title,
settingValue = "",
}: {
Component: React.ComponentType;
- settingKey:
- | "metabot-chat-system-prompt"
- | "metabot-nlq-system-prompt"
- | "metabot-sql-system-prompt";
+ settingKey: SystemPromptSettingKey;
+ title: string;
settingValue?: string | null;
}) {
setupPropertiesEndpoints(
@@ -41,157 +63,108 @@ function setup({
setupSettingsEndpoints([]);
setupUpdateSettingEndpoint();
- return renderWithProviders(
+ const view = renderWithProviders(
<>
<Component />
<UndoListing />
</>,
);
+ const textarea = await screen.findByRole("textbox", { name: title });
+ // Wait for the hook to hydrate inputValue from the loaded setting.
+ await waitFor(() => expect(textarea).toHaveValue(settingValue ?? ""));
+ return { ...view, textarea };
}
-function getUpdateCallsFor(settingKey: string) {
+function getUpdateCallsFor(settingKey: SystemPromptSettingKey) {
return fetchMock.callHistory.calls(`path:/api/setting/${settingKey}`, {
method: "PUT",
});
}
describe("MetabotSystemPromptsPage", () => {
- describe("MetabotChatPromptPage", () => {
- it("renders with the correct title", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
+ describe.each(PAGES)("$title", ({ Component, settingKey, title }) => {
+ it("renders the page with the existing prompt value", async () => {
+ const { textarea } = await setup({
+ Component,
+ settingKey,
+ title,
+ settingValue: "Existing value",
});
- expect(
- await screen.findByText("AI chat prompt instructions"),
- ).toBeInTheDocument();
+ expect(screen.getByText(title)).toBeInTheDocument();
+ expect(textarea).toHaveValue("Existing value");
});
+ });
- it("renders the textarea with existing prompt value", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- settingValue: "Be concise and helpful",
- });
+ describe("MetabotChatPromptPage save behavior", () => {
+ const chatPage = PAGES[0];
+ const getChatSaves = () => getUpdateCallsFor(chatPage.settingKey);
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
-
- await waitFor(() => {
- expect(textarea).toHaveValue("Be concise and helpful");
- });
- });
-
- it("updates the textarea value when user types", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- });
+ it("saves on blur and shows a 'Changes saved' toast", async () => {
+ const { textarea } = await setup(chatPage);
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
- await userEvent.type(textarea, "New instructions");
+ await userEvent.type(textarea, "Be concise");
+ fireEvent.blur(textarea);
- await waitFor(() => {
- expect(textarea).toHaveValue("New instructions");
- });
+ await waitFor(() => expect(getChatSaves()).toHaveLength(1));
+ const [call] = getChatSaves();
+ expect(await call?.request?.json()).toEqual({ value: "Be concise" });
+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();
});
- it("does not save while the user is typing", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
+ it("does not save if the user types and reverts before blurring", async () => {
+ const { textarea } = await setup({
+ ...chatPage,
+ settingValue: "Existing prompt",
});
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
- await userEvent.type(textarea, "Some prompt");
+ await userEvent.click(textarea);
+ await userEvent.type(textarea, "x{Backspace}");
+ fireEvent.blur(textarea);
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(0);
+ expect(getChatSaves()).toHaveLength(0);
});
- it("saves on blur and shows a 'Changes saved' toast", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- });
+ it("does not save if only the leading/trailing whitespace changes", async () => {
+ const { textarea } = await setup({ ...chatPage, settingValue: "hello" });
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
- await userEvent.type(textarea, "Be concise");
+ await userEvent.click(textarea);
+ await userEvent.type(textarea, " ");
fireEvent.blur(textarea);
- await waitFor(() => {
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(1);
- });
-
- const [call] = getUpdateCallsFor("metabot-chat-system-prompt");
- expect(await call?.request?.json()).toEqual({ value: "Be concise" });
-
- expect(await screen.findByText("Changes saved")).toBeInTheDocument();
+ expect(getChatSaves()).toHaveLength(0);
});
- it("does not re-save on blur if the value did not change", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- settingValue: "Existing prompt",
- });
-
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
- await waitFor(() => {
- expect(textarea).toHaveValue("Existing prompt");
- });
+ it("trims leading and trailing whitespace before saving", async () => {
+ const { textarea } = await setup(chatPage);
- fireEvent.focus(textarea);
+ await userEvent.type(textarea, " hello world ");
fireEvent.blur(textarea);
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(0);
+ await waitFor(() => expect(getChatSaves()).toHaveLength(1));
+ const [call] = getChatSaves();
+ expect(await call?.request?.json()).toEqual({ value: "hello world" });
});
it("saves each distinct value across consecutive edit cycles", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- });
-
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
+ const { textarea } = await setup(chatPage);
await userEvent.type(textarea, "First");
fireEvent.blur(textarea);
- await waitFor(() => {
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(1);
- });
+ await waitFor(() => expect(getChatSaves()).toHaveLength(1));
await userEvent.type(textarea, " edit");
fireEvent.blur(textarea);
- await waitFor(() => {
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(2);
- });
+ await waitFor(() => expect(getChatSaves()).toHaveLength(2));
- const calls = getUpdateCallsFor("metabot-chat-system-prompt");
+ const calls = getChatSaves();
expect(await calls[0]?.request?.json()).toEqual({ value: "First" });
expect(await calls[1]?.request?.json()).toEqual({ value: "First edit" });
});
- it("warns about unsaved edits via beforeunload, but stops once saved", async () => {
- setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- });
+ it("toggles the beforeunload guard with the dirty state", async () => {
+ const { textarea } = await setup(chatPage);
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
await userEvent.type(textarea, "Pending");
const dirtyEvent = new Event("beforeunload", { cancelable: true });
@@ -199,9 +172,7 @@ describe("MetabotSystemPromptsPage", () => {
expect(dirtyEvent.defaultPrevented).toBe(true);
fireEvent.blur(textarea);
- await waitFor(() => {
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(1);
- });
+ await waitFor(() => expect(getChatSaves()).toHaveLength(1));
const cleanEvent = new Event("beforeunload", { cancelable: true });
window.dispatchEvent(cleanEvent);
@@ -209,77 +180,14 @@ describe("MetabotSystemPromptsPage", () => {
});
it("saves a pending edit when the page unmounts", async () => {
- const { unmount } = setup({
- Component: MetabotChatPromptPage,
- settingKey: "metabot-chat-system-prompt",
- });
+ // Covers SPA navigation away mid-edit (e.g. browser back), where blur
+ // never fires on the focused textarea.
+ const { textarea, unmount } = await setup(chatPage);
- const textarea = await screen.findByRole("textbox", {
- name: "AI chat prompt instructions",
- });
await userEvent.type(textarea, "Half-typed");
- // No blur - simulate navigating away mid-edit.
unmount();
- await waitFor(() => {
- expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(1);
- });
- });
- });
-
- describe("NaturalLanguagePromptPage", () => {
- it("renders with the correct title", async () => {
- setup({
- Component: NaturalLanguagePromptPage,
- settingKey: "metabot-nlq-system-prompt",
- });
-
- expect(
- await screen.findByText("Natural language query prompt instructions"),
- ).toBeInTheDocument();
- });
-
- it("renders the textarea with existing prompt value", async () => {
- setup({
- Component: NaturalLanguagePromptPage,
- settingKey: "metabot-nlq-system-prompt",
- settingValue: "Prefer bar charts",
- });
-
- const textarea = await screen.findByRole("textbox", {
- name: "Natural language query prompt instructions",
- });
- await waitFor(() => {
- expect(textarea).toHaveValue("Prefer bar charts");
- });
- });
- });
-
- describe("SqlGenerationPromptPage", () => {
- it("renders with the correct title", async () => {
- setup({
- Component: SqlGenerationPromptPage,
- settingKey: "metabot-sql-system-prompt",
- });
-
- expect(
- await screen.findByText("SQL generation prompt instructions"),
- ).toBeInTheDocument();
- });
-
- it("renders the textarea with existing prompt value", async () => {
- setup({
- Component: SqlGenerationPromptPage,
- settingKey: "metabot-sql-system-prompt",
- settingValue: "Use uppercase SQL keywords",
- });
-
- const textarea = await screen.findByRole("textbox", {
- name: "SQL generation prompt instructions",
- });
- await waitFor(() => {
- expect(textarea).toHaveValue("Use uppercase SQL keywords");
- });
+ await waitFor(() => expect(getChatSaves()).toHaveLength(1));
});
});
});