Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: sql editor ai chat issue (#21275)
ecmadaoa85f6cb41952
diff --git a/frontend/src/modules/ai/components/ChatPanel.test.tsx b/frontend/src/modules/ai/components/ChatPanel.test.tsxnew file mode 100644index 0000000000..c974530c37--- /dev/null+++ b/frontend/src/modules/ai/components/ChatPanel.test.tsx@@ -0,0 +1,168 @@+import { Code, ConnectError } from "@connectrpc/connect";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { AIChatMessageRole } from "@/types/proto-es/v1/ai_service_pb";+import type { Conversation, Message } from "../types";++const mocks = vi.hoisted(() => ({+ chat: vi.fn(),+ createConversation: vi.fn(),+ createMessage: vi.fn(),+ updateMessage: vi.fn(),+ emit: vi.fn(),+ setShowHistoryDialog: vi.fn(),+ setPendingSendChat: vi.fn(),+ currentConversation: undefined as Conversation | undefined,+ context: undefined as Record<string, unknown> | undefined,+}));++vi.mock("@/api", () => ({+ aiServiceClientConnect: { chat: mocks.chat },+}));++vi.mock("@/modules/sql-editor/store/tab", () => ({+ getCurrentSQLEditorTab: () => ({+ connection: {+ instance: "instances/test",+ database: "instances/test/databases/demo",+ },+ }),+ useCurrentSQLEditorTab: () => ({+ connection: {+ instance: "instances/test",+ database: "instances/test/databases/demo",+ },+ }),+}));++vi.mock("../store", () => ({+ useConversationStore: () => ({+ createConversation: mocks.createConversation,+ createMessage: mocks.createMessage,+ updateMessage: mocks.updateMessage,+ }),+}));++vi.mock("./context", () => ({+ useAIContext: () => mocks.context,+}));++vi.mock("../logic/prompt", () => ({+ declaration: () => "schema context",+}));++vi.mock("@/utils", () => ({+ nextAnimationFrame: () => Promise.resolve(),+}));++vi.mock("./ActionBar", () => ({ ActionBar: () => null }));+vi.mock("./ChatView/ChatView", () => ({ ChatView: () => null }));+vi.mock("./DynamicSuggestions", () => ({+ DynamicSuggestions: () => null,+}));+vi.mock("./HistoryPanel/HistoryPanel", () => ({ HistoryPanel: () => null }));+vi.mock("./PromptInput", () => ({+ PromptInput: ({ onEnter }: { onEnter: (value: string) => void }) => (+ <button type="button" onClick={() => onEnter("show me the tables")}>+ send+ </button>+ ),+}));++import { ChatPanel } from "./ChatPanel";++const emptyConversation = (): Conversation => ({+ id: "conversation-1",+ created_ts: 1,+ name: "",+ instance: "instances/test",+ database: "instances/test/databases/demo",+ messageList: [],+});++beforeEach(() => {+ const conversation = emptyConversation();+ mocks.currentConversation = conversation;+ mocks.chat.mockReset().mockResolvedValue({ content: "SELECT 1" });+ mocks.createConversation.mockReset();+ mocks.updateMessage.mockReset().mockResolvedValue(undefined);+ mocks.emit.mockReset();+ mocks.setShowHistoryDialog.mockReset();+ mocks.setPendingSendChat.mockReset();+ mocks.createMessage.mockReset().mockImplementation(async (input) => {+ const current = mocks.currentConversation!;+ const nextConversation: Conversation = {+ ...current,+ messageList: [...current.messageList],+ };+ const message: Message = {+ id: `message-${nextConversation.messageList.length + 1}`,+ created_ts: nextConversation.messageList.length + 1,+ ...input,+ conversation: nextConversation,+ };+ nextConversation.messageList.push(message);+ mocks.currentConversation = nextConversation;+ return message;+ });+ mocks.context = {+ aiSetting: { enabled: true },+ engine: undefined,+ databaseMetadata: undefined,+ schema: undefined,+ chat: {+ list: [conversation],+ ready: true,+ selected: conversation,+ setSelected: vi.fn(),+ },+ showHistoryDialog: false,+ setShowHistoryDialog: mocks.setShowHistoryDialog,+ pendingSendChat: undefined,+ setPendingSendChat: mocks.setPendingSendChat,+ pendingPreInput: undefined,+ setPendingPreInput: vi.fn(),+ events: { emit: mocks.emit },+ };+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("ChatPanel", () => {+ test("includes the newly persisted user message in the chat request", async () => {+ render(<ChatPanel />);++ fireEvent.click(screen.getByRole("button", { name: "send" }));++ await waitFor(() => expect(mocks.chat).toHaveBeenCalledTimes(1));+ expect(mocks.chat.mock.calls[0]?.[0].messages).toEqual([+ expect.objectContaining({+ role: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_USER,+ content: "schema context\nshow me the tables",+ }),+ ]);+ });++ test("logs the original Connect error when the chat request fails", async () => {+ const error = new ConnectError("provider unavailable", Code.Internal);+ mocks.chat.mockRejectedValue(error);+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ render(<ChatPanel />);++ fireEvent.click(screen.getByRole("button", { name: "send" }));++ await waitFor(() => expect(mocks.updateMessage).toHaveBeenCalledTimes(1));+ expect(consoleError).toHaveBeenCalledWith(+ "[AI Assistant] chat failed:",+ error+ );+ expect(mocks.updateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ status: "FAILED",+ error: "ConnectError: [internal] provider unavailable",+ })+ );+ });+});diff --git a/frontend/src/modules/ai/components/ChatPanel.tsx b/frontend/src/modules/ai/components/ChatPanel.tsxindex 162b50e87a..85c68410c4 100644--- a/frontend/src/modules/ai/components/ChatPanel.tsx+++ b/frontend/src/modules/ai/components/ChatPanel.tsx@@ -86,33 +86,26 @@ export function ChatPanel() {if (!tab) return;const { messageList } = conversation;+ let prompt = query;if (messageList.length === 0) {const engine = context.engine;const databaseMetadata = context.databaseMetadata;const schema = context.schema;- const prompts: string[] = [+ prompt = [promptUtils.declaration(databaseMetadata, engine, schema),query,- ];- const prompt = prompts.join("\n");- await store.createMessage({- conversation_id: conversation.id,- content: query,- prompt,- author: "USER",- error: "",- status: "DONE",- });+ ].join("\n");+ }+ const userMessage = await store.createMessage({+ conversation_id: conversation.id,+ content: query,+ prompt,+ author: "USER",+ error: "",+ status: "DONE",+ });+ if (messageList.length === 0) {console.debug("[AI Assistant] init chat:", prompt);- } else {- await store.createMessage({- conversation_id: conversation.id,- content: query,- prompt: query,- author: "USER",- error: "",- status: "DONE",- });}const answer = await store.createMessage({@@ -123,8 +116,8 @@ export function ChatPanel() {conversation_id: conversation.id,status: "LOADING",});- const messages: AIChatMessage[] = conversation.messageList.map(- (message) =>+ const messages: AIChatMessage[] =+ userMessage.conversation.messageList.map((message) =>createProto(AIChatMessageSchema, {role:message.author === "USER"@@ -132,7 +125,7 @@ export function ChatPanel() {: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_ASSISTANT,content: message.prompt,})- );+ );setLoading(true);try {const response = await aiServiceClientConnect.chat({ messages });@@ -144,6 +137,7 @@ export function ChatPanel() {}answer.status = "DONE";} catch (err) {+ console.error("[AI Assistant] chat failed:", err);answer.error = String(err);answer.status = "FAILED";} finally {diff --git a/frontend/src/modules/ai/components/ChatView/AIMessageView.tsx b/frontend/src/modules/ai/components/ChatView/AIMessageView.tsxindex f8fb5cfb09..c2e1b46347 100644--- a/frontend/src/modules/ai/components/ChatView/AIMessageView.tsx+++ b/frontend/src/modules/ai/components/ChatView/AIMessageView.tsx@@ -26,9 +26,9 @@ export function AIMessageView({ message }: Props) {return (<divclassName={cn(- "border rounded-sm shadow-sm py-1 px-1 bg-control-bg/80 border-control-border text-control",- isDone && "w-full min-w-36",- isFailed && "max-w-[80%] min-w-36 bg-warning/10 border-warning/60",+ "min-w-0 max-w-full border rounded-sm shadow-sm py-1 px-1 bg-control-bg/80 border-control-border text-control",+ isDone && "w-full",+ isFailed && "max-w-[80%] bg-warning/10 border-warning/60",!isDone && !isFailed && "w-auto")}>@@ -41,9 +41,9 @@ export function AIMessageView({ message }: Props) {</div>)}{isFailed && (- <div className="flex items-start gap-x-1.5">+ <div className="flex min-w-0 items-start gap-x-1.5"><TriangleAlertIcon className="mt-0.5 inline-block size-4 shrink-0 text-warning" />- <span className="break-words text-sm text-control">+ <span className="min-w-0 wrap-anywhere whitespace-pre-wrap text-sm text-control">{message.error}</span></div>diff --git a/frontend/src/modules/ai/components/ChatView/ChatView.tsx b/frontend/src/modules/ai/components/ChatView/ChatView.tsxindex 2f1f187c0e..c8c520bc9d 100644--- a/frontend/src/modules/ai/components/ChatView/ChatView.tsx+++ b/frontend/src/modules/ai/components/ChatView/ChatView.tsx@@ -61,7 +61,10 @@ export function ChatView({ mode = "CHAT", conversation }: Props) {return (<ChatViewProvider value={chatViewValue}>- <div ref={scrollerRef} className="flex-1 overflow-y-auto">+ <div+ ref={scrollerRef}+ className="min-w-0 flex-1 overflow-x-hidden overflow-y-auto"+ >{conversation ? (conversation.messageList.length === 0 ? (mode === "VIEW" ? (@@ -70,12 +73,12 @@ export function ChatView({ mode = "CHAT", conversation }: Props) {) : (<divref={containerRef}- className="flex flex-col justify-end px-2 gap-y-4"+ className="flex min-w-0 max-w-full flex-col justify-end px-2 gap-y-4">{conversation.messageList.map((message) => (<divkey={message.id}- className={`flex message ${+ className={`message flex min-w-0 w-full ${message.author === "AI" ? "justify-start" : "justify-end"}`}>diff --git a/frontend/src/modules/ai/components/ChatView/Markdown/Markdown.tsx b/frontend/src/modules/ai/components/ChatView/Markdown/Markdown.tsxindex a9a77fae8e..717b3adb8d 100644--- a/frontend/src/modules/ai/components/ChatView/Markdown/Markdown.tsx+++ b/frontend/src/modules/ai/components/ChatView/Markdown/Markdown.tsx@@ -37,11 +37,15 @@ export function Markdown({ content, codeBlockProps }: Props) {"code",{className:- "inline-block rounded-xs bg-control-bg-hover px-0.5 mx-0.5 text-control",+ "inline-block max-w-full wrap-anywhere whitespace-normal rounded-xs bg-control-bg-hover px-0.5 mx-0.5 text-control",},node.value.replace(/\r?\n|\r/g, " ")),- image: (node) => createElement("img", { src: node.url }),+ image: (node) =>+ createElement("img", {+ src: node.url,+ className: "h-auto max-w-full",+ }),}),[codeBlockProps]);diff --git a/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts b/frontend/src/modules/ai/components/ChatView/Markdown/utils.tsindex fe8c0c8a4a..e6ddd36ef0 100644--- a/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts+++ b/frontend/src/modules/ai/components/ChatView/Markdown/utils.ts@@ -102,7 +102,7 @@ function defaultMdNodeToReact(node: RootContent, state: State): ReactNode {function rootToReact(node: Root, state: State): ReactNode {return createElement("div",- { className: "markdown" },+ { className: "markdown min-w-0 max-w-full wrap-anywhere" },mapChildren(node.children, state));}@@ -169,12 +169,16 @@ function htmlToReact(node: RootContentMap["html"]): ReactNode {type ImageProps = {src: string;+ className: string;alt?: string;title?: string;};function imageToReact(node: RootContentMap["image"]): ReactNode {- const props: ImageProps = { src: normalizeUri(node.url) };+ const props: ImageProps = {+ src: normalizeUri(node.url),+ className: "h-auto max-w-full",+ };if (node.alt) props.alt = node.alt;if (node.title) props.title = node.title;return createElement("img", props);@@ -218,7 +222,10 @@ function imageReferenceToReact(if (!definition) {return referenceToText(node, state);}- const props: ImageProps = { src: normalizeUri(definition.url || "") };+ const props: ImageProps = {+ src: normalizeUri(definition.url || ""),+ className: "h-auto max-w-full",+ };if (node.alt) props.alt = node.alt;if (definition.title) props.title = definition.title;return createElement("img", props);@@ -364,7 +371,7 @@ function tableToReact(node: RootContentMap["table"], state: State): ReactNode {if (bodyRows.length > 0) {sections.push(createElement("tbody", { key: "tbody" }, bodyRows));}- return createElement("table", null, sections);+ return createElement("table", { className: "w-full table-fixed" }, sections);}function textToReact(node: RootContentMap["text"]): ReactNode {diff --git a/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsx b/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsxnew file mode 100644index 0000000000..bb26b917ac--- /dev/null+++ b/frontend/src/modules/ai/components/ChatView/MessageWrapping.test.tsx@@ -0,0 +1,96 @@+import { render } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import type { Conversation, Message } from "../../types";+import { AIMessageView } from "./AIMessageView";+import { UserMessageView } from "./UserMessageView";++vi.mock("./Markdown/CodeBlock", () => ({+ CodeBlock: () => <div data-testid="code-block" />,+}));++const longContent =+ "https://example.com/" + "unbroken-path-segment".repeat(20);++function createMessage(+ author: Message["author"],+ status: Message["status"],+ overrides: Partial<Message> = {}+): Message {+ const conversation: Conversation = {+ id: "conversation-1",+ created_ts: 1,+ name: "Test",+ instance: "instances/test",+ database: "instances/test/databases/test",+ messageList: [],+ };+ const message: Message = {+ id: "message-1",+ created_ts: 1,+ author,+ content: longContent,+ prompt: longContent,+ status,+ error: "",+ conversation,+ ...overrides,+ };+ conversation.messageList.push(message);+ return message;+}++describe("AI chat message wrapping", () => {+ test.each([+ ["AI", AIMessageView],+ ["USER", UserMessageView],+ ] as const)("keeps long %s content inside the message bubble", (_, View) => {+ const message = createMessage(+ View === AIMessageView ? "AI" : "USER",+ "DONE"+ );+ const { container } = render(<View message={message} />);++ const bubble = container.firstElementChild;+ const markdown = container.querySelector(".markdown");+ expect(bubble?.className).toContain("min-w-0");+ expect(bubble?.className).toContain(+ View === AIMessageView ? "max-w-full" : "max-w-[60%]"+ );+ expect(markdown?.className).toContain("wrap-anywhere");+ expect(markdown?.className).toContain("min-w-0");+ expect(markdown?.textContent).toContain(longContent);+ });++ test("wraps long provider errors inside the failed message bubble", () => {+ const message = createMessage("AI", "FAILED", { error: longContent });+ const { container } = render(<AIMessageView message={message} />);++ const bubble = container.firstElementChild;+ const error = container.querySelector("span");+ expect(bubble?.className).toContain("min-w-0");+ expect(bubble?.className).toContain("max-w-[80%]");+ expect(error?.className).toContain("min-w-0");+ expect(error?.className).toContain("wrap-anywhere");+ expect(error?.textContent).toBe(longContent);+ });++ test("constrains inline code, images, and tables to the message width", () => {+ const content = [+ `\`${longContent}\``,+ ``,+ [`| ${longContent} |`, "| --- |", `| ${longContent} |`].join("\n"),+ ].join("\n\n");+ const message = createMessage("USER", "DONE", { content });+ const { container } = render(<UserMessageView message={message} />);++ const inlineCode = container.querySelector("code");+ expect(inlineCode?.className).toContain("max-w-full");+ expect(inlineCode?.className).toContain("wrap-anywhere");+ expect(inlineCode?.className).toContain("whitespace-normal");+ expect(container.querySelector("img")?.className).toContain("max-w-full");+ expect(container.querySelector("table")?.className).toContain("w-full");+ expect(container.querySelector("table")?.className).toContain(+ "table-fixed"+ );+ });+});diff --git a/frontend/src/modules/ai/components/ChatView/UserMessageView.tsx b/frontend/src/modules/ai/components/ChatView/UserMessageView.tsxindex 515181c959..c181dba7c0 100644--- a/frontend/src/modules/ai/components/ChatView/UserMessageView.tsx+++ b/frontend/src/modules/ai/components/ChatView/UserMessageView.tsx@@ -12,7 +12,7 @@ type Props = {*/export function UserMessageView({ message }: Props) {return (- <div className="user-message max-w-[60%] min-w-36 border rounded-sm shadow-sm py-1 px-2 bg-accent/15 border-accent/50 text-control">+ <div className="user-message min-w-0 max-w-[60%] border rounded-sm shadow-sm py-1 px-2 bg-accent/15 border-accent/50 text-control"><Markdown content={message.content} codeBlockProps={{ width: 0.6 }} /></div>);diff --git a/frontend/src/modules/ai/store/conversation.test.ts b/frontend/src/modules/ai/store/conversation.test.tsnew file mode 100644index 0000000000..9b67b78b46--- /dev/null+++ b/frontend/src/modules/ai/store/conversation.test.ts@@ -0,0 +1,144 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++type StoredDocument = Record<string, unknown> & {+ _id: string;+ _rev?: string;+};++const pouch = vi.hoisted(() => ({+ databases: new Map<string, Map<string, StoredDocument>>(),+}));++vi.mock("pouchdb", () => {+ class MockPouchDB {+ static plugin() {}++ constructor(private readonly name: string) {+ if (!pouch.databases.has(name)) {+ pouch.databases.set(name, new Map());+ }+ }++ private get documents() {+ return pouch.databases.get(this.name)!;+ }++ async createIndex() {}++ async find({ selector }: { selector: Record<string, unknown> }) {+ const docs = [...this.documents.values()].filter((document) =>+ Object.entries(selector).every(([field, condition]) => {+ const value = document[field];+ const matcher = condition as { $eq?: unknown; $in?: unknown[] };+ if ("$eq" in matcher) return value === matcher.$eq;+ if ("$in" in matcher) return matcher.$in?.includes(value) ?? false;+ return value === condition;+ })+ );+ return { docs };+ }++ async get(id: string) {+ const document = this.documents.get(id);+ if (!document) throw new Error("missing");+ return { ...document };+ }++ async put(document: StoredDocument) {+ const existing = this.documents.get(document._id);+ if (existing && document._rev !== existing._rev) {+ const error = new Error("Document update conflict") as Error & {+ status: number;+ };+ error.status = 409;+ throw error;+ }+ const generation = existing+ ? Number(existing._rev?.split("-")[0]) + 1+ : 1;+ const rev = `${generation}-test`;+ this.documents.set(document._id, { ...document, _rev: rev });+ return { id: document._id, ok: true, rev };+ }++ async bulkDocs(documents: StoredDocument[]) {+ return Promise.all(documents.map((document) => this.put(document)));+ }++ async destroy() {+ this.documents.clear();+ }+ }++ return { default: MockPouchDB };+});++vi.mock("pouchdb-find", () => ({ default: {} }));++import { useConversationStore } from "./conversation";++const connection = {+ instance: "instances/test",+ database: "instances/test/databases/demo",+};++beforeEach(() => {+ for (const documents of pouch.databases.values()) {+ documents.clear();+ }+ useConversationStore.setState({+ conversationsById: {},+ readyByConnection: {},+ });+});++describe("AI conversation persistence", () => {+ test("removing an empty conversation during reload does not conflict", async () => {+ await useConversationStore.getState().createConversation({+ ...connection,+ name: "",+ });+ useConversationStore.setState({+ conversationsById: {},+ readyByConnection: {},+ });++ const conversations = await useConversationStore+ .getState()+ .fetchConversationListByConnection(connection as never);++ expect(conversations).toEqual([]);+ expect(useConversationStore.getState().conversationsById).toEqual({});+ });++ test("reload marks an interrupted response as failed", async () => {+ const conversation = await useConversationStore+ .getState()+ .createConversation({ ...connection, name: "" });+ await useConversationStore.getState().createMessage({+ author: "AI",+ content: "",+ prompt: "",+ error: "",+ status: "LOADING",+ conversation_id: conversation.id,+ });+ useConversationStore.setState({+ conversationsById: {},+ readyByConnection: {},+ });++ const conversations = await useConversationStore+ .getState()+ .fetchConversationListByConnection(connection as never);++ expect(conversations[0]?.messageList[0]).toMatchObject({+ status: "FAILED",+ error: "Request timeout",+ });+ expect(+ useConversationStore.getState().conversationsById[conversation.id]+ ?.messageList[0]+ ).toMatchObject({ status: "FAILED", error: "Request timeout" });+ });+});diff --git a/frontend/src/modules/ai/store/conversation.ts b/frontend/src/modules/ai/store/conversation.tsindex 6b84377d02..e00be86d9f 100644--- a/frontend/src/modules/ai/store/conversation.ts+++ b/frontend/src/modules/ai/store/conversation.ts@@ -48,6 +48,15 @@ const conversations = new PouchDB<ConversationEntity>("bb.plugin.ai.conversations");const messages = new PouchDB<MessageEntity>("bb.plugin.ai.messages");++const putExisting = async <T extends { _id: string }>(+ database: PouchDB.Database<T>,+ entity: T+) => {+ const current = await database.get(entity._id);+ return database.put({ ...entity, _rev: current._rev });+};+const ready: Promise<unknown>[] = [];ready.push(messages.createIndex({@@ -113,17 +122,19 @@ export const useConversationStore = create<ConversationState>((set, get) => {const conversation = get().conversationsById[id];if (!conversation) return;if (conversation.messageList.length > 0) {- await messages.bulkDocs(- conversation.messageList.map((message) => ({- ...convertMessageToEntity(message),- row_status: "ARCHIVED" as const,- }))+ await Promise.all(+ conversation.messageList.map((message) =>+ putExisting(messages, {+ ...convertMessageToEntity(message),+ row_status: "ARCHIVED" as const,+ })+ ));}- await conversations.put(- { ...convertConversationToEntity(conversation), row_status: "ARCHIVED" },- { force: true }- );+ await putExisting(conversations, {+ ...convertConversationToEntity(conversation),+ row_status: "ARCHIVED",+ });set((state) => {const next = { ...state.conversationsById };delete next[id];@@ -132,7 +143,7 @@ export const useConversationStore = create<ConversationState>((set, get) => {};const updateMessage = async (message: Message): Promise<Message> => {- await messages.put(convertMessageToEntity(message), { force: true });+ await putExisting(messages, convertMessageToEntity(message));const conversation = get().conversationsById[message.conversation.id];if (conversation) {const nextConversation: Conversation = {@@ -154,13 +165,11 @@ export const useConversationStore = create<ConversationState>((set, get) => {const fixAbnormalMessages = async (messageList: Message[]) => {const requests = messageList.filter((message) => message.status === "LOADING")- .map((message) =>- updateMessage({- ...message,- status: "FAILED",- error: "Request timeout",- })- );+ .map((message) => {+ message.status = "FAILED";+ message.error = "Request timeout";+ return updateMessage(message);+ });await Promise.all(requests);};@@ -245,9 +254,7 @@ export const useConversationStore = create<ConversationState>((set, get) => {const updateConversation = async (conversation: Conversation): Promise<Conversation> => {- await conversations.put(convertConversationToEntity(conversation), {- force: true,- });+ await putExisting(conversations, convertConversationToEntity(conversation));const existing = get().conversationsById[conversation.id];const next: Conversation = {...conversation,