Skip to content

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

feat(sql-editor): chat-to-sql demo v2 (#5061)

Liu Ji177a5d4e3ff3
diff --git a/backend/legacyapi/plan.go b/backend/legacyapi/plan.go
index 3afa6726ce..c3ca9e2b2a 100644
--- a/backend/legacyapi/plan.go
+++ b/backend/legacyapi/plan.go
@@ -155,6 +155,8 @@ const (
FeatureSensitiveData FeatureType = "bb.feature.sensitive-data"
// FeatureAccessControl allows user to config the access control.
FeatureAccessControl FeatureType = "bb.feature.access-control"
+ // FeaturePluginOpenAI enables AI features powered by OpenAI.
+ FeaturePluginOpenAI FeatureType = "bb.feature.plugin.openai"
)
// Name returns a readable name of the feature.
@@ -218,6 +220,8 @@ func (e FeatureType) Name() string {
return "Sensitive data"
case FeatureAccessControl:
return "Access Control"
+ case FeaturePluginOpenAI:
+ return "OpenAI"
}
return ""
}
@@ -274,6 +278,8 @@ var FeatureMatrix = map[FeatureType][3]bool{
FeatureEnvironmentTierPolicy: {false, false, true},
FeatureSensitiveData: {false, false, true},
FeatureAccessControl: {false, false, true},
+ // Plugins
+ FeaturePluginOpenAI: {false, false, true},
}
// Plan is the API message for a plan.
diff --git a/frontend/src/bbkit/BBTextField.vue b/frontend/src/bbkit/BBTextField.vue
index 569aadb4ab..a7b5606059 100644
--- a/frontend/src/bbkit/BBTextField.vue
+++ b/frontend/src/bbkit/BBTextField.vue
@@ -4,7 +4,7 @@
v-model="state.text"
type="text"
autocomplete="off"
- class="text-main rounded-md"
+ class="text-main rounded-md placeholder:text-control-placeholder"
:class="
state.hasError
? 'border-error focus:ring-error focus:border-error'
diff --git a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue
new file mode 100644
index 0000000000..23b05e1905
--- /dev/null
+++ b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue
@@ -0,0 +1,131 @@
+<template>
+ <div class="px-4 py-6 lg:flex">
+ <div class="text-left lg:w-1/4">
+ <h1 class="text-2xl font-bold">
+ {{ $t("settings.general.workspace.plugin.openai.ai-augmentation") }}
+ </h1>
+ <span v-if="!allowEdit" class="text-sm text-gray-400">
+ {{ $t("settings.general.workspace.only-owner-can-edit") }}
+ </span>
+ </div>
+ <div class="flex-1 lg:px-5">
+ <div class="mb-7 mt-5 lg:mt-0">
+ <label
+ class="flex items-center gap-x-2 tooltip-wrapper"
+ :class="[allowEdit ? 'cursor-pointer' : 'cursor-not-allowed']"
+ >
+ <span class="font-medium">{{
+ $t("settings.general.workspace.plugin.openai.openai-key.self")
+ }}</span>
+
+ <span
+ v-if="!allowEdit"
+ class="text-sm text-gray-400 -translate-y-2 tooltip"
+ >
+ {{ $t("settings.general.workspace.only-owner-can-edit") }}
+ </span>
+ </label>
+ <div class="mb-3 text-sm text-gray-400">
+ <i18n-t
+ keypath="settings.general.workspace.plugin.openai.openai-key.description"
+ >
+ <template #viewDoc>
+ <a
+ href="https://platform.openai.com/docs/introduction/overview"
+ class="normal-link"
+ target="_blank"
+ >{{ $t("common.view-doc") }}</a
+ >
+ </template>
+ </i18n-t>
+ </div>
+ <BBTextField
+ class="mb-5 w-full"
+ :disabled="!allowEdit"
+ :value="state.openAIKey"
+ :placeholder="
+ $t(
+ 'settings.general.workspace.plugin.openai.openai-key.placeholder'
+ )
+ "
+ @input="handleOpenAIKeyChange"
+ />
+ <div class="flex">
+ <button
+ type="button"
+ class="btn-primary ml-auto"
+ :disabled="!allowSave"
+ @click.prevent="updateOpenAIKey"
+ >
+ {{ $t("common.update") }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive, watchEffect } from "vue";
+import {
+ pushNotification,
+ useCurrentUser,
+ useSettingByName,
+ useSettingStore,
+} from "@/store";
+import { hasWorkspacePermission } from "@/utils";
+import { useI18n } from "vue-i18n";
+
+interface LocalState {
+ openAIKey: string;
+}
+
+const { t } = useI18n();
+const settingStore = useSettingStore();
+const currentUser = useCurrentUser();
+
+const state = reactive<LocalState>({
+ openAIKey: "",
+});
+
+const openAIKeySetting = useSettingByName("bb.plugin.openai.key");
+
+watchEffect(() => {
+ state.openAIKey = openAIKeySetting.value?.value ?? "";
+});
+
+const allowEdit = computed((): boolean => {
+ return hasWorkspacePermission(
+ "bb.permission.workspace.manage-general",
+ currentUser.value.role
+ );
+});
+
+const allowSave = computed((): boolean => {
+ return (
+ allowEdit.value &&
+ state.openAIKey !== "" &&
+ state.openAIKey !== openAIKeySetting.value?.value
+ );
+});
+
+const handleOpenAIKeyChange = (event: InputEvent) => {
+ state.openAIKey = (event.target as HTMLInputElement).value;
+};
+
+const updateOpenAIKey = async () => {
+ if (!allowSave.value) {
+ return;
+ }
+
+ await settingStore.updateSettingByName({
+ name: "bb.plugin.openai.key",
+ value: state.openAIKey,
+ });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("settings.general.workspace.config-updated"),
+ });
+};
+</script>
diff --git a/frontend/src/components/GeneralSetting/index.ts b/frontend/src/components/GeneralSetting/index.ts
index 2eb3be2f56..f3623aacfb 100644
--- a/frontend/src/components/GeneralSetting/index.ts
+++ b/frontend/src/components/GeneralSetting/index.ts
@@ -1,5 +1,11 @@
import BrandingSetting from "./BrandingSetting.vue";
import SecuritySetting from "./SecuritySetting.vue";
import NetworkSetting from "./NetworkSetting.vue";
+import AIAugmentationSetting from "./AIAugmentationSetting.vue";
-export { BrandingSetting, SecuritySetting, NetworkSetting };
+export {
+ BrandingSetting,
+ SecuritySetting,
+ NetworkSetting,
+ AIAugmentationSetting,
+};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index e610a9794c..2eb0a95f25 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -481,7 +481,17 @@
"self": "External URL",
"description": "The external URL where user visits Bytebase, must start with http:// or https://. {viewDoc}"
},
- "config-updated": "Configuration is updated"
+ "config-updated": "Configuration is updated",
+ "plugin": {
+ "openai": {
+ "ai-augmentation": "AI augmentation",
+ "openai-key": {
+ "self": "OpenAI key",
+ "description": "Supply OpenAI key to enable chat to SQL capability in SQL Editor. {viewDoc}",
+ "placeholder": "An OpenAI Key usually starts with sk-*****"
+ }
+ }
+ }
}
},
"sensitive-data": {
@@ -1999,7 +2009,12 @@
"untitled": "Untitled conversation",
"delete": "Delete conversation",
"rename": "Rename conversation",
- "select-or-create": "Select or {create} a conversation to start."
+ "select-or-create": "Select or {create} a conversation to start.",
+ "exit-conversation-mode": "Exit chat mode",
+ "history-conversations": "History conversations",
+ "view-history-conversations": "View history conversations",
+ "new-conversation": "Start new conversation",
+ "no-message": "No message in this conversation"
},
"preset-suggestion": {
"1": "Which department has most employees?",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index bf1a9d6c1c..4c007f120c 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -479,7 +479,17 @@
"self": "外部链接",
"description": "用户或回调能访问到的 Bytebase URL,必须以 http:// 或 https:// 开头。{viewDoc}"
},
- "config-updated": "配置已更新"
+ "config-updated": "配置已更新",
+ "plugin": {
+ "openai": {
+ "ai-augmentation": "AI 增强",
+ "openai-key": {
+ "self": "OpenAI 密钥",
+ "description": "提供 OpenAI 密钥以在 SQL 编辑器中开启聊天转 SQL 的能力。{viewDoc}",
+ "placeholder": "OpenAI 密钥通常以 sk-***** 开头"
+ }
+ }
+ }
}
},
"sensitive-data": {
@@ -1998,7 +2008,10 @@
"untitled": "未命名会话",
"delete": "删除会话",
"rename": "修改会话名称",
- "select-or-create": "选择或{create}一个会话以开始。"
+ "select-or-create": "选择或{create}一个会话以开始。",
+ "exit-conversation-mode": "退出对话模式",
+ "view-history-conversations": "查看历史对话",
+ "new-conversation": "开启新对话"
},
"preset-suggestion": {
"1": "哪个部门的员工最多?",
diff --git a/frontend/src/plugins/ai/components/AIChatToSQL.vue b/frontend/src/plugins/ai/components/AIChatToSQL.vue
new file mode 100644
index 0000000000..af1406dbe0
--- /dev/null
+++ b/frontend/src/plugins/ai/components/AIChatToSQL.vue
@@ -0,0 +1,69 @@
+<template>
+ <ChatPanel v-if="openAIKey" />
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive, toRef } from "vue";
+import Emittery from "emittery";
+import { useLocalStorage } from "@vueuse/core";
+
+import type { AIContextEvents } from "../types";
+import { useChatByTab, provideAIContext } from "../logic";
+import {
+ useCurrentTab,
+ useInstanceById,
+ useMetadataByDatabaseId,
+ useSettingByName,
+} from "@/store";
+import ChatPanel from "./ChatPanel.vue";
+import { Connection } from "@/types";
+
+type LocalState = {
+ showHistoryDialog: boolean;
+};
+
+const emit = defineEmits<{
+ (
+ event: "apply-statement",
+ statement: string,
+ conn: Connection,
+ run: boolean
+ ): void;
+}>();
+
+const state = reactive<LocalState>({
+ showHistoryDialog: false,
+});
+
+const openAIKeySetting = useSettingByName("bb.plugin.openai.key");
+const openAIKey = computed(() => openAIKeySetting.value?.value ?? "");
+const tab = useCurrentTab();
+
+const instance = useInstanceById(
+ computed(() => tab.value.connection.instanceId)
+);
+const databaseMetadata = useMetadataByDatabaseId(
+ computed(() => tab.value.connection.databaseId),
+ false /* !skipCache */
+);
+
+const events: AIContextEvents = new Emittery();
+
+events.on("apply-statement", ({ statement, run }) => {
+ emit("apply-statement", statement, tab.value.connection, run);
+});
+
+const autoRun = useLocalStorage("bb.plugin.ai.auto-run", true);
+
+const chat = useChatByTab();
+
+provideAIContext({
+ openAIKey,
+ engineType: computed(() => instance.value.engine),
+ databaseMetadata: databaseMetadata,
+ autoRun,
+ showHistoryDialog: toRef(state, "showHistoryDialog"),
+ chat,
+ events,
+});
+</script>
diff --git a/frontend/src/plugins/ai/components/AIPromptButton.vue b/frontend/src/plugins/ai/components/AIPromptButton.vue
deleted file mode 100644
index 307884d447..0000000000
--- a/frontend/src/plugins/ai/components/AIPromptButton.vue
+++ /dev/null
@@ -1,76 +0,0 @@
-<template>
- <button
- v-if="openAIKey"
- class="w-full flex items-center gap-x-1 rounded-[3px] border border-control-border bg-white hover:bg-gray-100 pl-2 pr-1 py-1.5 outline-none"
- @click="state.showDialog = true"
- >
- <heroicons-outline:sparkles class="w-4 h-4 text-accent" />
- <span class="text-control-placeholder flex-1 text-left text-sm">
- {{ $t("plugin.ai.text-to-sql-placeholder") }}
- </span>
-
- <AIDialog v-if="state.showDialog" @close="state.showDialog = false" />
- </button>
-</template>
-
-<script lang="ts" setup>
-import { computed, reactive, toRef } from "vue";
-
-import AIDialog from "./AIDialog.vue";
-import type { AIContextEvents } from "../types";
-import { DatabaseMetadata } from "@/types/proto/store/database";
-import type { EngineType } from "@/types";
-import Emittery from "emittery";
-import { provideAIContext } from "../logic";
-import { useLocalStorage } from "@vueuse/core";
-import { useSettingByName } from "@/store";
-
-type LocalState = {
- showDialog: boolean;
-};
-
-const props = withDefaults(
- defineProps<{
- engineType?: EngineType;
- databaseMetadata?: DatabaseMetadata;
- }>(),
- {
- engineType: undefined,
- databaseMetadata: undefined,
- }
-);
-
-const emit = defineEmits<{
- (event: "apply-statement", statement: string, run: boolean): void;
- (event: "error", error: string): void;
- (event: "update:loading", loading: boolean): void;
-}>();
-
-const state = reactive<LocalState>({
- showDialog: false,
-});
-
-const openAIKeySetting = useSettingByName("bb.plugin.openai.key");
-const openAIKey = computed(() => openAIKeySetting.value?.value ?? "");
-
-const events: AIContextEvents = new Emittery();
-
-events.on("apply-statement", ({ statement, run }) => {
- emit("apply-statement", statement, run);
- state.showDialog = false;
-});
-events.on("error", (error) => {
- emit("error", error);
-});
-
-const autoRun = useLocalStorage("bb.plugin.ai.auto-run", true);
-
-provideAIContext({
- showDialog: toRef(state, "showDialog"),
- openAIKey,
- engineType: toRef(props, "engineType"),
- databaseMetadata: toRef(props, "databaseMetadata"),
- autoRun,
- events,
-});
-</script>
diff --git a/frontend/src/plugins/ai/components/ActionBar.vue b/frontend/src/plugins/ai/components/ActionBar.vue
new file mode 100644
index 0000000000..12359e49f9
--- /dev/null
+++ b/frontend/src/plugins/ai/components/ActionBar.vue
@@ -0,0 +1,44 @@
+<template>
+ <div
+ class="w-full flex flex-wrap gap-y-2 justify-between sm:items-center p-4 border-b bg-white"
+ >
+ <div
+ class="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center"
+ >
+ <NButton @click="tab.editMode = 'SQL-EDITOR'">
+ <template #icon>
+ <heroicons:chevron-left />
+ </template>
+ <span>{{ $t("plugin.ai.conversation.exit-conversation-mode") }}</span>
+ </NButton>
+ </div>
+
+ <div
+ class="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center"
+ >
+ <NButton @click="showHistoryDialog = true">
+ <template #icon>
+ <heroicons:clock />
+ </template>
+ <span>{{
+ $t("plugin.ai.conversation.view-history-conversations")
+ }}</span>
+ </NButton>
+ <NButton @click="events.emit('new-conversation')">
+ <template #icon>
+ <heroicons:plus />
+ </template>
+ <span>{{ $t("plugin.ai.conversation.new-conversation") }}</span>
+ </NButton>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { useCurrentTab } from "@/store";
+import { useAIContext } from "../logic";
+
+const tab = useCurrentTab();
+
+const { events, showHistoryDialog } = useAIContext();
+</script>
diff --git a/frontend/src/plugins/ai/components/AIDialog.vue b/frontend/src/plugins/ai/components/ChatPanel.vue
similarity index 60%
rename from frontend/src/plugins/ai/components/AIDialog.vue
rename to frontend/src/plugins/ai/components/ChatPanel.vue
index e7b2321d26..dba3a4f66b 100644
--- a/frontend/src/plugins/ai/components/AIDialog.vue
+++ b/frontend/src/plugins/ai/components/ChatPanel.vue
@@ -1,68 +1,76 @@
<template>
- <BBModal class="!pb-0" container-class="!p-0" @close="$emit('close')">
- <div
- class="h-[calc(100vh-10rem)] w-[calc(100vw-8rem)] max-w-[72rem] px-8 pb-4 flex"
- >
- <aside class="hidden lg:flex lg:flex-col w-[14em] border-l border-b">
- <ConversationList />
- </aside>
-
- <div class="flex-1 flex flex-col bg-gray-100">
- <ChatView @enter="requestAI" />
-
- <div class="px-2 py-2">
- <div>
- <label class="inline-flex items-center gap-x-1">
- <BBCheckbox :value="autoRun" @toggle="autoRun = $event" />
- <span class="textinfolabel">
- {{ $t("plugin.ai.run-automatically") }}
- </span>
- </label>
- </div>
- <PromptInput :disabled="state.loading" @enter="requestAI" />
- </div>
+ <div
+ v-if="openAIKey"
+ class="w-full flex flex-col"
+ :class="[
+ !isChatMode && 'px-4 py-2 border-t',
+ isChatMode && 'flex-1 overflow-hidden',
+ ]"
+ >
+ <template v-if="isChatMode">
+ <ActionBar />
+ <ChatView :conversation="selectedConversation" @enter="requestAI" />
+ </template>
+
+ <div :class="[isChatMode && 'px-4 py-2']">
+ <div v-if="isChatMode">
+ <label class="inline-flex items-center gap-x-1">
+ <BBCheckbox :value="autoRun" @toggle="autoRun = $event" />
+ <span class="textinfolabel">
+ {{ $t("plugin.ai.run-automatically") }}
+ </span>
+ </label>
</div>
+ <PromptInput @focus="tab.editMode = 'CHAT-TO-SQL'" @enter="requestAI" />
</div>
- </BBModal>
+
+ <template v-if="isChatMode">
+ <HistoryPanel v-if="showHistoryDialog" />
+ </template>
+ </div>
</template>
<script lang="ts" setup>
-import { reactive, toRef } from "vue";
-import { Axios, AxiosResponse } from "axios";
+import { computed, reactive, watch } from "vue";
import { head } from "lodash-es";
+import { Axios, AxiosResponse } from "axios";
-import { BBCheckbox, BBModal } from "@/bbkit";
-import { useAIContext } from "../logic";
-import type { OpenAIMessage, OpenAIResponse } from "../types";
-import ConversationList from "./ConversationList.vue";
+import { BBCheckbox } from "@/bbkit";
+import { useCurrentTab } from "@/store";
+import { useConversationStore } from "../store";
+import ActionBar from "./ActionBar.vue";
import ChatView from "./ChatView";
import PromptInput from "./PromptInput.vue";
-import { useConversationStore } from "../store";
+import HistoryPanel from "./HistoryPanel";
+import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";
+import { OpenAIMessage, OpenAIResponse } from "../types";
type LocalState = {
loading: boolean;
};
-defineEmits<{
- (event: "close"): void;
-}>();
-
const state = reactive<LocalState>({
loading: false,
});
-const context = useAIContext();
-
-const { showDialog, openAIKey, autoRun } = context;
-
+const tab = useCurrentTab();
const store = useConversationStore();
-const conversation = toRef(store, "selectedConversation");
+const isChatMode = computed(() => tab.value.editMode === "CHAT-TO-SQL");
+
+const context = useAIContext();
+const { events, openAIKey, autoRun, showHistoryDialog } = context;
+const {
+ list: conversationList,
+ ready,
+ selected: selectedConversation,
+} = useCurrentChat();
const requestAI = async (query: string) => {
- const c = conversation.value;
- if (!c) return;
+ const conversation = selectedConversation.value;
+ if (!conversation) return;
+ const t = tab.value;
- const { messageList } = c;
+ const { messageList } = conversation;
if (messageList.length === 0) {
// For the first message of a conversation,
// add extra database schema metadata info if possible
@@ -95,7 +103,7 @@ const requestAI = async (query: string) => {
prompts.push(`### ${query}`);
const prompt = prompts.join("\n");
await store.createMessage({
- conversation_id: c.id,
+ conversation_id: conversation.id,
content: query,
prompt,
author: "USER",
@@ -104,7 +112,7 @@ const requestAI = async (query: string) => {
});
} else {
await store.createMessage({
- conversation_id: c.id,
+ conversation_id: conversation.id,
content: query,
prompt: query,
author: "USER",
@@ -118,14 +126,14 @@ const requestAI = async (query: string) => {
prompt: "SELECT",
content: "",
error: "",
- conversation_id: c.id,
+ conversation_id: conversation.id,
status: "LOADING",
});
const url = "https://api.openai.com/v1/chat/completions";
const FINAL_PROMPT = "SELECT";
const messages: OpenAIMessage[] = [];
- c.messageList.forEach((message) => {
+ conversation.messageList.forEach((message) => {
const { author, prompt } = message;
messages.push({
role: author === "USER" ? "user" : "assistant",
@@ -183,11 +191,16 @@ const requestAI = async (query: string) => {
} finally {
state.loading = false;
await store.updateMessage(answer);
- if (c.id === conversation.value?.id) {
+ if (conversation.id === conversation.id) {
if (answer.status === "FAILED") {
context.events.emit("error", answer.error);
} else {
- if (showDialog.value && autoRun.value) {
+ if (
+ autoRun.value &&
+ t.id === tab.value.id &&
+ conversation.id === selectedConversation.value?.id
+ ) {
+ // If the chat is still active, emit 'apply-statement' event
context.events.emit("apply-statement", {
statement: answer.content,
run: autoRun.value,
@@ -197,4 +210,30 @@ const requestAI = async (query: string) => {
}
}
};
+
+onConnectionChanged(() => {
+ showHistoryDialog.value = false;
+});
+
+events.on("new-conversation", async () => {
+ showHistoryDialog.value = false;
+ const c = await store.createConversation({
+ name: "",
+ ...tab.value.connection,
+ });
+ selectedConversation.value = c;
+});
+
+watch(
+ [ready, conversationList],
+ async ([ready, list]) => {
+ if (ready && list.length === 0) {
+ store.createConversation({
+ name: "",
+ ...tab.value.connection,
+ });
+ }
+ },
+ { immediate: true }
+);
</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
index b44f3f3c44..215327af06 100644
--- a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
+++ b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
@@ -3,7 +3,7 @@
class="border rounded shadow py-1 px-1 bg-gray-100 border-gray-400"
:class="[
message.status === 'DONE'
- ? 'w-[60%]'
+ ? 'w-[80%]'
: message.status === 'FAILED'
? 'max-w-[60%]'
: 'w-auto',
diff --git a/frontend/src/plugins/ai/components/ChatView/ChatView.vue b/frontend/src/plugins/ai/components/ChatView/ChatView.vue
index 633d5d9b27..713c0bec1f 100644
--- a/frontend/src/plugins/ai/components/ChatView/ChatView.vue
+++ b/frontend/src/plugins/ai/components/ChatView/ChatView.vue
@@ -1,14 +1,17 @@
<template>
<div ref="scrollerRef" class="flex-1 py-4 overflow-y-auto">
<template v-if="conversation">
- <PresetSuggestions
- v-if="conversation.messageList.length === 0"
- @select="$emit('enter', $event)"
- />
+ <template v-if="conversation.messageList.length === 0">
+ <PresetSuggestions
+ v-if="mode === 'CHAT'"
+ @select="$emit('enter', $event)"
+ />
+ <EmptyView v-if="mode === 'VIEW'" />
+ </template>
<div
v-else
ref="containerRef"
- class="flex flex-col justify-end px-2 gap-y-8"
+ class="flex flex-col justify-end px-4 gap-y-8"
>
<div
v-for="message in conversation?.messageList"
@@ -24,7 +27,7 @@
</div>
</div>
</template>
- <template v-else>
+ <template v-else-if="mode === 'CHAT'">
<div
class="w-full h-full flex flex-col justify-end items-center pb-[2rem]"
>
@@ -34,7 +37,10 @@
class="textinfolabel"
>
<template #create>
- <button class="normal-link" @click="handleCreate">
+ <button
+ class="normal-link"
+ @click="events.emit('new-conversation')"
+ >
{{ $t("common.create") }}
</button>
</template>
@@ -48,10 +54,25 @@
import { ref, toRef, watch } from "vue";
import { useElementSize } from "@vueuse/core";
+import type { Conversation } from "../../types";
+import type { Mode } from "./types";
import UserMessageView from "./UserMessageView.vue";
import AIMessageView from "./AIMessageView.vue";
import PresetSuggestions from "./PresetSuggestions.vue";
-import { useConversationStore } from "../../store";
+import EmptyView from "./EmptyView.vue";
+import { useAIContext } from "../../logic";
+import { provideChatViewContext } from "./context";
+
+const props = withDefaults(
+ defineProps<{
+ mode?: Mode;
+ conversation?: Conversation;
+ }>(),
+ {
+ mode: "CHAT",
+ conversation: undefined,
+ }
+);
defineEmits<{
(event: "enter", value: string): void;
@@ -60,8 +81,7 @@ defineEmits<{
const scrollerRef = ref<HTMLDivElement>();
const containerRef = ref<HTMLDivElement>();
-const store = useConversationStore();
-const conversation = toRef(store, "selectedConversation");
+const { events } = useAIContext();
const { height: containerHeight } = useElementSize(containerRef);
@@ -74,10 +94,7 @@ const scrollToLast = () => {
};
watch(containerHeight, scrollToLast, { immediate: true });
-const handleCreate = async () => {
- const c = await store.createConversation({
- name: "", // Will display as "Untitled conversation"
- });
- store.selectConversation(c);
-};
+provideChatViewContext({
+ mode: toRef(props, "mode"),
+});
</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/CodeView.vue b/frontend/src/plugins/ai/components/ChatView/CodeView.vue
index 584ed29af0..39de7aaf0e 100644
--- a/frontend/src/plugins/ai/components/ChatView/CodeView.vue
+++ b/frontend/src/plugins/ai/components/ChatView/CodeView.vue
@@ -2,12 +2,13 @@
<div class="flex items-start w-full">
<MonacoEditor
ref="editorRef"
- class="flex-1 border h-auto max-h-[240px]"
+ class="flex-1 border h-auto"
language="sql"
- :value="message.content"
- :readonly="true"
+ :value="state.code"
+ :readonly="!state.editing"
:auto-focus="false"
:options="{
+ automaticLayout: true,
fontSize: 12,
lineHeight: 14,
lineNumbers: 'off',
@@ -21,57 +22,136 @@
},
}"
@ready="handleMonacoEditorReady"
+ @change="state.code = $event"
/>
<div class="flex flex-col gap-y-2 ml-0.5 mt-1">
- <button
- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
- @click="handleExecute"
- >
- <heroicons-outline:play class="w-4 h-4" />
- </button>
- <button
- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
- @click="handleCopy"
- >
- <heroicons-outline:clipboard-copy class="w-4 h-4" />
- </button>
+ <NTooltip placement="right">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="handleExecute"
+ >
+ <heroicons:play-circle class="w-4 h-4" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.run") }}
+ </div>
+ </NTooltip>
+ <NTooltip placement="right">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="handleCopy"
+ >
+ <heroicons:clipboard class="w-4 h-4" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.copy") }}
+ </div>
+ </NTooltip>
+ <template v-if="!state.editing">
+ <NTooltip placement="right">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="state.editing = true"
+ >
+ <heroicons:pencil class="w-4 h-4" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.edit") }}
+ </div>
+ </NTooltip>
+ </template>
+ <template v-if="state.editing">
+ <NTooltip placement="right">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="finishEditing(false)"
+ >
+ <heroicons:arrow-uturn-left class="w-4 h-4" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.cancel") }}
+ </div>
+ </NTooltip>
+ <NTooltip placement="right">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="finishEditing(true)"
+ >
+ <heroicons:check class="w-4 h-4" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.save") }}
+ </div>
+ </NTooltip>
+ </template>
</div>
</div>
</template>
<script lang="ts" setup>
-import { ref } from "vue";
+import { reactive, ref, watch } from "vue";
import { toClipboard } from "@soerenmartius/vue3-clipboard";
+import { useI18n } from "vue-i18n";
+import { NTooltip } from "naive-ui";
import type { Message } from "../../types";
import MonacoEditor from "@/components/MonacoEditor";
+import { minmax } from "@/utils";
import { useAIContext } from "../../logic";
import { pushNotification } from "@/store";
-import { useI18n } from "vue-i18n";
+import { useConversationStore } from "../../store";
+
+type LocalState = {
+ code: string;
+ editing: boolean;
+};
const props = defineProps<{
message: Message;
}>();
+const EDITOR_HEIGHT = {
+ min: 48,
+ max: 240,
+};
+
+const state = reactive<LocalState>({
+ code: props.message.content,
+ editing: false,
+});
const { t } = useI18n();
-const context = useAIContext();
+const { events, showHistoryDialog } = useAIContext();
const editorRef = ref<InstanceType<typeof MonacoEditor>>();
-const updateEditorHeight = () => {
+const updateEditorSize = () => {
const contentHeight =
editorRef.value?.editorInstance?.getContentHeight() as number;
- editorRef.value?.setEditorContentHeight(contentHeight);
+ const paddings = 2;
+ editorRef.value?.setEditorContentHeight(
+ minmax(contentHeight + paddings, EDITOR_HEIGHT.min, EDITOR_HEIGHT.max)
+ );
};
const handleMonacoEditorReady = () => {
- updateEditorHeight();
+ updateEditorSize();
};
const handleExecute = () => {
- context.events.emit("apply-statement", {
+ events.emit("apply-statement", {
statement: props.message.content,
run: true,
});
+ showHistoryDialog.value = false;
};
const handleCopy = () => {
@@ -83,4 +163,23 @@ const handleCopy = () => {
});
});
};
+
+const finishEditing = async (update: boolean) => {
+ state.editing = false;
+ if (!update) {
+ state.code = props.message.content;
+ } else {
+ // eslint-disable-next-line vue/no-mutating-props
+ props.message.content = state.code;
+ await useConversationStore().updateMessage(props.message);
+ }
+};
+
+watch(
+ () => props.message.content,
+ (content) => {
+ state.code = content;
+ state.editing = false;
+ }
+);
</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/EmptyView.vue b/frontend/src/plugins/ai/components/ChatView/EmptyView.vue
new file mode 100644
index 0000000000..a8c4033a18
--- /dev/null
+++ b/frontend/src/plugins/ai/components/ChatView/EmptyView.vue
@@ -0,0 +1,12 @@
+<template>
+ <div class="w-full h-full flex flex-col justify-center items-center">
+ <div class="w-[20rem] mx-auto">
+ <p>
+ <img src="../../../../assets/illustration/no-data.webp" />
+ </p>
+ <p class="text-center textinfolabel">
+ {{ $t("plugin.ai.conversation.no-message") }}
+ </p>
+ </div>
+ </div>
+</template>
diff --git a/frontend/src/plugins/ai/components/ChatView/context.ts b/frontend/src/plugins/ai/components/ChatView/context.ts
new file mode 100644
index 0000000000..d85afb2f19
--- /dev/null
+++ b/frontend/src/plugins/ai/components/ChatView/context.ts
@@ -0,0 +1,16 @@
+import { inject, InjectionKey, provide, Ref } from "vue";
+import { Mode } from "./types";
+
+export type ChatViewContext = {
+ mode: Ref<Mode>;
+};
+
+const KEY = Symbol("bb.plugin.ai.chat-view") as InjectionKey<ChatViewContext>;
+
+export const provideChatViewContext = (context: ChatViewContext) => {
+ provide(KEY, context);
+};
+
+export const useChatViewContext = () => {
+ return inject(KEY)!;
+};
diff --git a/frontend/src/plugins/ai/components/ChatView/types.ts b/frontend/src/plugins/ai/components/ChatView/types.ts
new file mode 100644
index 0000000000..315f7cb66a
--- /dev/null
+++ b/frontend/src/plugins/ai/components/ChatView/types.ts
@@ -0,0 +1 @@
+export type Mode = "CHAT" | "VIEW";
diff --git a/frontend/src/plugins/ai/components/ConversationList.vue b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
similarity index 75%
rename from frontend/src/plugins/ai/components/ConversationList.vue
rename to frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
index 82b75bf313..64b89461ae 100644
--- a/frontend/src/plugins/ai/components/ConversationList.vue
+++ b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
@@ -1,22 +1,17 @@
<template>
<div class="h-full overflow-hidden flex flex-col">
- <div class="py-2 px-2">
- <h3 class="font-bold">
- {{ $t("plugin.ai.conversation.conversations") }}
- </h3>
- </div>
<div class="flex-1 overflow-y-auto p-1 flex flex-col gap-y-2">
<template v-if="ready">
<div
- v-for="conversation in conversationList"
+ v-for="conversation in list"
:key="conversation.id"
:data-conversation-id="conversation.id"
class="flex items-start gap-x-0.5 border rounded-md py-2 pl-2 pr-0.5 hover:bg-indigo-50 hover:border-indigo-400 cursor-pointer"
:class="[
- selectedConversation?.id === conversation.id &&
+ selected?.id === conversation.id &&
'bg-indigo-100 border-indigo-400',
]"
- @click="store.selectConversation(conversation)"
+ @click="selected = conversation"
>
<div
v-if="conversation.name"
@@ -55,10 +50,12 @@
<div
class="sticky bottom-0 btn-normal items-center justify-center gap-x-1"
- @click="addConversation"
+ @click="events.emit('new-conversation')"
>
<heroicons-outline:plus class="w-4 h-4" />
- <span class="pr-3">{{ $t("common.new") }}</span>
+ <span class="pr-2">{{
+ $t("plugin.ai.conversation.new-conversation")
+ }}</span>
</div>
</template>
<template v-else>
@@ -76,43 +73,50 @@
</template>
<script lang="ts" setup>
-import { reactive, toRef, watch } from "vue";
+import { reactive, watch } from "vue";
import { NPopconfirm } from "naive-ui";
import scrollIntoView from "scroll-into-view-if-needed";
import { head } from "lodash-es";
+import { useCurrentTab } from "@/store";
import ConversationRenameDialog from "./ConversationRenameDialog.vue";
-import type { Conversation } from "../types";
-import { useConversationList, useConversationStore } from "../store";
+import type { Conversation } from "../../types";
+import { useConversationStore } from "../../store";
+import { useAIContext, useCurrentChat } from "../../logic";
type LocalState = {
rename: Conversation | undefined;
};
+const tab = useCurrentTab();
+const store = useConversationStore();
+const { events } = useAIContext();
+const { list, ready, selected } = useCurrentChat();
+
const state = reactive<LocalState>({
rename: undefined,
});
-const store = useConversationStore();
-const { conversationList, ready } = useConversationList();
-const selectedConversation = toRef(store, "selectedConversation");
-const addConversation = async () => {
- const c = await store.createConversation({
- name: "", // Will display as "Untitled conversation"
- });
- store.selectConversation(c);
-};
+watch(
+ [
+ () => tab.value.connection.instanceId,
+ () => tab.value.connection.databaseId,
+ ],
+ () => {
+ state.rename = undefined;
+ },
+ { immediate: true }
+);
const handleDeleteConversation = async (conversation: Conversation) => {
- const index = conversationList.value.findIndex(
- (c) => c.id === selectedConversation.value?.id
- );
+ // try to keep the selected or a nearby item selected.
+ const index = list.value.findIndex((c) => c.id === selected.value?.id);
await store.deleteConversation(conversation.id);
- store.selectConversation(conversationList.value[index]);
+ selected.value = list.value[index];
};
watch(
- [() => selectedConversation.value?.id, conversationList],
+ [() => selected.value?.id, list],
([id, list]) => {
if (!id) return;
if (list.length === 0) return;
diff --git a/frontend/src/plugins/ai/components/ConversationRenameDialog.vue b/frontend/src/plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue
similarity index 80%
rename from frontend/src/plugins/ai/components/ConversationRenameDialog.vue
rename to frontend/src/plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue
index 89c7fb39eb..66e4bc2e6e 100644
--- a/frontend/src/plugins/ai/components/ConversationRenameDialog.vue
+++ b/frontend/src/plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue
@@ -8,7 +8,7 @@
<div class="w-full">
<NInput
v-model:value="state.name"
- class="w-full"
+ class="bb-ai-conversation-rename-input w-full"
@keypress.enter="handleRename"
/>
</div>
@@ -33,14 +33,14 @@
</template>
<script lang="ts" setup>
-import { reactive } from "vue";
+import { onMounted, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { NButton, NInput } from "naive-ui";
import { head } from "lodash-es";
-import type { Conversation } from "../types";
+import type { Conversation } from "../../types";
import { BBModal } from "@/bbkit";
-import { useConversationStore } from "../store";
+import { useConversationStore } from "../../store";
type LocalState = {
name: string;
@@ -75,4 +75,15 @@ const handleRename = async () => {
await store.updateConversation(conversation);
emit("updated");
};
+
+onMounted(() => {
+ requestAnimationFrame(() => {
+ const input = document.querySelector(
+ ".bb-ai-conversation-rename-input input[type=text]"
+ ) as HTMLInputElement;
+ if (input) {
+ input.focus();
+ }
+ });
+});
</script>
diff --git a/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue b/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue
new file mode 100644
index 0000000000..4f5107bd45
--- /dev/null
+++ b/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue
@@ -0,0 +1,29 @@
+<template>
+ <BBModal
+ :title="$t('plugin.ai.conversation.history-conversations')"
+ class="!pb-0"
+ container-class="!p-0"
+ @close="showHistoryDialog = false"
+ >
+ <div
+ class="h-[calc(100vh-10rem)] w-[calc(100vw-8rem)] max-w-[72rem] px-8 pb-4 flex"
+ >
+ <aside class="hidden lg:flex lg:flex-col w-[14em] border-l border-b">
+ <ConversationList />
+ </aside>
+
+ <div class="flex-1 flex flex-col bg-gray-100">
+ <ChatView mode="VIEW" :conversation="selected" />
+ </div>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { useAIContext, useCurrentChat } from "../../logic";
+import ConversationList from "./ConversationList.vue";
+import ChatView from "../ChatView";
+
+const { showHistoryDialog } = useAIContext();
+const { selected } = useCurrentChat();
+</script>
diff --git a/frontend/src/plugins/ai/components/HistoryPanel/index.ts b/frontend/src/plugins/ai/components/HistoryPanel/index.ts
new file mode 100644
index 0000000000..20aae55311
--- /dev/null
+++ b/frontend/src/plugins/ai/components/HistoryPanel/index.ts
@@ -0,0 +1,3 @@
+import HistoryPanel from "./HistoryPanel.vue";
+
+export default HistoryPanel;
diff --git a/frontend/src/plugins/ai/components/PromptInput.vue b/frontend/src/plugins/ai/components/PromptInput.vue
index a95b261253..49c88ef011 100644
--- a/frontend/src/plugins/ai/components/PromptInput.vue
+++ b/frontend/src/plugins/ai/components/PromptInput.vue
@@ -3,7 +3,6 @@
v-model:value="state.value"
:disabled="disabled"
:placeholder="$t('plugin.ai.text-to-sql-placeholder')"
- class="bb-ai-prompt-input"
@keypress.enter="handlePressEnter"
>
<template #prefix>
@@ -24,7 +23,7 @@
</template>
<script lang="ts" setup>
-import { onMounted, reactive } from "vue";
+import { reactive } from "vue";
import { NInput } from "naive-ui";
type LocalState = {
@@ -56,17 +55,6 @@ const applyValue = (value: string) => {
const handlePressEnter = () => {
applyValue(state.value);
};
-
-onMounted(() => {
- requestAnimationFrame(() => {
- const input = document.querySelector(
- ".bb-ai-prompt-input input[type=text]"
- ) as HTMLInputElement;
- if (input) {
- input.focus();
- }
- });
-});
</script>
<style lang="postcss">
diff --git a/frontend/src/plugins/ai/index.ts b/frontend/src/plugins/ai/index.ts
index dfae7e918a..d4ffae80b2 100644
--- a/frontend/src/plugins/ai/index.ts
+++ b/frontend/src/plugins/ai/index.ts
@@ -1,5 +1,4 @@
-import AIDialog from "./components/AIDialog.vue";
-import AIPromptButton from "./components/AIPromptButton.vue";
+import AIChatToSQL from "./components/AIChatToSQL.vue";
export * from "./types";
-export { AIDialog, AIPromptButton };
+export { AIChatToSQL };
diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.ts
index 2edd280c79..35dd13a1ea 100644
--- a/frontend/src/plugins/ai/logic/index.ts
+++ b/frontend/src/plugins/ai/logic/index.ts
@@ -1 +1,3 @@
export * from "./context";
+export * from "./useChatByTab";
+export * from "./utils";
diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.ts
new file mode 100644
index 0000000000..ce878523ff
--- /dev/null
+++ b/frontend/src/plugins/ai/logic/useChatByTab.ts
@@ -0,0 +1,68 @@
+import { useCurrentTab } from "@/store";
+import { TabInfo } from "@/types";
+import { last } from "lodash-es";
+import { computed, ref, watch } from "vue";
+import { useConversationStore } from "../store";
+import { AIChatInfo, Conversation } from "../types";
+import { useAIContext } from "./context";
+
+const chatsByTab = new Map<string, AIChatInfo>();
+
+export const useChatByTab = () => {
+ const tab = useCurrentTab();
+ const store = useConversationStore();
+
+ const initializeChat = (tab: TabInfo): AIChatInfo => {
+ const ready = ref(false);
+ store.fetchConversationListByConnection(tab.connection).then(() => {
+ ready.value = true;
+ });
+ const list = computed(() => {
+ const { instanceId, databaseId } = tab.connection;
+ return store.conversationList.filter(
+ (c) => c.instanceId === instanceId && c.databaseId === databaseId
+ );
+ });
+ const selected = ref<Conversation>();
+ watch(
+ [list, ready, selected],
+ ([list, ready]) => {
+ if (ready) {
+ if (!selected.value) {
+ selected.value = last(list);
+ }
+ }
+ },
+ { immediate: true }
+ );
+ return { list, ready, selected };
+ };
+
+ const getChatByTab = (tab: TabInfo) => {
+ const key = JSON.stringify(tab.connection);
+ const existed = chatsByTab.get(key);
+ if (existed) return existed;
+ const chat = initializeChat(tab);
+ chatsByTab.set(key, chat);
+ return chat;
+ };
+
+ return computed(() => {
+ return getChatByTab(tab.value);
+ });
+};
+
+export const useCurrentChat = () => {
+ const { chat } = useAIContext();
+ const list = computed(() => chat.value.list.value);
+ const ready = computed(() => chat.value.ready.value);
+ const selected = computed({
+ get() {
+ return chat.value.selected.value;
+ },
+ set(val) {
+ chat.value.selected.value = val;
+ },
+ });
+ return { list, ready, selected };
+};
diff --git a/frontend/src/plugins/ai/logic/utils.ts b/frontend/src/plugins/ai/logic/utils.ts
new file mode 100644
index 0000000000..c623c72f9e
--- /dev/null
+++ b/frontend/src/plugins/ai/logic/utils.ts
@@ -0,0 +1,25 @@
+import { watch } from "vue";
+import type { Connection } from "@/types";
+import { useCurrentTab } from "@/store";
+
+export const onConnectionChanged = (
+ fn: (newConn: Connection, oldConn: Connection | undefined) => void,
+ immediate = false
+) => {
+ const tab = useCurrentTab();
+ return watch(
+ [
+ () => tab.value.connection.instanceId,
+ () => tab.value.connection.databaseId,
+ ],
+ (newValues, oldValues) => {
+ fn(
+ { instanceId: newValues[0], databaseId: newValues[1] },
+ oldValues[0] && oldValues[1]
+ ? { instanceId: oldValues[0], databaseId: oldValues[1] }
+ : undefined
+ );
+ },
+ { immediate }
+ );
+};
diff --git a/frontend/src/plugins/ai/store/conversation.ts b/frontend/src/plugins/ai/store/conversation.ts
index 0177d127d9..9a636d83fb 100644
--- a/frontend/src/plugins/ai/store/conversation.ts
+++ b/frontend/src/plugins/ai/store/conversation.ts
@@ -1,11 +1,12 @@
-import { computed, onMounted, reactive, ref, toRef, watchEffect } from "vue";
-import { groupBy, last, omit } from "lodash-es";
+import { computed, reactive, ref, unref, watchEffect } from "vue";
+import { groupBy, omit } from "lodash-es";
import { defineStore } from "pinia";
import PouchDB from "pouchdb";
import PouchDBFind from "pouchdb-find";
import { v1 as uuidv1 } from "uuid";
import { Conversation, Message } from "../types";
+import { Connection, MaybeRef } from "@/types";
type RowStatus = "NORMAL" | "ARCHIVED";
@@ -124,20 +125,18 @@ export const useConversationStore = defineStore("ai-conversation", () => {
getConversationById,
} = useLocalCache();
- const selectedConversationId = ref<string>();
const conversationList = computed(() => {
return [...conversationById.values()];
});
- const selectedConversation = computed(() => {
- const id = selectedConversationId.value;
- if (!id) return undefined;
- return getConversationById(id);
- });
- const fetchConversationList = async () => {
+ const fetchConversationListByConnection = async (conn: Connection) => {
const conversationEntityList = (
await conversations.find({
- selector: { row_status: { $eq: "NORMAL" } },
+ selector: {
+ row_status: { $eq: "NORMAL" },
+ instanceId: { $eq: conn.instanceId },
+ databaseId: { $eq: conn.databaseId },
+ },
})
).docs;
const flattenMessageMessageList = (
@@ -165,12 +164,6 @@ export const useConversationStore = defineStore("ai-conversation", () => {
conversation.messageList.sort((a, b) => a.created_ts - b.created_ts);
return conversation;
});
- if (conversationList.length === 0) {
- const initialConversation = await createConversation({
- name: "",
- });
- conversationList.push(initialConversation);
- }
await fixAbnormalMessages(conversationList.flatMap((c) => c.messageList));
return conversationList;
};
@@ -240,10 +233,6 @@ export const useConversationStore = defineStore("ai-conversation", () => {
return convertMessage(m, message.conversation);
};
- const selectConversation = (c: Conversation | undefined) => {
- selectedConversationId.value = c?.id;
- };
-
const fixAbnormalMessages = async (messageList: Message[]) => {
const requests = messageList
.filter((message) => message.status === "LOADING")
@@ -256,37 +245,36 @@ export const useConversationStore = defineStore("ai-conversation", () => {
};
const reset = () => {
- console.log("reset conversation storage");
+ // console.debug("reset conversation storage");
return Promise.all([conversations.destroy(), messages.destroy()]);
};
- watchEffect(() => {
- if (!selectedConversationId.value) {
- selectConversation(last(conversationList.value));
- }
- });
-
return {
conversationById,
conversationList,
- selectedConversation,
- fetchConversationList,
+ fetchConversationListByConnection,
createConversation,
updateConversation,
deleteConversation,
createMessage,
updateMessage,
- selectConversation,
reset,
};
});
-export const useConversationList = () => {
+export const useConversationListByConnection = (conn: MaybeRef<Connection>) => {
const store = useConversationStore();
const ready = ref(false);
- onMounted(async () => {
- await store.fetchConversationList();
+ watchEffect(async () => {
+ ready.value = false;
+ await store.fetchConversationListByConnection(unref(conn));
ready.value = true;
});
- return { conversationList: toRef(store, "conversationList"), ready };
+ const list = computed(() => {
+ const { instanceId, databaseId } = unref(conn);
+ return store.conversationList.filter(
+ (c) => c.instanceId === instanceId && c.databaseId === databaseId
+ );
+ });
+ return { list, ready };
};
diff --git a/frontend/src/plugins/ai/types/context.ts b/frontend/src/plugins/ai/types/context.ts
index f9eb7b9964..3d045f0627 100644
--- a/frontend/src/plugins/ai/types/context.ts
+++ b/frontend/src/plugins/ai/types/context.ts
@@ -2,18 +2,28 @@ import type { Ref } from "vue";
import type Emittery from "emittery";
import type { EngineType } from "@/types";
import type { DatabaseMetadata } from "@/types/proto/store/database";
+import { Conversation } from "./conversation";
export type AIContextEvents = Emittery<{
"apply-statement": { statement: string; run: boolean };
error: string;
+ "new-conversation": any;
}>;
+export type AIChatInfo = {
+ list: Ref<Conversation[]>;
+ ready: Ref<boolean>;
+ selected: Ref<Conversation | undefined>;
+};
+
export type AIContext = {
- showDialog: Ref<boolean>;
openAIKey: Ref<string>;
engineType: Ref<EngineType | undefined>;
databaseMetadata: Ref<DatabaseMetadata | undefined>;
autoRun: Ref<boolean>;
+ showHistoryDialog: Ref<boolean>;
+
+ chat: Ref<AIChatInfo>;
// Events
events: AIContextEvents;
diff --git a/frontend/src/plugins/ai/types/conversation.ts b/frontend/src/plugins/ai/types/conversation.ts
index f5dea75985..d77ad1424a 100644
--- a/frontend/src/plugins/ai/types/conversation.ts
+++ b/frontend/src/plugins/ai/types/conversation.ts
@@ -1,3 +1,5 @@
+import type { InstanceId, DatabaseId } from "@/types";
+
export type MessageAuthor = "USER" | "AI";
export type MessageStatus = "LOADING" | "DONE" | "FAILED";
@@ -17,5 +19,7 @@ export type Conversation = {
id: string; // uuid
created_ts: number; // ms
name: string;
+ instanceId: InstanceId;
+ databaseId: DatabaseId;
messageList: Message[];
};
diff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.ts
index 0a3c0a57ea..fdccf9546a 100644
--- a/frontend/src/store/modules/tab.ts
+++ b/frontend/src/store/modules/tab.ts
@@ -1,5 +1,5 @@
import { defineStore } from "pinia";
-import { computed, reactive, ref, watch } from "vue";
+import { computed, reactive, ref, toRef, watch } from "vue";
import { pick } from "lodash-es";
import { watchThrottled } from "@vueuse/core";
import type { TabInfo, CoreTabInfo, AnyTabInfo } from "@/types";
@@ -265,3 +265,8 @@ export const useTabStore = defineStore("tab", () => {
reset,
};
});
+
+export const useCurrentTab = () => {
+ const store = useTabStore();
+ return toRef(store, "currentTab");
+};
diff --git a/frontend/src/types/plan.ts b/frontend/src/types/plan.ts
index bcf98c0631..7752991787 100644
--- a/frontend/src/types/plan.ts
+++ b/frontend/src/types/plan.ts
@@ -34,7 +34,9 @@ export type FeatureType =
| "bb.feature.backup-policy"
| "bb.feature.environment-tier-policy"
| "bb.feature.sensitive-data"
- | "bb.feature.access-control";
+ | "bb.feature.access-control"
+ // Plugins
+ | "bb.feature.plugin.openai";
export enum PlanType {
FREE = 0,
diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.ts
index 8a592ad807..813597b462 100644
--- a/frontend/src/types/tab.ts
+++ b/frontend/src/types/tab.ts
@@ -24,6 +24,8 @@ export enum TabMode {
Admin = 2,
}
+export type EditMode = "SQL-EDITOR" | "CHAT-TO-SQL";
+
export interface TabInfo {
id: string;
name: string;
@@ -33,6 +35,7 @@ export interface TabInfo {
statement: string;
selectedStatement: string;
mode: TabMode;
+ editMode: EditMode;
executeParams?: {
query: string;
config: ExecuteConfig;
diff --git a/frontend/src/utils/tab.ts b/frontend/src/utils/tab.ts
index 79816e2fd4..cef23abd57 100644
--- a/frontend/src/utils/tab.ts
+++ b/frontend/src/utils/tab.ts
@@ -25,6 +25,7 @@ export const getDefaultTab = (): TabInfo => {
statement: "",
selectedStatement: "",
mode: TabMode.ReadOnly,
+ editMode: "SQL-EDITOR",
isExecutingSQL: false,
};
};
diff --git a/frontend/src/views/SettingWorkspaceGeneral.vue b/frontend/src/views/SettingWorkspaceGeneral.vue
index 48fd9c10e0..5028f65ad0 100644
--- a/frontend/src/views/SettingWorkspaceGeneral.vue
+++ b/frontend/src/views/SettingWorkspaceGeneral.vue
@@ -3,6 +3,7 @@
<BrandingSetting />
<SecuritySetting />
<NetworkSetting v-if="!isSaaSMode" />
+ <AIAugmentationSetting />
</div>
</template>
@@ -12,6 +13,7 @@ import {
BrandingSetting,
SecuritySetting,
NetworkSetting,
+ AIAugmentationSetting,
} from "@/components/GeneralSetting";
import { useActuatorStore } from "@/store";
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
index 138caee5ed..c9aa51af7b 100644
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
@@ -78,20 +78,6 @@
</NPopover>
</template>
</div>
-
- <div
- v-if="
- tabStore.currentTab.mode === TabMode.ReadOnly &&
- !tabStore.isDisconnected
- "
- class="w-full -mb-1"
- >
- <AIPromptButton
- :engine-type="instance.engine"
- :database-metadata="databaseMetadata"
- @apply-statement="handleApplySQL"
- />
- </div>
</div>
</template>
@@ -103,11 +89,9 @@ import {
useSQLEditorStore,
useInstanceById,
useWebTerminalStore,
- useMetadataByDatabaseId,
} from "@/store";
import type { ExecuteConfig, ExecuteOption } from "@/types";
import { TabMode, UNKNOWN_ID } from "@/types";
-import { AIPromptButton } from "@/plugins/ai";
import SharePopover from "./SharePopover.vue";
import AdminModeButton from "./AdminModeButton.vue";
@@ -206,17 +190,4 @@ const handleFormatSQL = () => {
const handleClearScreen = () => {
emit("clear-screen");
};
-
-const databaseId = computed(() => tabStore.currentTab.connection.databaseId);
-const databaseMetadata = useMetadataByDatabaseId(databaseId, false);
-const instance = useInstanceById(
- computed(() => tabStore.currentTab.connection.instanceId)
-);
-
-const handleApplySQL = (sql: string, run: boolean) => {
- tabStore.currentTab.statement = sql;
- if (run) {
- emit("execute", sql, { databaseType: selectedInstanceEngine.value });
- }
-};
</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
index 385811f0a0..c9776c1d84 100644
--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
@@ -1,16 +1,23 @@
<template>
<div class="flex h-full w-full flex-col justify-start items-start">
- <EditorAction @execute="handleExecute" @save-sheet="trySaveSheet" />
+ <template v-if="tab.editMode === 'SQL-EDITOR'">
+ <EditorAction @execute="handleExecute" @save-sheet="trySaveSheet" />
- <ConnectionPathBar />
+ <ConnectionPathBar />
- <template v-if="!tabStore.isDisconnected">
- <SQLEditor @execute="handleExecute" @save-sheet="trySaveSheet" />
- </template>
- <template v-else>
- <ConnectionHolder />
+ <template v-if="!tabStore.isDisconnected">
+ <SQLEditor @execute="handleExecute" @save-sheet="trySaveSheet" />
+ </template>
+ <template v-else>
+ <ConnectionHolder />
+ </template>
</template>
+ <AIChatToSQL
+ v-if="!tabStore.isDisconnected"
+ @apply-statement="handleApplyStatement"
+ />
+
<ExecutingHintModal />
<SaveSheetModal ref="saveSheetModal" />
@@ -20,8 +27,8 @@
<script lang="ts" setup>
import { ref } from "vue";
-import type { ExecuteConfig, ExecuteOption } from "@/types";
-import { useTabStore } from "@/store";
+import type { Connection, ExecuteConfig, ExecuteOption } from "@/types";
+import { useCurrentTab, useInstanceStore, useTabStore } from "@/store";
import SQLEditor from "./SQLEditor.vue";
import {
EditorAction,
@@ -31,9 +38,11 @@ import {
SaveSheetModal,
} from "../EditorCommon";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
+import { AIChatToSQL } from "@/plugins/ai";
const tabStore = useTabStore();
const saveSheetModal = ref<InstanceType<typeof SaveSheetModal>>();
+const tab = useCurrentTab();
const { execute } = useExecuteSQL();
@@ -48,4 +57,21 @@ const handleExecute = (
const trySaveSheet = (sheetName?: string) => {
saveSheetModal.value?.trySaveSheet(sheetName);
};
+
+const handleApplyStatement = async (
+ statement: string,
+ conn: Connection,
+ run: boolean
+) => {
+ tab.value.statement = statement;
+ if (run) {
+ const instanceStore = useInstanceStore();
+ const instance = await instanceStore.getOrFetchInstanceById(
+ conn.instanceId
+ );
+ handleExecute(statement, {
+ databaseType: instanceStore.formatEngine(instance),
+ });
+ }
+};
</script>