Skip to content

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

Save Metabot system prompts on blur instead of debounced keystroke (#73766)

Andrei Chernykh062e8a3a112e
diff --git a/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts b/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
index 92d097c1eb2..4b41dba0872 100644
--- a/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
+++ b/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
@@ -269,7 +269,8 @@ describe("AI Controls > Metabot access and customization", () => {
cy.findByRole("textbox", { name: /AI chat prompt instructions/ })
.should("be.visible")
.click()
- .type("Be concise and helpful.");
+ .type("Be concise and helpful.")
+ .blur();
cy.wait("@savePrompt").its("response.statusCode").should("eq", 204);
@@ -297,7 +298,8 @@ describe("AI Controls > Metabot access and customization", () => {
})
.should("be.visible")
.click()
- .type("Always use uppercase SQL keywords.");
+ .type("Always use uppercase SQL keywords.")
+ .blur();
cy.wait("@saveSqlPrompt").its("response.statusCode").should("eq", 204);
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts
index f4b3644e93e..f1a1149cc90 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts
@@ -1 +1,2 @@
+export { useAdminSettingWithBlurInput } from "./useAdminSettingWithBlurInput";
export { useAdminSettingWithDebouncedInput } from "./useAdminSettingWithDebouncedInput";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts
new file mode 100644
index 00000000000..137e68883fc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdminSettingWithBlurInput.ts
@@ -0,0 +1,72 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { useAdminSetting } from "metabase/api/utils";
+import { useBeforeUnload } from "metabase/common/hooks/use-before-unload";
+import type {
+ EnterpriseSettingKey,
+ EnterpriseSettings,
+} from "metabase-types/api";
+
+/**
+ * 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.
+ */
+export function useAdminSettingWithBlurInput<K extends EnterpriseSettingKey>(
+ settingName: K,
+) {
+ const { value: settingValue, updateSetting } = useAdminSetting(settingName);
+ const [inputValue, setInputValue] =
+ useState<EnterpriseSettings[K]>(settingValue);
+ const lastSavedRef = useRef<EnterpriseSettings[K] | undefined>(undefined);
+
+ // `lastSavedRef.current === undefined` is the "not yet initialized" sentinel.
+ useEffect(() => {
+ if (lastSavedRef.current === undefined && settingValue !== undefined) {
+ setInputValue(settingValue);
+ lastSavedRef.current = settingValue;
+ }
+ }, [settingValue]);
+
+ const isDirty = inputValue !== lastSavedRef.current;
+
+ const save = useCallback(() => {
+ if (!isDirty) {
+ return;
+ }
+ lastSavedRef.current = inputValue;
+ updateSetting({
+ key: settingName,
+ value: inputValue,
+ });
+ }, [isDirty, inputValue, settingName, updateSetting]);
+
+ // Mirror `save` so blur / unmount can read the latest closure without
+ // re-binding handlers on every keystroke.
+ 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();
+ }, []);
+
+ // Persist a pending edit on SPA navigation away.
+ useEffect(() => {
+ return () => {
+ saveRef.current();
+ };
+ }, []);
+
+ return {
+ inputValue,
+ handleInputChange: setInputValue,
+ handleBlur,
+ };
+}
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 a4b2a527b75..476c6c23741 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
@@ -7,7 +7,7 @@ import {
import { useSelector } from "metabase/redux";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Text, Textarea } from "metabase/ui";
-import { useAdminSettingWithDebouncedInput } from "metabase-enterprise/ai-controls/hooks";
+import { useAdminSettingWithBlurInput } from "metabase-enterprise/ai-controls/hooks";
import S from "./MetabotSystemPromptsPage.module.css";
@@ -24,9 +24,8 @@ type SystemPromptPageProps = {
function SystemPromptPage(props: SystemPromptPageProps) {
const { title, description, settingKey } = props;
- const { handleInputChange, inputValue } = useAdminSettingWithDebouncedInput<
- string | null
- >(settingKey);
+ const { handleInputChange, handleBlur, inputValue } =
+ useAdminSettingWithBlurInput(settingKey);
return (
<SettingsPageWrapper title={title} mt="sm">
@@ -38,6 +37,7 @@ function SystemPromptPage(props: SystemPromptPageProps) {
aria-label={title}
className={S.textareaWrapper}
onChange={(e) => handleInputChange(e.target.value)}
+ onBlur={handleBlur}
placeholder={getPlaceholder()}
value={inputValue || ""}
/>
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 861c9c5f8d5..c7803e882d4 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
@@ -1,11 +1,18 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import {
setupPropertiesEndpoints,
setupSettingsEndpoints,
setupUpdateSettingEndpoint,
} from "__support__/server-mocks";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ fireEvent,
+ renderWithProviders,
+ screen,
+ waitFor,
+} from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
import { createMockSettings } from "metabase-types/api/mocks";
import {
@@ -34,7 +41,18 @@ function setup({
setupSettingsEndpoints([]);
setupUpdateSettingEndpoint();
- renderWithProviders(<Component />);
+ return renderWithProviders(
+ <>
+ <Component />
+ <UndoListing />
+ </>,
+ );
+}
+
+function getUpdateCallsFor(settingKey: string) {
+ return fetchMock.callHistory.calls(`path:/api/setting/${settingKey}`, {
+ method: "PUT",
+ });
}
describe("MetabotSystemPromptsPage", () => {
@@ -81,6 +99,132 @@ describe("MetabotSystemPromptsPage", () => {
expect(textarea).toHaveValue("New instructions");
});
});
+
+ it("does not save while the user is typing", async () => {
+ setup({
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "AI chat prompt instructions",
+ });
+ await userEvent.type(textarea, "Some prompt");
+
+ expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(0);
+ });
+
+ it("saves on blur and shows a 'Changes saved' toast", async () => {
+ setup({
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "AI chat prompt instructions",
+ });
+ await userEvent.type(textarea, "Be concise");
+ 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();
+ });
+
+ 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");
+ });
+
+ fireEvent.focus(textarea);
+ fireEvent.blur(textarea);
+
+ expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(0);
+ });
+
+ 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",
+ });
+
+ await userEvent.type(textarea, "First");
+ fireEvent.blur(textarea);
+ await waitFor(() => {
+ expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(1);
+ });
+
+ await userEvent.type(textarea, " edit");
+ fireEvent.blur(textarea);
+ await waitFor(() => {
+ expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(2);
+ });
+
+ const calls = getUpdateCallsFor("metabot-chat-system-prompt");
+ 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",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "AI chat prompt instructions",
+ });
+ await userEvent.type(textarea, "Pending");
+
+ const dirtyEvent = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(dirtyEvent);
+ expect(dirtyEvent.defaultPrevented).toBe(true);
+
+ fireEvent.blur(textarea);
+ await waitFor(() => {
+ expect(getUpdateCallsFor("metabot-chat-system-prompt")).toHaveLength(1);
+ });
+
+ const cleanEvent = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(cleanEvent);
+ expect(cleanEvent.defaultPrevented).toBe(false);
+ });
+
+ it("saves a pending edit when the page unmounts", async () => {
+ const { unmount } = setup({
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt",
+ });
+
+ 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", () => {