Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: sql editor ai chat (#21277)

ecmadaoece92901b320
diff --git a/frontend/src/lib/keyValueStorage.ts b/frontend/src/lib/keyValueStorage.ts
deleted file mode 100644
index 0c7cfda977..0000000000
--- a/frontend/src/lib/keyValueStorage.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import PouchDB from "pouchdb";
-import PouchDBFind from "pouchdb-find";
-
-PouchDB.plugin(PouchDBFind);
-
-// Simple key-value storage over PouchDB, relocated from the legacy Pinia
-// `useStorageStore`. Stateless module-level singleton — no reactive state, so
-// it doesn't belong on the app store (and its get/put would shadow Zustand's
-// own `get`).
-const db = new PouchDB<{ _id: string; value: unknown }>("bb.storage", {
- // Remove unused and old data automatically.
- auto_compaction: true,
- // Do not save and track old revisions, this is for saving storage usage.
- revs_limit: 1,
-});
-
-export const keyValueStorage = {
- async put<T = unknown>(key: string, value: T): Promise<void> {
- await db.put({ _id: key, value }, { force: true });
- },
- async get<T = unknown>(key: string): Promise<T | undefined> {
- try {
- const doc = await db.get(key);
- return doc.value as T;
- } catch {
- // Data not found or error occurred.
- return undefined;
- }
- },
- async remove(key: string): Promise<void> {
- const doc = await db.get(key);
- if (doc) {
- await db.remove(doc);
- }
- },
-};
diff --git a/frontend/src/lib/plan/initialSQLStorage.test.ts b/frontend/src/lib/plan/initialSQLStorage.test.ts
new file mode 100644
index 0000000000..64ffc728e3
--- /dev/null
+++ b/frontend/src/lib/plan/initialSQLStorage.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { consumeInitialSQL, saveInitialSQL } from "./initialSQLStorage";
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe("initial SQL storage", () => {
+ test("removes a consumed value from durable storage", () => {
+ const key = saveInitialSQL("SELECT 1");
+
+ expect(consumeInitialSQL<string>(key)).toBe("SELECT 1");
+ expect(localStorage.getItem(key)).toBeNull();
+ });
+
+ test("replays a consumed value for StrictMode initialization", () => {
+ const key = saveInitialSQL("SELECT 1");
+
+ expect(consumeInitialSQL<string>(key)).toBe("SELECT 1");
+ expect(consumeInitialSQL<string>(key)).toBe("SELECT 1");
+ });
+
+ test("removes abandoned values after one day", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-29T00:00:00Z"));
+ const abandonedKey = saveInitialSQL({ "databases/one": "ALTER TABLE t" });
+ const consumedKey = saveInitialSQL("SELECT 1");
+ consumeInitialSQL(consumedKey);
+
+ vi.setSystemTime(new Date("2026-08-30T00:00:00.001Z"));
+ saveInitialSQL("SELECT 1");
+
+ expect(localStorage.getItem(abandonedKey)).toBeNull();
+ expect(consumeInitialSQL(consumedKey)).toBeUndefined();
+ });
+
+ test("keeps only the most recent abandoned values", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-29T00:00:00Z"));
+ const keys = Array.from({ length: 25 }, (_, index) => {
+ vi.setSystemTime(new Date(Date.UTC(2026, 7, 29, 0, 0, index)));
+ return saveInitialSQL(`SELECT ${index}`);
+ });
+
+ const storedKeys = Array.from({ length: localStorage.length }, (_, index) =>
+ localStorage.key(index)
+ ).filter((key) => key?.startsWith("bb.plan.initial-sql."));
+ expect(storedKeys).toHaveLength(20);
+ expect(localStorage.getItem(keys[0])).toBeNull();
+ expect(localStorage.getItem(keys.at(-1)!)).not.toBeNull();
+ });
+
+ test("reports local storage failures to the caller", () => {
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("Storage quota exceeded", "QuotaExceededError");
+ });
+
+ expect(() => saveInitialSQL("SELECT 1")).toThrow("Storage quota exceeded");
+ });
+});
diff --git a/frontend/src/lib/plan/initialSQLStorage.ts b/frontend/src/lib/plan/initialSQLStorage.ts
new file mode 100644
index 0000000000..f6f6a65b4f
--- /dev/null
+++ b/frontend/src/lib/plan/initialSQLStorage.ts
@@ -0,0 +1,82 @@
+import { v4 as uuidv4 } from "uuid";
+
+const STORAGE_PREFIX = "bb.plan.initial-sql.";
+const STORAGE_TTL_MS = 24 * 60 * 60 * 1000;
+const MAX_STORED_VALUES = 20;
+
+type StoredInitialSQL = {
+ createdAt: number;
+ value: unknown;
+};
+
+// React StrictMode replays the initial fetch in development. Keep consumed
+// values in memory so the replay sees the same SQL after durable storage has
+// already been cleared.
+const consumedValues = new Map<string, StoredInitialSQL>();
+
+const parseStoredValue = (raw: string): StoredInitialSQL | undefined => {
+ try {
+ const parsed = JSON.parse(raw) as Partial<StoredInitialSQL>;
+ if (
+ typeof parsed !== "object" ||
+ parsed === null ||
+ typeof parsed.createdAt !== "number" ||
+ !("value" in parsed)
+ ) {
+ return undefined;
+ }
+ return parsed as StoredInitialSQL;
+ } catch {
+ return undefined;
+ }
+};
+
+const pruneStoredValues = (maxStoredValues = MAX_STORED_VALUES) => {
+ const now = Date.now();
+ for (const [key, stored] of consumedValues) {
+ if (now - stored.createdAt > STORAGE_TTL_MS) {
+ consumedValues.delete(key);
+ }
+ }
+ const storedValues: Array<{ createdAt: number; key: string }> = [];
+ for (let i = localStorage.length - 1; i >= 0; i--) {
+ const key = localStorage.key(i);
+ if (!key?.startsWith(STORAGE_PREFIX)) continue;
+ const stored = parseStoredValue(localStorage.getItem(key) ?? "");
+ if (!stored || now - stored.createdAt > STORAGE_TTL_MS) {
+ localStorage.removeItem(key);
+ } else {
+ storedValues.push({ createdAt: stored.createdAt, key });
+ }
+ }
+ storedValues
+ .sort((a, b) => a.createdAt - b.createdAt)
+ .slice(0, Math.max(0, storedValues.length - maxStoredValues))
+ .forEach(({ key }) => localStorage.removeItem(key));
+};
+
+export const saveInitialSQL = (value: unknown): string => {
+ pruneStoredValues(MAX_STORED_VALUES - 1);
+ const key = `${STORAGE_PREFIX}${uuidv4()}`;
+ localStorage.setItem(key, JSON.stringify({ createdAt: Date.now(), value }));
+ return key;
+};
+
+export const consumeInitialSQL = <T>(key: string): T | undefined => {
+ if (!key.startsWith(STORAGE_PREFIX)) return undefined;
+ pruneStoredValues();
+ const consumed = consumedValues.get(key);
+ if (consumed) {
+ return consumed.value as T;
+ }
+ try {
+ const stored = parseStoredValue(localStorage.getItem(key) ?? "");
+ if (!stored) {
+ return undefined;
+ }
+ consumedValues.set(key, stored);
+ return stored.value as T;
+ } finally {
+ localStorage.removeItem(key);
+ }
+};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index a3efb57e8c..271c6191cb 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1634,6 +1634,7 @@
"reset-to-defaults": "Reset to defaults"
},
"go-to-plan-page": "Go to plan page",
+ "initial-sql-storage-failed": "Unable to temporarily save the SQL. Clear some browser storage and try again.",
"isolation-level": {
"read-committed": "Read Committed",
"read-uncommitted": "Read Uncommitted",
@@ -1811,7 +1812,8 @@
"actions": {
"explain-code": "Explain code",
"find-problems": "Find problems",
- "insert-at-caret": "Insert at caret"
+ "insert-at-caret": "Insert at caret",
+ "new-chat-using-selection": "New chat using selection"
},
"ai-assistant": "AI Assistant",
"conversation": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 6a16e77fb6..356d41fd51 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1634,6 +1634,7 @@
"reset-to-defaults": "Restablecer valores predeterminados"
},
"go-to-plan-page": "Ir a la página del plan",
+ "initial-sql-storage-failed": "No se pudo guardar temporalmente el SQL. Libera espacio de almacenamiento del navegador e inténtalo de nuevo.",
"isolation-level": {
"read-committed": "Lectura confirmada",
"read-uncommitted": "Lectura no confirmada",
@@ -1811,7 +1812,8 @@
"actions": {
"explain-code": "Explicar el código",
"find-problems": "encontrar problemas",
- "insert-at-caret": "Insertar en el cursor"
+ "insert-at-caret": "Insertar en el cursor",
+ "new-chat-using-selection": "Nuevo chat con la selección"
},
"ai-assistant": "Asistente de IA",
"conversation": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 76e1068db6..039805d171 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1634,6 +1634,7 @@
"reset-to-defaults": "デフォルトに戻す"
},
"go-to-plan-page": "プランページへ移動",
+ "initial-sql-storage-failed": "SQL を一時保存できませんでした。ブラウザーのストレージを空けて、もう一度お試しください。",
"isolation-level": {
"read-committed": "コミット済み読み取り",
"read-uncommitted": "未コミット読み取り",
@@ -1811,7 +1812,8 @@
"actions": {
"explain-code": "コードの説明",
"find-problems": "問題を見つける",
- "insert-at-caret": "キャレットに挿入"
+ "insert-at-caret": "キャレットに挿入",
+ "new-chat-using-selection": "選択範囲を使用して新しいチャットを開始"
},
"ai-assistant": "AI アシスタント",
"conversation": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 01d770ab72..75ba1f5549 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1634,6 +1634,7 @@
"reset-to-defaults": "Đặt lại về mặc định"
},
"go-to-plan-page": "Đi tới trang kế hoạch",
+ "initial-sql-storage-failed": "Không thể lưu tạm thời SQL. Hãy giải phóng dung lượng lưu trữ của trình duyệt rồi thử lại.",
"isolation-level": {
"read-committed": "Đọc đã cam kết",
"read-uncommitted": "Đọc chưa cam kết",
@@ -1811,7 +1812,8 @@
"actions": {
"explain-code": "Giải thích mã",
"find-problems": "Tìm vấn đề",
- "insert-at-caret": "Chèn vào con trỏ"
+ "insert-at-caret": "Chèn vào con trỏ",
+ "new-chat-using-selection": "Cuộc trò chuyện mới bằng nội dung đã chọn"
},
"ai-assistant": "Trợ lý AI",
"conversation": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index b333444acb..0e3f927d1e 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1634,6 +1634,7 @@
"reset-to-defaults": "重置为默认值"
},
"go-to-plan-page": "前往计划页面",
+ "initial-sql-storage-failed": "无法临时保存 SQL。请清理部分浏览器存储空间后重试。",
"isolation-level": {
"read-committed": "已提交读",
"read-uncommitted": "未提交读",
@@ -1811,7 +1812,8 @@
"actions": {
"explain-code": "解释代码",
"find-problems": "找出问题",
- "insert-at-caret": "在光标处插入"
+ "insert-at-caret": "在光标处插入",
+ "new-chat-using-selection": "使用选中内容新建对话"
},
"ai-assistant": "AI 助手",
"conversation": {
diff --git a/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts b/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts
index e6ddd36ef0..5403b68d17 100644
--- a/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts
+++ b/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts
@@ -102,7 +102,9 @@ function defaultMdNodeToReact(node: RootContent, state: State): ReactNode {
function rootToReact(node: Root, state: State): ReactNode {
return createElement(
"div",
- { className: "markdown min-w-0 max-w-full wrap-anywhere" },
+ {
+ className: "markdown min-w-0 max-w-full wrap-anywhere text-sm leading-5",
+ },
mapChildren(node.children, state)
);
}
diff --git a/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsx b/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsx
index bb26b917ac..3fe5d9f80c 100644
--- a/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsx
+++ b/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsx
@@ -58,6 +58,8 @@ describe("AI chat message wrapping", () => {
);
expect(markdown?.className).toContain("wrap-anywhere");
expect(markdown?.className).toContain("min-w-0");
+ expect(markdown?.className).toContain("text-sm");
+ expect(markdown?.className).toContain("leading-5");
expect(markdown?.textContent).toContain(longContent);
});
diff --git a/frontend/src/modules/ai/components/PromptInput.test.tsx b/frontend/src/modules/ai/components/PromptInput.test.tsx
new file mode 100644
index 0000000000..36e2e5cf23
--- /dev/null
+++ b/frontend/src/modules/ai/components/PromptInput.test.tsx
@@ -0,0 +1,65 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { PromptInput } from "./PromptInput";
+
+const mocks = vi.hoisted(() => ({
+ eventsOn: vi.fn(() => vi.fn()),
+ setPendingPreInput: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/utils", () => ({
+ keyboardShortcutStr: (value: string) => value,
+}));
+
+vi.mock("./context", () => ({
+ useAIContext: () => ({
+ pendingPreInput: undefined,
+ setPendingPreInput: mocks.setPendingPreInput,
+ events: { on: mocks.eventsOn },
+ }),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("PromptInput", () => {
+ test("allows only vertical resizing within half the viewport", () => {
+ render(<PromptInput onEnter={vi.fn()} />);
+
+ const textarea = screen.getByRole("textbox");
+ expect(textarea).toHaveClass("resize-y", "max-h-[50vh]");
+ expect(textarea).not.toHaveClass("resize-x", "resize");
+ });
+
+ test("preserves a manually selected height while editing", () => {
+ render(<PromptInput onEnter={vi.fn()} />);
+
+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
+ vi.spyOn(textarea, "getBoundingClientRect").mockReturnValue({
+ bottom: 100,
+ height: 80,
+ left: 0,
+ right: 300,
+ top: 20,
+ width: 300,
+ x: 0,
+ y: 20,
+ toJSON: () => ({}),
+ });
+ Object.defineProperty(textarea, "scrollHeight", {
+ configurable: true,
+ value: 120,
+ });
+
+ fireEvent.pointerDown(textarea, { clientX: 295, clientY: 95 });
+ textarea.style.height = "280px";
+ fireEvent.change(textarea, { target: { value: "Explain this query" } });
+
+ expect(textarea.style.height).toBe("280px");
+ });
+});
diff --git a/frontend/src/modules/ai/components/PromptInput.tsx b/frontend/src/modules/ai/components/PromptInput.tsx
index 3c7c6a4389..6d524d8cc1 100644
--- a/frontend/src/modules/ai/components/PromptInput.tsx
+++ b/frontend/src/modules/ai/components/PromptInput.tsx
@@ -15,13 +15,15 @@ type Props = {
const LINE_HEIGHT_PX = 20;
const MIN_ROWS = 1;
const MAX_ROWS = 10;
+const RESIZE_HANDLE_SIZE_PX = 16;
/**
* React port of `plugins/ai/components/PromptInput.vue`.
*
- * Autosizing textarea (1-10 visible rows) bound to local state. Enter
- * submits; Shift+Enter inserts a newline. The trailing button is a
- * tooltipped ⏎ that submits when clicked.
+ * Autosizing textarea (1-10 visible rows) bound to local state. Users can
+ * resize it vertically, after which their chosen height is preserved. Enter
+ * submits; Shift+Enter inserts a newline. The trailing button is a tooltipped
+ * ⏎ that submits when clicked.
*
* Naive UI's `NInput type="textarea" autosize` isn't available; we
* hand-roll the autosize by measuring `scrollHeight` after each value
@@ -31,8 +33,8 @@ const MAX_ROWS = 10;
* identically for plain text input.
*
* Reacts to two external triggers from `AIContext`:
- * - `pendingPreInput`: a one-shot seed value (e.g. `OpenAIButton`
- * "Ask AI about this query"). Cleared after consumption.
+ * - `pendingPreInput`: a one-shot seed value from an editor action. Cleared
+ * after consumption.
* - `new-conversation` event: re-focuses the textarea so the user can
* immediately type into a freshly-created conversation.
*/
@@ -42,6 +44,7 @@ export function PromptInput({ disabled = false, onEnter }: Props) {
const [value, setValue] = useState("");
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
+ const manuallyResizedRef = useRef(false);
// Focus on mount + on `new-conversation` so the user can start typing
// immediately.
@@ -74,7 +77,7 @@ export function PromptInput({ disabled = false, onEnter }: Props) {
// clamped to [MIN_ROWS, MAX_ROWS] lines.
useLayoutEffect(() => {
const el = textareaRef.current;
- if (!el) return;
+ if (!el || manuallyResizedRef.current) return;
el.style.height = "auto";
const minHeight = MIN_ROWS * LINE_HEIGHT_PX;
const maxHeight = MAX_ROWS * LINE_HEIGHT_PX;
@@ -82,6 +85,18 @@ export function PromptInput({ disabled = false, onEnter }: Props) {
el.style.height = `${next}px`;
}, [value]);
+ const handlePointerDown = (
+ event: React.PointerEvent<HTMLTextAreaElement>
+ ) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ if (
+ event.clientX >= bounds.right - RESIZE_HANDLE_SIZE_PX &&
+ event.clientY >= bounds.bottom - RESIZE_HANDLE_SIZE_PX
+ ) {
+ manuallyResizedRef.current = true;
+ }
+ };
+
const applyValue = (raw: string) => {
setValue("");
onEnter(raw);
@@ -125,19 +140,20 @@ export function PromptInput({ disabled = false, onEnter }: Props) {
placeholder={t("plugin.ai.text-to-sql-placeholder")}
onChange={(e) => setValue(e.target.value)}
onKeyDown={handleKeyDown}
+ onPointerDown={handlePointerDown}
rows={MIN_ROWS}
className={cn(
- "w-full resize-none rounded-xs border border-control-border bg-background pl-2 pr-9 py-1 text-sm",
+ "w-full min-h-5 max-h-[50vh] resize-y overflow-y-auto rounded-xs border border-control-border bg-background pl-2 pr-14 py-1 text-sm",
"leading-5 text-main placeholder:text-control-placeholder",
"focus:outline-none focus:border-accent focus:ring-0",
- "disabled:opacity-50 disabled:cursor-not-allowed"
+ "disabled:resize-none disabled:opacity-50 disabled:cursor-not-allowed"
)}
/>
<Tooltip content={tooltipContent} side="top">
<Button
appearance="secondary"
size="xs"
- className="absolute right-1 bottom-1 h-6 px-1.5 text-accent"
+ className="absolute right-5 bottom-1 h-6 px-1.5 text-accent"
disabled={!value || disabled}
onClick={handleSubmitClick}
aria-label={t("plugin.ai.send")}
diff --git a/frontend/src/modules/ai/components/context.tsx b/frontend/src/modules/ai/components/context.tsx
index 8cffe1fcf8..51f684d67d 100644
--- a/frontend/src/modules/ai/components/context.tsx
+++ b/frontend/src/modules/ai/components/context.tsx
@@ -67,9 +67,8 @@ export type ReactAIContext = {
/**
* One-shot trigger written by the `new-conversation` event handler when
- * the host pre-fills a seed prompt (e.g. `OpenAIButton.tsx` "Ask AI
- * about this query"). `PromptInput` reads + clears it on mount /
- * pending-pre-input change.
+ * an editor action pre-fills a seed prompt. `PromptInput` reads + clears it
+ * on mount / pending-pre-input change.
*/
pendingPreInput: string | undefined;
setPendingPreInput: (next: string | undefined) => void;
diff --git a/frontend/src/modules/sql-editor/components/EditorAction.tsx b/frontend/src/modules/sql-editor/components/EditorAction.tsx
index d2dbb42af6..ae88091b7a 100644
--- a/frontend/src/modules/sql-editor/components/EditorAction.tsx
+++ b/frontend/src/modules/sql-editor/components/EditorAction.tsx
@@ -235,10 +235,7 @@ export function EditorAction({ onExecute }: Props) {
</div>
<div className="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center">
<ChooserGroup />
- <OpenAIButton
- size="sm"
- statement={currentTab?.selectedStatement || currentTab?.statement}
- />
+ <OpenAIButton size="sm" />
</div>
</div>
);
diff --git a/frontend/src/modules/sql-editor/components/ExecuteHint.tsx b/frontend/src/modules/sql-editor/components/ExecuteHint.tsx
index 1f3bee9e96..eb65fecd5e 100644
--- a/frontend/src/modules/sql-editor/components/ExecuteHint.tsx
+++ b/frontend/src/modules/sql-editor/components/ExecuteHint.tsx
@@ -1,9 +1,9 @@
import { Trans, useTranslation } from "react-i18next";
-import { v4 as uuidv4 } from "uuid";
import { router } from "@/app/router";
import { buildPlanCreateRoute } from "@/app/router/routeHelpers";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
+import { saveInitialSQL } from "@/lib/plan/initialSQLStorage";
import { applyPlanTitleToQuery } from "@/lib/plan/title";
import { useSQLEditorAllowAdmin } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
@@ -16,7 +16,6 @@ import {
extractProjectResourceName,
getDatabaseEnvironment,
} from "@/utils";
-import { putBlob } from "@/utils/blob-storage";
import { AdminModeButton } from "./AdminModeButton";
type Props = {
@@ -48,8 +47,6 @@ export function ExecuteHint({ database, onClose }: Props) {
return;
}
- onClose();
-
const db = await useAppStore
.getState()
.getOrFetchDatabaseByName(connectedDatabase);
@@ -61,8 +58,17 @@ export function ExecuteHint({ database, onClose }: Props) {
const tab = tabsState.tabsById.get(tabsState.currentTabId);
const statement = tab?.selectedStatement || tab?.statement || "";
- const sqlStorageKey = `bb.issues.sql.${uuidv4()}`;
- void putBlob(sqlStorageKey, statement);
+ let sqlStorageKey: string;
+ try {
+ sqlStorageKey = saveInitialSQL(statement);
+ } catch {
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("plan.initial-sql-storage-failed"),
+ });
+ return;
+ }
const { databaseName } = extractDatabaseResourceName(db.name);
const query: Record<string, string> = {
@@ -78,6 +84,7 @@ export function ExecuteHint({ database, onClose }: Props) {
const route = router.resolve(
buildPlanCreateRoute(extractProjectResourceName(db.project), query)
);
+ onClose();
window.open(route.fullPath, "_blank");
};
diff --git a/frontend/src/modules/sql-editor/components/OpenAIButton.test.tsx b/frontend/src/modules/sql-editor/components/OpenAIButton.test.tsx
index 1fa5547357..1ac38ee250 100644
--- a/frontend/src/modules/sql-editor/components/OpenAIButton.test.tsx
+++ b/frontend/src/modules/sql-editor/components/OpenAIButton.test.tsx
@@ -2,7 +2,6 @@ import type { ReactElement } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
-import { Engine } from "@/types/proto-es/v1/common_pb";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -26,12 +25,7 @@ const mocks = vi.hoisted(() => ({
// `useAppStore((s) => s.getOrFetchSettingByName)` in an effect.
aiSetting: undefined as unknown,
getOrFetchSettingByName: vi.fn().mockResolvedValue(undefined),
- useConnectionOfCurrentSQLEditorTab: vi.fn(),
hasWorkspacePermissionV2: vi.fn(() => true),
- nextAnimationFrame: vi.fn(() => Promise.resolve()),
- emit: vi.fn(),
- explainCode: vi.fn((s: string) => `EXPLAIN:${s}`),
- findProblems: vi.fn((s: string) => `FIND:${s}`),
routerPush: vi.fn(),
}));
@@ -56,11 +50,6 @@ vi.mock("@/stores/app", () => {
};
});
-// `useConnectionOfCurrentSQLEditorTab` now lives on the Pinia bridge hook.
-vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
- useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
-}));
-
// Zustand tab store — derived hook + selector hook for connection/mode.
vi.mock("@/modules/sql-editor/store/tab", () => ({
useIsDisconnected: () => mocks.tabState.isDisconnected,
@@ -91,16 +80,6 @@ vi.mock("@/modules/sql-editor/store", () => ({
vi.mock("@/utils", () => ({
hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,
- nextAnimationFrame: mocks.nextAnimationFrame,
-}));
-
-vi.mock("@/modules/ai/logic", () => ({
- aiContextEvents: { emit: mocks.emit },
-}));
-
-vi.mock("@/modules/ai/logic/prompt", () => ({
- explainCode: mocks.explainCode,
- findProblems: mocks.findProblems,
}));
vi.mock("@/app/router", async (importOriginal) => ({
@@ -151,41 +130,18 @@ vi.mock("@/components/ui/popover", () => ({
),
}));
-vi.mock("@/components/ui/dropdown-menu", () => ({
- DropdownMenu: ({
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({
children,
- open,
+ content,
}: {
children: React.ReactNode;
- open?: boolean;
+ content: React.ReactNode;
}) => (
- <div data-testid="dropdown-menu" data-open={String(open ?? false)}>
+ <div data-testid="tooltip" data-content={String(content)}>
{children}
</div>
),
- DropdownMenuTrigger: ({ render }: { render?: React.ReactElement }) => (
- <div data-testid="dropdown-menu-trigger">{render}</div>
- ),
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="dropdown-menu-content">{children}</div>
- ),
- DropdownMenuItem: ({
- children,
- onClick,
- disabled,
- }: {
- children: React.ReactNode;
- onClick?: () => void;
- disabled?: boolean;
- }) => (
- <button
- data-testid="dropdown-menu-item"
- disabled={disabled}
- onClick={onClick}
- >
- {children}
- </button>
- ),
}));
let OpenAIButton: typeof import("./OpenAIButton").OpenAIButton;
@@ -215,7 +171,6 @@ type VueStateValues = {
isDisconnected: boolean;
currentMode: string | undefined;
showAIPanel: boolean;
- instance: { engine: Engine };
openAIEnabled: boolean;
};
@@ -224,7 +179,6 @@ const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {
isDisconnected: false,
currentMode: "SAVED_QUERY",
showAIPanel: false,
- instance: { engine: Engine.POSTGRES },
openAIEnabled: true,
...overrides,
};
@@ -240,11 +194,6 @@ const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {
mocks.aiSetting = values.openAIEnabled
? { value: { value: { case: "ai", value: { enabled: true } } } }
: undefined;
-
- // Migrated hook returns PLAIN values — no Vue `.value` wrapper.
- mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({
- instance: values.instance,
- });
};
beforeEach(async () => {
@@ -325,13 +274,23 @@ describe("OpenAIButton", () => {
unmount();
});
- test("click toggles showAIPanel when enabled", () => {
+ test("uses the icon only to toggle the panel without an action menu", () => {
setupDefaultMocks();
+ const LegacyOpenAIButton = OpenAIButton as React.ComponentType<{
+ statement?: string;
+ }>;
const { container, render, unmount } = renderIntoContainer(
- <OpenAIButton />
+ <LegacyOpenAIButton statement="SELECT 1" />
);
render();
+ expect(container.querySelector("[data-testid='dropdown-menu']")).toBeNull();
+ expect(
+ container
+ .querySelector("[data-testid='tooltip']")
+ ?.getAttribute("data-content")
+ ).toBe("plugin.ai.ai-assistant");
+
const button = container.querySelector(
"[data-testid='button']"
) as HTMLButtonElement | null;
@@ -345,32 +304,4 @@ describe("OpenAIButton", () => {
unmount();
});
-
- test("selecting explain-code action emits send-chat with prompt", async () => {
- setupDefaultMocks();
- const { container, render, unmount } = renderIntoContainer(
- <OpenAIButton statement="SELECT 1" />
- );
- render();
-
- const items = container.querySelectorAll(
- "[data-testid='dropdown-menu-item']"
- );
- // First item = explain-code
- const explainItem = items[0] as HTMLButtonElement | undefined;
- expect(explainItem?.textContent).toBe("plugin.ai.actions.explain-code");
-
- await act(async () => {
- explainItem?.click();
- });
-
- expect(mocks.setShowAIPanel).toHaveBeenCalledWith(true);
- expect(mocks.explainCode).toHaveBeenCalledWith("SELECT 1", Engine.POSTGRES);
- expect(mocks.emit).toHaveBeenCalledWith("send-chat", {
- content: "EXPLAIN:SELECT 1",
- newChat: true,
- });
-
- unmount();
- });
});
diff --git a/frontend/src/modules/sql-editor/components/OpenAIButton.tsx b/frontend/src/modules/sql-editor/components/OpenAIButton.tsx
index e092c91b44..f854e626ae 100644
--- a/frontend/src/modules/sql-editor/components/OpenAIButton.tsx
+++ b/frontend/src/modules/sql-editor/components/OpenAIButton.tsx
@@ -3,26 +3,17 @@ import { useTranslation } from "react-i18next";
import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/app/router/handles";
import { RouterLink } from "@/components/RouterLink";
import { Button, buttonVariants } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
+import { Tooltip } from "@/components/ui/tooltip";
import {
AI_ASSISTANT_PRODUCT_INTRO,
PRODUCT_INTRO_QUERY_KEY,
} from "@/lib/productIntro";
import { cn } from "@/lib/utils";
-import { aiContextEvents } from "@/modules/ai/logic";
-import * as promptUtils from "@/modules/ai/logic/prompt";
-import type { ChatAction } from "@/modules/ai/types";
-import { useConnectionOfCurrentSQLEditorTab } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { useSQLEditorStore } from "@/modules/sql-editor/store";
import {
useIsDisconnected,
@@ -30,33 +21,25 @@ import {
} from "@/modules/sql-editor/store/tab";
import { useAppStore } from "@/stores/app";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
-import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";
+import { hasWorkspacePermissionV2 } from "@/utils";
type Size = "sm" | "default";
type Props = {
- /**
- * Restricts the popselect to the provided subset of actions. When omitted
- * all built-in actions (explain-code, find-problems) render.
- */
- readonly actions?: ChatAction[];
- /** The SQL statement the assistant should reason about. */
- readonly statement?: string;
readonly size?: Size;
};
/**
* Replaces frontend/src/views/sql-editor/EditorCommon/OpenAIButton/*.vue.
* Shows an AI-assistant toggle when the editor is connected + in saved query
- * mode. Clicking the button toggles the AI panel; the attached dropdown
- * offers shortcuts that seed the chat with a prompt.
+ * mode. Clicking the button toggles the AI panel. Statement-specific AI
+ * actions live in the editor context menu.
*/
-export function OpenAIButton({ actions, statement, size = "default" }: Props) {
+export function OpenAIButton({ size = "default" }: Props) {
const { t } = useTranslation();
const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);
const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);
const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
- const { instance } = useConnectionOfCurrentSQLEditorTab();
// Make sure the AI setting is resolved before we gate the enabled state.
useEffect(() => {
@@ -74,8 +57,6 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {
: false;
});
- const [menuOpen, setMenuOpen] = useState(false);
-
if (isDisconnected || currentMode !== "SAVED_QUERY") {
return null;
}
@@ -111,80 +92,18 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {
);
}
- // ---- Enabled state -------------------------------------------------------
- const allActions: { value: ChatAction; label: string }[] = [
- { value: "explain-code", label: t("plugin.ai.actions.explain-code") },
- { value: "find-problems", label: t("plugin.ai.actions.find-problems") },
- ];
- const visibleActions = actions
- ? allActions.filter((o) => actions.includes(o.value))
- : allActions;
- const hasActions = visibleActions.length > 0;
-
- const handleSelect = async (action: ChatAction) => {
- setMenuOpen(false);
- const newChat = !showAIPanel;
- setShowAIPanel(true);
-
- if (!statement) return;
- await nextAnimationFrame();
- if (action === "explain-code") {
- void aiContextEvents.emit("send-chat", {
- content: promptUtils.explainCode(statement, instance.engine),
- newChat,
- });
- } else if (action === "find-problems") {
- void aiContextEvents.emit("send-chat", {
- content: promptUtils.findProblems(statement, instance.engine),
- newChat,
- });
- }
- };
-
- const renderButton = (onClick?: () => void) => (
- <Button
- appearance={buttonAppearance}
- size={size}
- className={buttonClass}
- aria-label={t("plugin.ai.ai-assistant")}
- onClick={onClick}
- >
- {icon}
- </Button>
- );
-
- if (!hasActions) {
- return renderButton(handleToggle);
- }
-
return (
- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
- <DropdownMenuTrigger
- render={renderButton(handleToggle)}
- onContextMenu={(e) => {
- // Right-click opens the action menu; left-click is handled by the
- // button's onClick and toggles the AI panel.
- e.preventDefault();
- setMenuOpen(true);
- }}
- />
- <DropdownMenuContent align="end" sideOffset={4}>
- <div className="px-3 py-1.5 text-xs font-semibold text-control-light">
- {t("plugin.ai.ai-assistant")}
- </div>
- {visibleActions.map((opt) => (
- <DropdownMenuItem
- key={opt.value}
- disabled={!statement}
- onClick={() => {
- void handleSelect(opt.value);
- }}
- >
- {opt.label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
+ <Tooltip content={t("plugin.ai.ai-assistant")} side="bottom">
+ <Button
+ appearance={buttonAppearance}
+ size={size}
+ className={buttonClass}
+ aria-label={t("plugin.ai.ai-assistant")}
+ onClick={handleToggle}
+ >
+ {icon}
+ </Button>
+ </Tooltip>
);
}
diff --git a/frontend/src/modules/sql-editor/components/Panels/ViewsPanel/ViewDetail.tsx b/frontend/src/modules/sql-editor/components/Panels/ViewsPanel/ViewDetail.tsx
index b12557f2e0..56e4c44ff7 100644
--- a/frontend/src/modules/sql-editor/components/Panels/ViewsPanel/ViewDetail.tsx
+++ b/frontend/src/modules/sql-editor/components/Panels/ViewsPanel/ViewDetail.tsx
@@ -32,7 +32,6 @@ export function ViewDetail({ db, database, schema, view }: ViewDetailProps) {
const { detail, clearDetail } = useViewStateNav();
const [mode, setMode] = useState<Mode>("COLUMNS");
const [keyword, setKeyword] = useState("");
- const [selectedStatement, setSelectedStatement] = useState("");
const [format, setFormat] = useState<boolean>(() => {
if (typeof window === "undefined") return false;
return (
@@ -117,23 +116,14 @@ export function ViewDetail({ db, database, schema, view }: ViewDetailProps) {
/>
{t("sql-editor.format")}
</label>
- <OpenAIButton
- size="sm"
- actions={["explain-code"]}
- statement={selectedStatement || view.definition}
- />
+ <OpenAIButton size="sm" />
</div>
) : (
<PanelSearchBox value={keyword} onChange={setKeyword} />
)}
</div>
<TabsPanel value="DEFINITION" className="flex-1 min-h-0 mt-0">
- <DefinitionViewer
- db={db}
- code={view.definition}
- format={format}
- onSelectContent={setSelectedStatement}
- />
+ <DefinitionViewer db={db} code={view.definition} format={format} />
</TabsPanel>
{view.columns.length > 0 ? (
<TabsPanel value="COLUMNS" className="flex-1 min-h-0 mt-0">
diff --git a/frontend/src/modules/sql-editor/components/Panels/common/CodeViewer.tsx b/frontend/src/modules/sql-editor/components/Panels/common/CodeViewer.tsx
index 4f55e718e3..652b912914 100644
--- a/frontend/src/modules/sql-editor/components/Panels/common/CodeViewer.tsx
+++ b/frontend/src/modules/sql-editor/components/Panels/common/CodeViewer.tsx
@@ -188,11 +188,7 @@ export function CodeViewer({
/>
{t("sql-editor.format")}
</label>
- <OpenAIButton
- size="sm"
- actions={["explain-code"]}
- statement={selectedStatement || content}
- />
+ <OpenAIButton size="sm" />
</div>
</div>
<div className="flex-1 min-h-0 flex flex-col overflow-hidden">
diff --git a/frontend/src/modules/sql-editor/components/Panels/common/DefinitionViewer.tsx b/frontend/src/modules/sql-editor/components/Panels/common/DefinitionViewer.tsx
index f5c9b7a9a5..647c24a257 100644
--- a/frontend/src/modules/sql-editor/components/Panels/common/DefinitionViewer.tsx
+++ b/frontend/src/modules/sql-editor/components/Panels/common/DefinitionViewer.tsx
@@ -18,7 +18,6 @@ interface DefinitionViewerProps {
db: Database;
code: string;
format?: boolean;
- onSelectContent?: (content: string) => void;
}
/**
@@ -27,12 +26,7 @@ interface DefinitionViewerProps {
* ViewsPanel detail header has the toggle). Sets `uiStore.isShowingCode`
* on mount so `Panels.vue` renders the AIChatToSQL pane next to it.
*/
-export function DefinitionViewer({
- db,
- code,
- format,
- onSelectContent,
-}: DefinitionViewerProps) {
+export function DefinitionViewer({ db, code, format }: DefinitionViewerProps) {
const setIsShowingCode = useSQLEditorStore((s) => s.setIsShowingCode);
const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);
const engine = useMemo(() => getInstanceResource(db).engine, [db]);
@@ -105,15 +99,13 @@ export function DefinitionViewer({
const model = editor.getModel();
if (!selection || !model) {
setSelectedStatement("");
- onSelectContent?.("");
return;
}
const selected = model.getValueInRange(selection);
setSelectedStatement(selected);
- onSelectContent?.(selected);
});
return () => sub.dispose();
- }, [editor, onSelectContent]);
+ }, [editor]);
return (
<ReadonlyMonaco
diff --git a/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.test.tsx b/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.test.tsx
new file mode 100644
index 0000000000..70324a1273
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.test.tsx
@@ -0,0 +1,109 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import type { MonacoModule } from "@/components/monaco/types";
+import { useAIActions } from "./useAIActions";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ getOrFetchSettingByName: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ ({
+ "plugin.ai.actions.explain-code": "Explain code",
+ "plugin.ai.actions.find-problems": "Find problems",
+ "plugin.ai.actions.new-chat-using-selection":
+ "New chat using selection",
+ })[key] ?? key,
+ }),
+}));
+
+vi.mock("@/stores/app", () => {
+ type AppStoreStub = {
+ getOrFetchSettingByName: typeof mocks.getOrFetchSettingByName;
+ getSettingByName: () => {
+ value: { value: { case: string; value: { enabled: boolean } } };
+ };
+ };
+ const state = {
+ getOrFetchSettingByName: mocks.getOrFetchSettingByName,
+ getSettingByName: () => ({
+ value: { value: { case: "ai", value: { enabled: true } } },
+ }),
+ } satisfies AppStoreStub;
+ return {
+ useAppStore: (selector: (state: AppStoreStub) => unknown) => selector(state),
+ };
+});
+
+const roots: ReturnType<typeof createRoot>[] = [];
+
+afterEach(() => {
+ for (const root of roots) {
+ act(() => root.unmount());
+ }
+ roots.length = 0;
+ vi.clearAllMocks();
+});
+
+describe("useAIActions", () => {
+ test("identifies every editor context-menu action as AI", () => {
+ const addAction = vi.fn((_action: { id: string; label: string }) => ({
+ dispose: vi.fn(),
+ }));
+ const disposable = () => ({ dispose: vi.fn() });
+ const editor = {
+ addAction,
+ createContextKey: vi.fn(() => ({ set: vi.fn() })),
+ getModel: () => ({
+ getLanguageId: () => "sql",
+ getValue: () => "SELECT 1",
+ getValueInRange: () => "SELECT 1",
+ }),
+ getSelection: () => ({}),
+ onDidChangeCursorSelection: disposable,
+ onDidChangeModelContent: disposable,
+ };
+ const monaco = {} as MonacoModule;
+ const callback = vi.fn();
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ roots.push(root);
+
+ function Host() {
+ useAIActions({
+ monaco,
+ editor: editor as never,
+ actions: ["explain-code", "find-problems", "new-chat"],
+ callback,
+ });
+ return null;
+ }
+
+ act(() => root.render(<Host />));
+
+ expect(addAction.mock.calls.map(([action]) => action)).toMatchObject([
+ {
+ id: "explain-code",
+ label: "[AI] Explain code",
+ contextMenuGroupId: "2_ai_assistant",
+ },
+ {
+ id: "find-problems",
+ label: "[AI] Find problems",
+ contextMenuGroupId: "2_ai_assistant",
+ },
+ {
+ id: "new-chat-using-selection",
+ label: "[AI] New chat using selection",
+ contextMenuGroupId: "2_ai_assistant",
+ },
+ ]);
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.ts b/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.ts
index 237d529db3..3446c6e174 100644
--- a/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.ts
+++ b/frontend/src/modules/sql-editor/components/Panels/common/useAIActions.ts
@@ -1,5 +1,6 @@
import type * as monaco from "monaco-editor";
import { useEffect } from "react";
+import { useTranslation } from "react-i18next";
import type { MonacoModule } from "@/components/monaco/types";
import type { ChatAction } from "@/modules/ai/types";
import { useAppStore } from "@/stores/app";
@@ -28,6 +29,7 @@ export function useAIActions({
actions,
callback,
}: UseAIActionsOptions) {
+ const { t } = useTranslation();
const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
// Subscribe to the AI setting so the registered Monaco actions re-register
// or unregister live when an admin toggles AI access while the editor is
@@ -87,7 +89,7 @@ export function useAIActions({
subscriptions.push(
editor.addAction({
id: "explain-code",
- label: "Explain code",
+ label: `[AI] ${t("plugin.ai.actions.explain-code")}`,
precondition: "!bb.ai.contentEmpty",
contextMenuGroupId: "2_ai_assistant",
contextMenuOrder: 1,
@@ -99,7 +101,7 @@ export function useAIActions({
subscriptions.push(
editor.addAction({
id: "find-problems",
- label: "Find problems",
+ label: `[AI] ${t("plugin.ai.actions.find-problems")}`,
precondition: "!bb.ai.contentEmpty",
contextMenuGroupId: "2_ai_assistant",
contextMenuOrder: 2,
@@ -111,7 +113,7 @@ export function useAIActions({
subscriptions.push(
editor.addAction({
id: "new-chat-using-selection",
- label: "New chat using selection",
+ label: `[AI] ${t("plugin.ai.actions.new-chat-using-selection")}`,
precondition: "!bb.ai.selectedContentEmpty",
contextMenuGroupId: "2_ai_assistant",
contextMenuOrder: 2,
@@ -122,5 +124,5 @@ export function useAIActions({
return () => {
subscriptions.forEach((sub) => sub.dispose());
};
- }, [monaco, editor, aiEnabled, actions, callback]);
+ }, [monaco, editor, aiEnabled, actions, callback, t]);
}
diff --git a/frontend/src/routes/project/ProjectSyncSchemaPage.tsx b/frontend/src/routes/project/ProjectSyncSchemaPage.tsx
index 4006dd2f0e..fa277c4a5a 100644
--- a/frontend/src/routes/project/ProjectSyncSchemaPage.tsx
+++ b/frontend/src/routes/project/ProjectSyncSchemaPage.tsx
@@ -11,7 +11,6 @@ import {
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { v4 as uuidv4 } from "uuid";
import { router } from "@/app/router";
import { buildPlanCreateRoute } from "@/app/router/routeHelpers";
import { DatabaseSelect } from "@/components/DatabaseSelect";
@@ -50,7 +49,7 @@ import { StepIndicator } from "@/components/ui/step-indicator";
import { useClickOutside } from "@/hooks/useClickOutside";
import { useEscapeKey } from "@/hooks/useEscapeKey";
import { useProjectByName } from "@/hooks/useProjectByName";
-import { keyValueStorage } from "@/lib/keyValueStorage";
+import { saveInitialSQL } from "@/lib/plan/initialSQLStorage";
import { applyPlanTitleToQuery } from "@/lib/plan/title";
import { cn } from "@/lib/utils";
import { useAppStore } from "@/stores/app";
@@ -401,9 +400,16 @@ export function ProjectSyncSchemaPage({ projectId }: { projectId: string }) {
}
});
query.databaseList = Object.keys(sqlMap).join(",");
- const sqlMapStorageKey = `bb.issues.sql-map.${uuidv4()}`;
- void keyValueStorage.put(sqlMapStorageKey, sqlMap);
- query.sqlMapStorageKey = sqlMapStorageKey;
+ try {
+ query.sqlMapStorageKey = saveInitialSQL(sqlMap);
+ } catch {
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("plan.initial-sql-storage-failed"),
+ });
+ return;
+ }
if (!project) return; // defensive: should not happen if the page rendered
applyPlanTitleToQuery(query, project, () =>
generatePlanTitle(
@@ -416,7 +422,7 @@ export function ProjectSyncSchemaPage({ projectId }: { projectId: string }) {
router.push(
buildPlanCreateRoute(extractProjectResourceName(project.name), query)
);
- }, [selectedDatabaseNameList, schemaDiffCache, project]);
+ }, [selectedDatabaseNameList, schemaDiffCache, project, t]);
if (!project) return null;
diff --git a/frontend/src/routes/project/plan-detail/utils/createPlan.test.ts b/frontend/src/routes/project/plan-detail/utils/createPlan.test.ts
index 3671e93b43..5eb4a19552 100644
--- a/frontend/src/routes/project/plan-detail/utils/createPlan.test.ts
+++ b/frontend/src/routes/project/plan-detail/utils/createPlan.test.ts
@@ -1,10 +1,17 @@
import { create } from "@bufbuild/protobuf";
-import { describe, expect, test } from "vitest";
+import { beforeEach, describe, expect, test } from "vitest";
+import { saveInitialSQL } from "@/lib/plan/initialSQLStorage";
import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";
+import { getSheetStatement } from "@/utils";
import { createPlanSkeleton } from "./createPlan";
+import { getLocalSheetByName } from "./localSheet";
const project = create(ProjectSchema, { name: "projects/p" });
+beforeEach(() => {
+ localStorage.clear();
+});
+
describe("createPlanSkeleton", () => {
test("creates a change-database spec without a template query", async () => {
const plan = await createPlanSkeleton(project, {
@@ -28,4 +35,44 @@ describe("createPlanSkeleton", () => {
expect(plan.specs[0].config.case).toBe("changeDatabaseConfig");
});
+
+ test("consumes initial SQL transferred through local storage", async () => {
+ const sqlStorageKey = saveInitialSQL("ALTER TABLE users ADD active bool;");
+
+ const plan = await createPlanSkeleton(project, {
+ databaseList: "projects/p/databases/db",
+ sqlStorageKey,
+ });
+
+ const spec = plan.specs[0];
+ expect(spec.config.case).toBe("changeDatabaseConfig");
+ if (spec.config.case !== "changeDatabaseConfig") return;
+ expect(
+ getSheetStatement(getLocalSheetByName(spec.config.value.sheet))
+ ).toBe("ALTER TABLE users ADD active bool;");
+ expect(localStorage.getItem(sqlStorageKey)).toBeNull();
+ });
+
+ test("consumes per-database SQL transferred through local storage", async () => {
+ const sqlMapStorageKey = saveInitialSQL({
+ "projects/p/databases/one": "ALTER TABLE one ADD active bool;",
+ "projects/p/databases/two": "ALTER TABLE two ADD active bool;",
+ });
+
+ const plan = await createPlanSkeleton(project, {
+ databaseList: "projects/p/databases/one,projects/p/databases/two",
+ sqlMapStorageKey,
+ });
+
+ expect(
+ plan.specs.map((spec) => {
+ if (spec.config.case !== "changeDatabaseConfig") return "";
+ return getSheetStatement(getLocalSheetByName(spec.config.value.sheet));
+ })
+ ).toEqual([
+ "ALTER TABLE one ADD active bool;",
+ "ALTER TABLE two ADD active bool;",
+ ]);
+ expect(localStorage.getItem(sqlMapStorageKey)).toBeNull();
+ });
});
diff --git a/frontend/src/routes/project/plan-detail/utils/createPlan.ts b/frontend/src/routes/project/plan-detail/utils/createPlan.ts
index 4b15cacd2f..ee22e6474e 100644
--- a/frontend/src/routes/project/plan-detail/utils/createPlan.ts
+++ b/frontend/src/routes/project/plan-detail/utils/createPlan.ts
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { head } from "lodash-es";
import { v4 as uuidv4 } from "uuid";
-import { keyValueStorage } from "@/lib/keyValueStorage";
+import { consumeInitialSQL } from "@/lib/plan/initialSQLStorage";
import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
import {
Plan_ChangeDatabaseConfigSchema,
@@ -61,15 +61,15 @@ const maybeSetInitialSQLForSpec = (spec: Plan_Spec, initialSQL: InitialSQL) => {
setLocalSheetStatement(getLocalSheetByName(sheet), sql);
};
-const extractInitialSQLFromQuery = async (
+const extractInitialSQLFromQuery = (
query: Record<string, string>
-): Promise<InitialSQL> => {
+): InitialSQL => {
if (query.sql) {
return { sql: query.sql };
}
if (query.sqlStorageKey) {
return {
- sql: (await keyValueStorage.get<string>(query.sqlStorageKey)) || "",
+ sql: consumeInitialSQL<string>(query.sqlStorageKey) || "",
};
}
const sqlMapText = query.sqlMap;
@@ -86,9 +86,7 @@ const extractInitialSQLFromQuery = async (
if (query.sqlMapStorageKey) {
return {
sqlMap:
- (await keyValueStorage.get<Record<string, string>>(
- query.sqlMapStorageKey
- )) || {},
+ consumeInitialSQL<Record<string, string>>(query.sqlMapStorageKey) || {},
};
}
return {};
@@ -105,7 +103,7 @@ export const createPlanSkeleton = async (
const targets = query.databaseGroupName
? [query.databaseGroupName]
: databaseNameList;
- const initialSQL = await extractInitialSQLFromQuery(query);
+ const initialSQL = extractInitialSQLFromQuery(query);
const plan = create(PlanSchema, {
description: query.description,
name: `${project.name}/plans/${getNextLocalSheetUID()}`,
diff --git a/frontend/src/utils/blob-storage.ts b/frontend/src/utils/blob-storage.ts
deleted file mode 100644
index f5bb7a599f..0000000000
--- a/frontend/src/utils/blob-storage.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import PouchDB from "pouchdb";
-import PouchDBFind from "pouchdb-find";
-
-PouchDB.plugin(PouchDBFind);
-
-// Module-level PouchDB instance for the "bb.storage" key/value store used by
-// SQL-editor blob-passing (e.g. stashing a SQL statement for the issue/plan
-// creation page to pick up). The Pinia `useStorageStore` opens a parallel
-// PouchDB instance against the same DB name — both share the underlying
-// IndexedDB layer, so reads on one side observe writes from the other.
-const db = new PouchDB<{ _id: string; value: unknown }>("bb.storage", {
- auto_compaction: true,
- revs_limit: 1,
-});
-
-export const putBlob = async <T = unknown>(
- key: string,
- value: T
-): Promise<void> => {
- await db.put({ _id: key, value }, { force: true });
-};
-
-export const getBlob = async <T = unknown>(
- key: string
-): Promise<T | undefined> => {
- try {
- const doc = await db.get(key);
- return doc.value as T;
- } catch {
- return undefined;
- }
-};
-
-export const removeBlob = async (key: string): Promise<void> => {
- try {
- const doc = await db.get(key);
- if (doc) {
- await db.remove(doc);
- }
- } catch {
- // not found: nothing to remove
- }
-};