Skip to content

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

feat(sql-editor): AI Assistant improvements (#14051)

Liu Ji694dcdcc8ed6
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index a422ca599d..0fce0d9dc4 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -3229,7 +3229,8 @@
"chat": "Chat",
"explain-code": "Explain code",
"find-problems": "Find problems",
- "new-chat": "New chat"
+ "new-chat": "New chat",
+ "insert-at-caret": "Insert at caret"
},
"send": "Send",
"new-line": "New line",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index e4b2c07044..f6e6f02974 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3229,7 +3229,8 @@
"chat": "Charlar",
"explain-code": "Explicar el código",
"find-problems": "encontrar problemas",
- "new-chat": "Nuevo chat"
+ "new-chat": "Nuevo chat",
+ "insert-at-caret": "Insertar en el cursor"
},
"send": "Enviar",
"new-line": "Nueva linea",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 18cdf9100c..d3569b856a 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3229,7 +3229,8 @@
"chat": "チャット",
"explain-code": "コードの説明",
"find-problems": "問題を見つける",
- "new-chat": "新しいチャット"
+ "new-chat": "新しいチャット",
+ "insert-at-caret": "キャレットに挿入"
},
"send": "送信",
"new-line": "改行",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 9e3dd8f169..1a552072ef 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3229,7 +3229,8 @@
"chat": "对话",
"explain-code": "解释代码",
"find-problems": "找出问题",
- "new-chat": "开启新对话"
+ "new-chat": "开启新对话",
+ "insert-at-caret": "在光标处插入"
},
"send": "发送",
"new-line": "换行",
diff --git a/frontend/src/plugins/ai/components/ActionBar.vue b/frontend/src/plugins/ai/components/ActionBar.vue
index 6aa1d4140b..f601e3277a 100644
--- a/frontend/src/plugins/ai/components/ActionBar.vue
+++ b/frontend/src/plugins/ai/components/ActionBar.vue
@@ -45,33 +45,14 @@
{{ $t("plugin.ai.conversation.new-conversation") }}
</template>
</NPopover>
- <NPopover placement="bottom">
- <template #trigger>
- <NButton
- size="small"
- quaternary
- style="--n-padding: 0 5px"
- @click="showAIPanel = false"
- >
- <template #icon>
- <XIcon class="w-4 h-4" />
- </template>
- </NButton>
- </template>
- <template #default>
- {{ $t("common.hide") }}
- </template>
- </NPopover>
</div>
</div>
</template>
<script lang="ts" setup>
-import { ClockIcon, XIcon, PlusIcon } from "lucide-vue-next";
+import { ClockIcon, PlusIcon } from "lucide-vue-next";
import { NButton, NPopover } from "naive-ui";
-import { useSQLEditorContext } from "@/views/sql-editor/context";
import { useAIContext } from "../logic";
const { events, showHistoryDialog } = useAIContext();
-const { showAIPanel } = useSQLEditorContext();
</script>
diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vue
index 31d562c0c2..726fef9586 100644
--- a/frontend/src/plugins/ai/components/ChatPanel.vue
+++ b/frontend/src/plugins/ai/components/ChatPanel.vue
@@ -11,8 +11,8 @@
@enter="requestAI"
/>
- <div class="px-2 py-2 flex flex-col gap-2">
- <DynamicSuggestions class="flex-1 w-full" @enter="requestAI" />
+ <div class="px-2 pb-2 pt-1 flex flex-col gap-1">
+ <DynamicSuggestions class="w-full" @enter="requestAI" />
<PromptInput v-if="tab" @enter="requestAI" />
</div>
diff --git a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
index 3251152f55..b8952bd007 100644
--- a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
+++ b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
@@ -3,13 +3,19 @@
class="border rounded shadow py-1 px-1 bg-gray-50 border-gray-400"
:class="[
message.status === 'DONE'
- ? 'w-[60%] min-w-[9rem]'
+ ? 'w-[100%] min-w-[9rem]'
: message.status === 'FAILED'
? 'max-w-[40%] min-w-[9rem]'
: 'w-auto',
]"
>
- <Markdown v-if="message.status === 'DONE'" :content="message.content" />
+ <Markdown
+ v-if="message.status === 'DONE'"
+ :content="message.content"
+ :code-block-props="{
+ width: 1.0,
+ }"
+ />
<div v-else-if="message.status === 'LOADING'" class="flex items-center">
<BBSpin class="mx-1" :size="18" />
</div>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
index 9a057a00d6..889217354f 100644
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
@@ -1,66 +1,81 @@
<template>
<div
ref="containerRef"
- class="flex items-start"
+ class="flex flex-col overflow-x-hidden border border-gray-500 rounded bg-white"
:data-message-wrapper-width="messageWrapperWidth"
- :style="`width: ${width}px`"
+ :style="`width: ${combinedWidth}px`"
>
- <div class="flex-1 overflow-x-hidden">
- <MonacoEditor
- :content="code"
- :readonly="true"
- :auto-focus="false"
- :auto-height="{
- min: 48,
- max: 120,
- padding: 2,
- }"
- :options="{
- automaticLayout: true,
- fontSize: 12,
- lineHeight: 14,
- lineNumbers: 'off',
- wordWrap: 'on',
- scrollbar: {
- vertical: 'hidden',
- horizontal: 'hidden',
- useShadows: false,
- verticalScrollbarSize: 0,
- horizontalScrollbarSize: 0,
- alwaysConsumeMouseWheel: false,
- },
- }"
- class="border h-auto bg-white"
- />
- </div>
- <div class="flex flex-col gap-y-2 ml-0.5 mt-1">
- <NPopover placement="right">
- <template #trigger>
- <button
- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
- @click="handleExecute"
- >
- <PlayIcon class="w-3.5 h-3.5" />
- </button>
- </template>
- <div class="whitespace-nowrap">
- {{ $t("common.run") }}
- </div>
- </NPopover>
- <NPopover placement="right">
- <template #trigger>
- <button
- class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
- @click="handleCopy"
- >
- <ClipboardIcon class="w-3.5 h-3.5" />
- </button>
- </template>
- <div class="whitespace-nowrap">
- {{ $t("common.copy") }}
- </div>
- </NPopover>
+ <div class="flex items-center justify-between px-1 pt-1">
+ <div class="text-xs">SQL</div>
+ <div class="flex items-center justify-end gap-2">
+ <NPopover placement="bottom">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="handleExecute"
+ >
+ <PlayIcon class="w-3.5 h-3.5" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.run") }}
+ </div>
+ </NPopover>
+ <NPopover placement="bottom">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click.capture="handleInsertAtCaret"
+ >
+ <InsertAtCaretIcon :size="14" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("plugin.ai.actions.insert-at-caret") }}
+ </div>
+ </NPopover>
+ <NPopover placement="bottom">
+ <template #trigger>
+ <button
+ class="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ @click="handleCopy"
+ >
+ <ClipboardIcon class="w-3.5 h-3.5" />
+ </button>
+ </template>
+ <div class="whitespace-nowrap">
+ {{ $t("common.copy") }}
+ </div>
+ </NPopover>
+ </div>
</div>
+
+ <MonacoEditor
+ :content="code"
+ :readonly="true"
+ :auto-focus="false"
+ :auto-height="{
+ min: 20,
+ max: 120,
+ padding: 2,
+ }"
+ :options="{
+ automaticLayout: true,
+ fontSize: 12,
+ lineHeight: 14,
+ lineNumbers: 'off',
+ wordWrap: 'on',
+ scrollbar: {
+ vertical: 'hidden',
+ horizontal: 'hidden',
+ useShadows: false,
+ verticalScrollbarSize: 0,
+ horizontalScrollbarSize: 0,
+ alwaysConsumeMouseWheel: false,
+ },
+ }"
+ class="h-auto"
+ />
</div>
</template>
@@ -74,22 +89,31 @@ import { MonacoEditor } from "@/components/MonacoEditor";
import { useAIContext } from "@/plugins/ai/logic";
import { pushNotification } from "@/store";
import { findAncestor, toClipboard } from "@/utils";
+import { useSQLEditorContext } from "@/views/sql-editor/context";
+import InsertAtCaretIcon from "./InsertAtCaretIcon.vue";
+
+export type CodeBlockProps = {
+ width: number;
+};
-const props = defineProps<{
- code: string;
-}>();
+const props = defineProps<
+ CodeBlockProps & {
+ code: string;
+ }
+>();
const { t } = useI18n();
const { events, showHistoryDialog } = useAIContext();
+const { events: editorEvents } = useSQLEditorContext();
const containerRef = ref<HTMLElement>();
const messageWrapperRef = computed(() =>
findAncestor(containerRef.value, ".message")
);
const { width: messageWrapperWidth } = useElementSize(messageWrapperRef);
-const width = computed(() => {
+const combinedWidth = computed(() => {
const PADDING = 8;
const min = 8 * 16; /* 8rem */
- const auto = messageWrapperWidth.value * 0.6 - PADDING * 2;
+ const auto = messageWrapperWidth.value * props.width - PADDING * 2;
return Math.max(min, auto);
});
@@ -100,6 +124,14 @@ const handleExecute = () => {
showHistoryDialog.value = false;
};
+const handleInsertAtCaret = () => {
+ const { code } = props;
+ editorEvents.emit("insert-at-caret", {
+ content: code,
+ });
+ showHistoryDialog.value = false;
+};
+
const handleCopy = () => {
toClipboard(props.code).then(() => {
pushNotification({
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue
new file mode 100644
index 0000000000..8e3d6ced9c
--- /dev/null
+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue
@@ -0,0 +1,28 @@
+<template>
+ <div class="inline-block relative">
+ <AlignLeftIcon
+ :style="{
+ width: `${size}px`,
+ height: `${size}px`,
+ }"
+ />
+ <ArrowLeftIcon
+ class="text-accent absolute"
+ :stroke-width="4"
+ :style="{
+ width: `${size * 0.7}px`,
+ height: `${size * 0.7}px`,
+ right: `${size * -0.2}px`,
+ bottom: `${size * 0.035}px`,
+ }"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { AlignLeftIcon, ArrowLeftIcon } from "lucide-vue-next";
+
+defineProps<{
+ size: number;
+}>();
+</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue
index 9ea2610dd2..9b549f5791 100644
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue
+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue
@@ -1,10 +1,13 @@
<template>
<AstToMarkdown :ast="mdast" class="text-sm">
<template #code="parsedAst">
- <CodeBlock :code="parsedAst.value" />
+ <CodeBlock :code="parsedAst.value" v-bind="codeBlockProps" />
</template>
<template #inlineCode="parsedAst">
- <HighlightCodeBlock :code="parsedAst.value" class="inline-block bg-gray-200 px-0.5 mx-0.5" />
+ <HighlightCodeBlock
+ :code="parsedAst.value"
+ class="inline-block bg-gray-200 px-0.5 mx-0.5"
+ />
</template>
<template #image="parsedAst">
<img :src="parsedAst.url" />
@@ -19,10 +22,11 @@ import { unified } from "unified";
import { computed } from "vue";
import HighlightCodeBlock from "@/components/HighlightCodeBlock";
import AstToMarkdown from "./AstToVNode.vue";
-import CodeBlock from "./CodeBlock.vue";
+import CodeBlock, { type CodeBlockProps } from "./CodeBlock.vue";
const props = defineProps<{
content: string;
+ codeBlockProps: CodeBlockProps;
}>();
const processor = unified().use(remarkParse).use(remarkGfm);
diff --git a/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue b/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue
index 4a4964a8d2..16d3588cc6 100644
--- a/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue
+++ b/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue
@@ -2,7 +2,12 @@
<div
class="user-message max-w-[60%] min-w-[9rem] border rounded shadow py-1 px-2 bg-indigo-100 border-indigo-400"
>
- <Markdown :content="message.content" />
+ <Markdown
+ :content="message.content"
+ :code-block-props="{
+ width: 0.6,
+ }"
+ />
</div>
</template>
diff --git a/frontend/src/plugins/ai/components/DynamicSuggestions.vue b/frontend/src/plugins/ai/components/DynamicSuggestions.vue
index 3848f402d0..638baadbc3 100644
--- a/frontend/src/plugins/ai/components/DynamicSuggestions.vue
+++ b/frontend/src/plugins/ai/components/DynamicSuggestions.vue
@@ -1,54 +1,48 @@
<template>
- <div
- v-if="!ready || suggestions.length > 0"
- class="flex items-center overflow-hidden h-[22px]"
- >
+ <div v-if="show" class="flex items-center overflow-hidden h-[22px]">
<template v-if="dynamicSuggestions && !ready">
- <BBSpin :size="20" class="mr-2" />
- <span class="text-sm">{{
- $t("plugin.ai.conversation.tips.suggest-prompt")
- }}</span>
+ <BBSpin :size="16" class="mr-2" />
+ <span class="text-sm">
+ {{ $t("plugin.ai.conversation.tips.suggest-prompt") }}
+ </span>
</template>
- <template v-if="ready && suggestions.length > 0">
- <div
- class="relative flex items-center gap-x-2 overflow-hidden text-xs leading-4"
+ <div
+ v-if="ready"
+ class="relative flex items-center gap-1 overflow-hidden text-xs leading-4"
+ >
+ <NButton
+ v-if="current"
+ size="tiny"
+ class="flex-1 overflow-hidden"
+ @click.capture="consume"
>
- <div
- class="flex items-stretch gap-x-2 whitespace-nowrap overflow-x-auto hide-scrollbar"
- >
- <NEllipsis
- v-for="(sug, i) in suggestions"
- :key="i"
- style="max-width: 20rem"
- class="border rounded-sm shrink-0 py-0.5 px-2 cursor-pointer hover:bg-indigo-100 hover:border-indigo-500"
- @click.capture="consume(sug)"
- >
- {{ sug }}
- </NEllipsis>
-
- <div class="shrink-0 flex items-center">
- <BBSpin v-if="state === 'LOADING'" :size="16" />
- <NButton
- v-if="state === 'IDLE'"
- size="tiny"
- quaternary
- @click="dynamicSuggestions?.fetch()"
- >
- {{ $t("plugin.ai.conversation.tips.more") }}
- </NButton>
- <span v-if="state === 'ENDED'" class="text-gray-500">
- {{ $t("plugin.ai.conversation.tips.no-more") }}
- </span>
- </div>
+ <div class="w-full truncate">
+ {{ current }}
</div>
- </div>
- </template>
+ </NButton>
+
+ <BBSpin v-if="state === 'LOADING'" :size="16" class="shrink-0" />
+ <NButton
+ v-if="state === 'IDLE'"
+ size="tiny"
+ type="primary"
+ quaternary
+ class="shrink-0"
+ @click="dynamicSuggestions?.consume()"
+ >
+ <RefreshCwIcon class="w-3.5 h-3.5" />
+ </NButton>
+ <span v-if="state === 'ENDED'" class="shrink-0 text-gray-500">
+ {{ $t("plugin.ai.conversation.tips.no-more") }}
+ </span>
+ </div>
</div>
</template>
<script lang="ts" setup>
-import { NButton, NEllipsis } from "naive-ui";
+import { RefreshCwIcon } from "lucide-vue-next";
+import { NButton } from "naive-ui";
import { computed } from "vue";
import { BBSpin } from "@/bbkit";
import { useDynamicSuggestions } from "../logic";
@@ -62,11 +56,19 @@ const dynamicSuggestions = useDynamicSuggestions();
const ready = computed(() => dynamicSuggestions.value?.ready ?? false);
const state = computed(() => dynamicSuggestions.value?.state ?? "IDLE");
const suggestions = computed(() => dynamicSuggestions.value?.suggestions ?? []);
+const current = computed(() => dynamicSuggestions.value?.current());
+
+const show = computed(() => {
+ if (!ready.value) return true; // show a spinner
+ return suggestions.value.length > 0 || state.value === "LOADING";
+});
-const consume = (sug: string) => {
- const suggestions = dynamicSuggestions.value;
- if (!suggestions) return;
- suggestions.consume(sug);
- emit("enter", sug);
+const consume = () => {
+ const suggestion = dynamicSuggestions.value;
+ if (!suggestion) return;
+ const curr = current.value;
+ if (!curr) return;
+ emit("enter", curr);
+ suggestion.consume();
};
</script>
diff --git a/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue b/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue
index 526f0d8996..cdda9b8a9b 100644
--- a/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue
+++ b/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue
@@ -10,7 +10,7 @@
<ConversationList />
</aside>
- <div class="flex-1 flex flex-col bg-gray-100 overflow-hidden">
+ <div class="flex-1 flex flex-col py-2 bg-gray-100 overflow-hidden">
<ChatView mode="VIEW" :conversation="selected" />
</div>
</div>
diff --git a/frontend/src/plugins/ai/components/PromptInput.vue b/frontend/src/plugins/ai/components/PromptInput.vue
index 576278dc16..368d9d9498 100644
--- a/frontend/src/plugins/ai/components/PromptInput.vue
+++ b/frontend/src/plugins/ai/components/PromptInput.vue
@@ -13,12 +13,9 @@
}"
size="small"
type="textarea"
- style="--n-padding-left: 8px; --n-padding-right: 4px"
+ style="--n-padding-left: 6px; --n-padding-right: 0px"
@keypress.enter="handlePressEnter"
>
- <template #prefix>
- <heroicons-outline:sparkles class="w-3.5 h-3.5 text-accent" />
- </template>
<template #suffix>
<NPopover placement="bottom" style="--n-padding: 6px 8px">
<template #trigger>
@@ -53,6 +50,7 @@
<script lang="ts" setup>
import { NButton, NInput, NPopover, type InputInst } from "naive-ui";
import { onMounted, reactive, ref, watch } from "vue";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import { keyboardShortcutStr, nextAnimationFrame } from "@/utils";
import { useAIContext } from "../logic";
@@ -77,7 +75,7 @@ const state = reactive<LocalState>({
value: "",
});
-const { pendingPreInput } = useAIContext();
+const { pendingPreInput, events } = useAIContext();
const inputRef = ref<InputInst>();
const applyValue = (value: string) => {
@@ -89,8 +87,9 @@ const handlePressEnter = (e?: KeyboardEvent) => {
if (e?.shiftKey) {
return;
}
- applyValue(state.value);
e?.preventDefault();
+ if (!state.value.trim()) return;
+ applyValue(state.value);
};
onMounted(() => {
@@ -110,4 +109,8 @@ watch(
flush: "post",
}
);
+
+useEmitteryEventListener(events, "new-conversation", () => {
+ inputRef.value?.focus();
+});
</script>
diff --git a/frontend/src/plugins/ai/components/editor-actions.ts b/frontend/src/plugins/ai/components/editor-actions.ts
index 21ea3de2ee..9345dd6177 100644
--- a/frontend/src/plugins/ai/components/editor-actions.ts
+++ b/frontend/src/plugins/ai/components/editor-actions.ts
@@ -84,17 +84,7 @@ export const useAIActions = async (
actions.value.push(action);
}
if (opts.actions.includes("new-chat")) {
- const action1 = editor.addAction({
- id: "new-chat",
- label: "New chat",
- precondition: "bb.ai.selectedContentEmpty",
- contextMenuGroupId: "2_ai_assistant",
- contextMenuOrder: 2,
- run: async () => {
- opts.callback("new-chat", monaco, editor);
- },
- });
- const action2 = editor.addAction({
+ const action = editor.addAction({
id: "new-chat-using-selection",
label: "New chat using selection",
precondition: "!bb.ai.selectedContentEmpty",
@@ -104,8 +94,7 @@ export const useAIActions = async (
opts.callback("new-chat", monaco, editor);
},
});
- actions.value.push(action1);
- actions.value.push(action2);
+ actions.value.push(action);
}
} else {
// When the language is "javascript" we do not have AI Assistant actions
diff --git a/frontend/src/plugins/ai/logic/prompt.ts b/frontend/src/plugins/ai/logic/prompt.ts
index ef461e407b..6e6d1e89f0 100644
--- a/frontend/src/plugins/ai/logic/prompt.ts
+++ b/frontend/src/plugins/ai/logic/prompt.ts
@@ -82,6 +82,8 @@ export const wrapStatementMarkdown = (statement: string, engine?: Engine) => {
let openTag = "```";
if (engine) {
openTag += engineNameV1(engine).toLowerCase();
+ } else {
+ openTag += "SQL";
}
const closeTag = "```";
return [openTag, statement, closeTag].join("\n");
diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
index d1b0a6706a..9900972604 100644
--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
@@ -14,8 +14,10 @@ export type SuggestionContext = {
ready: boolean;
state: "LOADING" | "IDLE" | "ENDED";
used: Set<string>;
- consume: (sug: string) => void;
+ current: () => string | undefined;
+ consume: () => void;
fetch: () => Promise<string[]>; // returns empty means reaches the end
+ next: () => Promise<string | undefined>; // returns next suggestion or empty (ended)
};
const cache = ref(new Map<string, SuggestionContext>());
@@ -38,6 +40,7 @@ export const useDynamicSuggestions = () => {
});
const requestAI = async (messages: OpenAIMessage[]) => {
+ await new Promise((resolve) => setTimeout(resolve, 1000));
const body = {
model: "gpt-3.5-turbo",
messages,
@@ -86,22 +89,28 @@ export const useDynamicSuggestions = () => {
schema,
key: keyOf(schema),
suggestions: [],
+ index: 0,
state: "IDLE",
ready: false,
used: new Set(),
- consume(sug) {
+ current() {
+ const { suggestions } = suggestion;
+ return head(suggestions);
+ },
+ consume() {
const { suggestions, used } = suggestion;
- const index = suggestions.indexOf(sug);
- if (index >= 0) {
- suggestions.splice(index, 1);
- }
+ const sug = suggestion.current();
+ if (!sug) return;
+ suggestions.shift();
used.add(sug);
if (suggestions.length === 0) {
suggestion.fetch();
}
},
async fetch() {
- const { used, suggestions, key } = suggestion;
+ const { state, used, suggestions, key } = suggestion;
+ if (state === "ENDED") return [];
+
const commands = [
`You are an assistant who works as a Magic: The Suggestion card designer. Create cards that are in the following card schema and JSON format. OUTPUT MUST FOLLOW THIS CARD SCHEMA AND JSON FORMAT. DO NOT EXPLAIN THE CARD.`,
`{"suggestion-1": "What is the average salary of employees in each department?", "suggestion-2": "What is the average salary of employees in each department?", "suggestion-3": "What is the average salary of employees in each department?"}`,
@@ -131,11 +140,13 @@ export const useDynamicSuggestions = () => {
];
suggestion.state = "LOADING";
- const more = (await requestAI(messages)).filter((sug) => {
- if (used.has(sug)) return false;
- if (suggestions.includes(sug)) return false;
- return true;
- });
+ const more = uniq(
+ (await requestAI(messages)).filter((sug) => {
+ if (used.has(sug)) return false;
+ if (suggestions.includes(sug)) return false;
+ return true;
+ })
+ );
suggestions.push(...more);
suggestion.state = more.length === 0 ? "ENDED" : "IDLE";
@@ -149,6 +160,19 @@ export const useDynamicSuggestions = () => {
return more;
},
+ async next() {
+ const originalState = suggestion.state;
+ if (originalState === "ENDED") return;
+ const curr = suggestion.current();
+ if (curr) {
+ suggestion.used.add(curr);
+ }
+ if (suggestion.suggestions.length === 1) {
+ await suggestion.fetch();
+ }
+ suggestion.suggestions.shift();
+ return suggestion.current();
+ },
});
const stored = storage.load<string[]>(suggestion.key, []);
if (stored && stored.length > 0) {
diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue
index 1610c06236..9b1722b31a 100644
--- a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue
@@ -109,7 +109,6 @@ const options = computed(() => {
label: t("plugin.ai.actions.find-problems"),
disabled: !statement,
},
- { value: "new-chat", label: t("plugin.ai.actions.new-chat") },
];
return options.filter((opt) => {
if (props.actions && !props.actions.includes(opt.value)) return false;
@@ -153,13 +152,10 @@ const handleSelect = async (action: ChatAction) => {
});
}
}
- if (action === "new-chat") {
- events.emit("new-conversation", { input: "" });
- }
};
const handleClickButton = () => {
- showAIPanel.value = true;
+ showAIPanel.value = !showAIPanel.value;
};
const goConfigure = () => {
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
index 6916a213f7..8f6085c4c0 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
@@ -3,7 +3,12 @@
<GutterBar class="border-r border-control-border" :class="gutterBarClass" />
<div class="flex-1 overflow-y-hidden overflow-x-auto" :class="contentClass">
- <slot v-if="!viewState || viewState.view === 'CODE'" name="code-panel" />
+ <div
+ v-show="!viewState || viewState.view === 'CODE'"
+ class="w-full h-full overflow-hidden"
+ >
+ <slot name="code-panel" />
+ </div>
<template v-if="viewState">
<InfoPanel v-if="viewState.view === 'INFO'" :key="tab?.id" />
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue
index 032da69009..6c0bc533cc 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/DefinitionViewer.vue
@@ -1,18 +1,24 @@
<template>
<Splitpanes
class="default-theme flex flex-row items-stretch flex-1 w-full overflow-hidden"
+ @resized="handleAIPanelResize($event, 1)"
>
<Pane>
<MonacoEditor
:content="content"
:readonly="true"
class="w-full h-full relative"
+ @select-content="handleSelectContent"
@ready="handleEditorReady"
/>
</Pane>
- <Pane v-if="showAIPanel" :size="30" class="overflow-hidden flex flex-col">
+ <Pane
+ v-if="showAIPanel"
+ :size="AIPanelSize"
+ class="overflow-hidden flex flex-col"
+ >
<Suspense>
- <AIChatToSQL />
+ <AIChatToSQL key="ai-chat-to-sql" />
<template #fallback>
<div
class="w-full h-full flex-grow flex flex-col items-center justify-center"
@@ -28,7 +34,7 @@
<script setup lang="ts">
import { computedAsync } from "@vueuse/core";
import { Pane, Splitpanes } from "splitpanes";
-import { computed } from "vue";
+import { computed, ref } from "vue";
import { BBSpin } from "@/bbkit";
import {
MonacoEditor,
@@ -50,13 +56,15 @@ const props = defineProps<{
format?: boolean;
}>();
-defineEmits<{
+const emit = defineEmits<{
+ (event: "select-content", content: string): void;
(event: "back"): void;
}>();
-const { showAIPanel } = useSQLEditorContext();
+const { showAIPanel, AIPanelSize, handleAIPanelResize } = useSQLEditorContext();
const instanceEngine = computed(() => props.db.instanceResource.engine);
const AIContext = useAIContext();
+const selectedStatement = ref("");
const formatted = computedAsync(
async () => {
@@ -86,6 +94,11 @@ const content = computed(() => {
: props.code;
});
+const handleSelectContent = (selected: string) => {
+ selectedStatement.value = selected;
+ emit("select-content", selected);
+};
+
const handleEditorReady = (
monaco: MonacoModule,
editor: IStandaloneCodeEditor
@@ -99,11 +112,12 @@ const handleEditorReady = (
showAIPanel.value = true;
if (action !== "explain-code") return;
+ const statement = selectedStatement.value || content.value;
await nextAnimationFrame();
AIContext.events.emit("send-chat", {
content: promptUtils.explainCode(
- props.code,
+ statement,
props.db.instanceResource.engine
),
newChat,
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue
index 662d6aa876..6f869efd76 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue
@@ -41,7 +41,7 @@
</NCheckbox>
<OpenAIButton
size="small"
- :statement="view.definition"
+ :statement="selectedStatement || view.definition"
:actions="['explain-code']"
/>
</div>
@@ -53,6 +53,7 @@
:db="db"
:code="view.definition"
:format="format"
+ @select-content="selectedStatement = $event"
/>
<ColumnsTable
v-show="state.mode === 'COLUMNS'"
@@ -76,7 +77,7 @@
import { useLocalStorage } from "@vueuse/core";
import { ChevronLeftIcon, CodeIcon, FileSymlinkIcon } from "lucide-vue-next";
import { NButton, NCheckbox, NTab, NTabs } from "naive-ui";
-import { computed, h, reactive, watch } from "vue";
+import { computed, h, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { ColumnIcon, ViewIcon } from "@/components/Icon";
import { SearchBox } from "@/components/v2";
@@ -115,6 +116,7 @@ const format = useLocalStorage<boolean>(
"bb.sql-editor.editor-panel.code-viewer.format",
false
);
+const selectedStatement = ref("");
const tabItems = computed(() => {
const items = [
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue
index fcc72b258e..f18a65f85b 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue
@@ -17,7 +17,7 @@
</NCheckbox>
<OpenAIButton
size="small"
- :statement="code"
+ :statement="selectedStatement || content"
:actions="['explain-code']"
/>
</div>
@@ -25,6 +25,7 @@
<Splitpanes
class="default-theme flex flex-row items-stretch flex-1 w-full overflow-hidden"
+ @resized="handleAIPanelResize($event, 1)"
>
<Pane>
<MonacoEditor
@@ -35,12 +36,17 @@
callback: handleFormatContent,
}"
class="w-full h-full relative"
+ @select-content="selectedStatement = $event"
@ready="handleEditorReady"
/>
</Pane>
- <Pane v-if="showAIPanel" :size="30" class="overflow-hidden flex flex-col">
+ <Pane
+ v-if="showAIPanel"
+ :size="AIPanelSize"
+ class="overflow-hidden flex flex-col"
+ >
<Suspense>
- <AIChatToSQL />
+ <AIChatToSQL key="ai-chat-to-sql" />
<template #fallback>
<div
class="w-full h-full flex-grow flex flex-col items-center justify-center"
@@ -58,7 +64,7 @@ import { computedAsync, useLocalStorage } from "@vueuse/core";
import { ChevronLeftIcon } from "lucide-vue-next";
import { NButton, NCheckbox } from "naive-ui";
import { Pane, Splitpanes } from "splitpanes";
-import { computed } from "vue";
+import { computed, ref } from "vue";
import { BBSpin } from "@/bbkit";
import {
MonacoEditor,
@@ -85,13 +91,14 @@ defineEmits<{
(event: "back"): void;
}>();
-const { showAIPanel } = useSQLEditorContext();
+const { showAIPanel, AIPanelSize, handleAIPanelResize } = useSQLEditorContext();
const AIContext = useAIContext();
const format = useLocalStorage<boolean>(
"bb.sql-editor.editor-panel.code-viewer.format",
false
);
const instanceEngine = computed(() => props.db.instanceResource.engine);
+const selectedStatement = ref("");
const formatted = computedAsync(
async () => {
@@ -139,10 +146,12 @@ const handleEditorReady = (
showAIPanel.value = true;
if (action !== "explain-code") return;
+ const statement = selectedStatement.value || content.value;
+
await nextAnimationFrame();
AIContext.events.emit("send-chat", {
content: promptUtils.explainCode(
- props.code,
+ statement,
props.db.instanceResource.engine
),
newChat,
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
index ba9277df5e..869e9763a2 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
@@ -28,7 +28,6 @@
import { storeToRefs } from "pinia";
import { v1 as uuidv1 } from "uuid";
import { computed, nextTick, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
import type {
AdviceOption,
IStandaloneCodeEditor,
@@ -62,11 +61,14 @@ const emit = defineEmits<{
(e: "execute", params: SQLEditorQueryParams): void;
}>();
-const { t } = useI18n();
const tabStore = useSQLEditorTabStore();
const sheetAndTabStore = useWorkSheetAndTabStore();
const uiStateStore = useUIStateStore();
-const { showAIPanel, events: editorEvents } = useSQLEditorContext();
+const {
+ showAIPanel,
+ pendingInsertAtCaret,
+ events: editorEvents,
+} = useSQLEditorContext();
const { currentTab, isSwitchingTab } = storeToRefs(tabStore);
const AIContext = useAIContext();
const pendingFormatContentCommand = ref(false);
@@ -217,11 +219,11 @@ const handleEditorReady = (
}
if (action === "new-chat") {
const statement = tab?.selectedStatement ?? "";
- const inputs: string[] = [];
- if (statement) {
- inputs.push(`// ${t("plugin.ai.text-to-sql-placeholder")}`);
- inputs.push(promptUtils.wrapStatementMarkdown(statement));
- }
+ if (!statement) return;
+ const inputs = [
+ "", // just an empty line
+ promptUtils.wrapStatementMarkdown(statement),
+ ];
AIContext.events.emit("new-conversation", {
input: inputs.join("\n"),
});
@@ -263,6 +265,33 @@ const handleEditorReady = (
},
{ immediate: true }
);
+
+ watch(
+ pendingInsertAtCaret,
+ () => {
+ const text = pendingInsertAtCaret.value;
+ if (!text) return;
+ pendingInsertAtCaret.value = undefined;
+
+ requestAnimationFrame(() => {
+ const selection = editor.getSelection();
+ const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;
+ const range =
+ selection ??
+ new monaco.Range(maxLineNumber + 1, 1, maxLineNumber + 1, 1);
+ editor.executeEdits("bb.event.insert-at-caret", [
+ {
+ forceMoveMarkers: true,
+ text,
+ range,
+ },
+ ]);
+ editor.focus();
+ editor.revealLine(range.startLineNumber);
+ });
+ },
+ { immediate: true }
+ );
};
const updateAdvices = (
tab: SQLEditorTab,
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
index 44aaed6aab..f966ebb03c 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
@@ -9,7 +9,11 @@
<template v-if="isDisconnected || allowReadonlyMode">
<EditorAction @execute="handleExecute" />
- <Splitpanes v-if="tab" class="default-theme overflow-hidden">
+ <Splitpanes
+ v-if="tab"
+ class="default-theme overflow-hidden"
+ @resized="handleAIPanelResize($event, 1)"
+ >
<Pane>
<Suspense>
<SQLEditor @execute="handleExecute" />
@@ -24,11 +28,11 @@
</Pane>
<Pane
v-if="showAIPanel"
- :size="33"
+ :size="AIPanelSize"
class="overflow-hidden flex flex-col"
>
<Suspense>
- <AIChatToSQL />
+ <AIChatToSQL key="ai-chat-to-sql" />
<template #fallback>
<div
class="w-full h-full flex-grow flex flex-col items-center justify-center"
@@ -88,7 +92,7 @@ const SQLEditor = defineAsyncComponent(() => import("./SQLEditor.vue"));
const tabStore = useSQLEditorTabStore();
const { currentTab: tab, isDisconnected } = storeToRefs(tabStore);
const { instance } = useConnectionOfCurrentSQLEditorTab();
-const { showAIPanel } = useSQLEditorContext();
+const { showAIPanel, AIPanelSize, handleAIPanelResize } = useSQLEditorContext();
const allowReadonlyMode = computed(() => {
if (isDisconnected.value) return false;
diff --git a/frontend/src/views/sql-editor/SQLEditorHomePage.vue b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
index 8a1879003e..9f5095f7f2 100644
--- a/frontend/src/views/sql-editor/SQLEditorHomePage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
@@ -106,7 +106,11 @@ const state = reactive<LocalState>({
const router = useRouter();
const databaseStore = useDatabaseV1Store();
const tabStore = useSQLEditorTabStore();
-const { events: editorEvents, showConnectionPanel } = useSQLEditorContext();
+const {
+ events: editorEvents,
+ showConnectionPanel,
+ pendingInsertAtCaret,
+} = useSQLEditorContext();
const { showPanel: showSheetPanel } = useSheetContext();
const { currentTab, isDisconnected } = storeToRefs(tabStore);
@@ -146,9 +150,23 @@ useEmitteryEventListener(
}
);
-provideEditorPanelContext({
+const editorPanelContext = provideEditorPanelContext({
tab: currentTab,
});
+
+useEmitteryEventListener(
+ editorEvents,
+ "insert-at-caret",
+ async ({ content }) => {
+ if (!tabStore.currentTab) return;
+ editorPanelContext.updateViewState({
+ view: "CODE",
+ });
+ requestAnimationFrame(() => {
+ pendingInsertAtCaret.value = content;
+ });
+ }
+);
</script>
<style lang="postcss">
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
index ab6b3f796e..9414bc82b4 100644
--- a/frontend/src/views/sql-editor/context.ts
+++ b/frontend/src/views/sql-editor/context.ts
@@ -1,3 +1,4 @@
+import { useLocalStorage } from "@vueuse/core";
import Emittery from "emittery";
import type { InjectionKey, Ref } from "vue";
import { inject, provide, ref } from "vue";
@@ -7,6 +8,9 @@ import type { Worksheet } from "@/types/proto/v1/worksheet_service";
export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY";
+// 30% by default
+export const storedAIPanelSize = useLocalStorage("bb.plugin.ai.panel-size", 30);
+
type SQLEditorEvents = Emittery<{
"save-sheet": {
tab: SQLEditorTab;
@@ -28,12 +32,16 @@ type SQLEditorEvents = Emittery<{
start: { line: number; column: number };
end?: { line: number; column: number };
};
+ "insert-at-caret": {
+ content: string;
+ };
}>;
export type SQLEditorContext = {
asidePanelTab: Ref<AsidePanelTab>;
showConnectionPanel: Ref<boolean>;
showAIPanel: Ref<boolean>;
+ AIPanelSize: Ref<number>;
schemaViewer: Ref<
| {
database: ComposedDatabase;
@@ -43,9 +51,12 @@ export type SQLEditorContext = {
| undefined
>;
+ pendingInsertAtCaret: Ref<string | undefined>;
+
events: SQLEditorEvents;
maybeSwitchProject: (project: string) => Promise<string>;
+ handleAIPanelResize: (panes: { size: number }[], index?: number) => void;
};
export const KEY = Symbol(
@@ -62,7 +73,9 @@ export const provideSQLEditorContext = () => {
asidePanelTab: ref("WORKSHEET"),
showConnectionPanel: ref(false),
showAIPanel: ref(false),
+ AIPanelSize: storedAIPanelSize,
schemaViewer: ref(undefined),
+ pendingInsertAtCaret: ref(),
events: new Emittery(),
maybeSwitchProject: (project) => {
@@ -72,6 +85,11 @@ export const provideSQLEditorContext = () => {
}
return Promise.resolve(editorStore.project);
},
+ handleAIPanelResize: (panes, index = 0) => {
+ if (panes.length <= index) return;
+ const { size } = panes[index];
+ storedAIPanelSize.value = size;
+ },
};
provide(KEY, context);