Skip to content

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

refactor(react): migrate ai plugin (#20330)

ecmadaoe19181bfb01a
diff --git a/docs/superpowers/specs/2026-05-12-sql-editor-react-migration-stage-22-design.md b/docs/superpowers/specs/2026-05-12-sql-editor-react-migration-stage-22-design.md
new file mode 100644
index 0000000000..5d3e6816c2
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-12-sql-editor-react-migration-stage-22-design.md
@@ -0,0 +1,419 @@
+# SQL Editor React Migration — Stage 22 Design
+
+**Date:** 2026-05-12
+**Author:** [email protected]
+**Status:** Draft
+
+## 1. Goal & non-goals
+
+**Goal:** Port the AI plugin's Vue component tree under
+`frontend/src/plugins/ai/components/` to React, swap the two
+`<VueMount component={AIChatToSQLBridgeHost}>` call sites in the SQL
+Editor's host shells to render the React `<AIChatToSQL>` directly, and
+delete both the Vue tree and the reverse-bridge primitive
+(`frontend/src/react/components/VueMount.tsx`) — that primitive's only
+consumer is the AI plugin. After this stage the SQL Editor surface and
+everything mounted inside it is 100% React.
+
+**Non-goals:**
+- The framework-agnostic TS layers under `plugins/ai/{logic,store,types}/`
+ are already shared by React callers (`OpenAIButton.tsx`,
+ `StandardPanel/SQLEditor.tsx`, etc.). They stay. Only behavioural fixes
+ needed to bridge Vue-Ref-shaped APIs (`useChatByTab` returning
+ `ComputedRef<AIChatInfo>`) to React-friendly shapes are in scope. New
+ parallel React helpers may be added alongside; the Vue helpers can be
+ retired once nothing imports them.
+- The AI feature itself (prompt format, conversation/store schema,
+ AICompletion RPC, persistence). Parity port only.
+- The reverse-bridge file `VueMount.tsx` is deleted once both mount
+ points swap, but **`ReactPageMount`** (the *forward* bridge that lets
+ Vue host React) stays — it's still used for `<ReactPageMount
+ page="SQLEditorLayout">` from `router/sqlEditor.ts`.
+- New AI-side features (e.g. richer markdown, attachments, streaming
+ rendering) — explicitly out of scope.
+- Test coverage for AI flows beyond what the migration directly
+ benefits from. The Vue tree has zero existing tests; we add tests
+ only for new React seams whose contract is non-obvious (see §5).
+
+## 2. Inventory
+
+**In scope (~1,256 LOC of `plugins/ai/components/`):**
+
+| File | LOC | Notes |
+|---|---|---|
+| `components/ChatPanel.vue` | 187 | Root visible shell. Hosts `ActionBar`, `ChatView`, `DynamicSuggestions`, `PromptInput`, `HistoryPanel`. Owns the `requestAI(query)` orchestrator (createMessage USER → createMessage AI LOADING → `sqlServiceClientConnect.aICompletion` → update). |
+| `components/ProvideAIContext.vue` | 124 | Sets up the `AIContext` via Vue `provide`. Subscribes to two events on the shared `aiContextEvents`: `new-conversation` (reuse-if-empty / create-new) and `send-chat`. Fetches the AI setting on mount. |
+| `components/ChatView/Markdown/CodeBlock.vue` | 129 | SQL `<MonacoEditor>` snippet card with Run / Insert-at-Caret / Copy actions. Reads `useElementSize` of nearest `.message` ancestor for adaptive width. Emits `run-statement` / `insert-at-caret`. |
+| `components/HistoryPanel/ConversationList.vue` | 129 | Listing of past conversations: select, rename (via `ConversationRenameDialog`), delete (with `NPopconfirm`). |
+| `components/PromptInput.vue` | 116 | `NInput type="textarea"` autosize 1-10 rows. Emits `enter` on plain Enter (Shift+Enter inserts newline). Focuses on mount + on `new-conversation`. Reacts to `pendingPreInput` (one-shot input prefill). |
+| `components/DynamicSuggestions.vue` | 102 | Calls `useDynamicSuggestions()` which streams 3 prompt suggestions. Click → `@enter`. |
+| `components/ChatView/ChatView.vue` | 92 | Auto-scroll-to-bottom message list. `mode: "CHAT" \| "VIEW"`. Provides `ChatViewContext` so child views can read `mode`. |
+| `components/HistoryPanel/ConversationRenameDialog.vue` | 88 | Rename modal with a single `NInput`. |
+| `components/ActionBar.vue` | 58 | Top bar: New chat / History / Close buttons. Emits `new-conversation`. |
+| `components/ChatView/AIMessageView.vue` | 42 | AI bubble: spinner while LOADING, error pill on FAILED, otherwise `<Markdown>` of `message.content` with `codeBlockProps={ width: 0.85 }`. |
+| `components/ChatView/Markdown/Markdown.vue` | 38 | `unified().use(remarkParse).use(remarkGfm)` parses content, hands the AST to `AstToVNode` with custom `code` / `inlineCode` / `image` slots. |
+| `components/HistoryPanel/HistoryPanel.vue` | 29 | Drawer wrapping `ConversationList` + `ChatView mode="VIEW"`. |
+| `components/ChatView/Markdown/InsertAtCaretIcon.vue` | 28 | Inline SVG icon (parametrized by `size`). |
+| `components/ChatView/Markdown/AstToVNode.vue` | 24 | Receives mdast root, walks via `mdastToVNode[type]` (in `utils.ts`), uses Vue slots for custom rendering of `code` / `inlineCode` / `image`. |
+| `components/AIChatToSQLBridgeHost.vue` | 23 | Bridge entry: `<ProvideAIContext><Suspense><AIChatToSQL/></Suspense></ProvideAIContext>`. **Deleted in Phase 4** — React host renders `<AIChatToSQL />` directly. |
+| `components/ChatView/UserMessageView.vue` | 21 | User bubble (text). |
+| `components/ChatView/EmptyView.vue` | 16 | Empty-state placeholder shown when a `VIEW`-mode conversation has no messages. |
+| `components/AIChatToSQL.vue` | 10 | Top-level async wrapper: `await import("./ChatPanel.vue")`, then renders `<ChatPanel v-if="aiSetting.enabled">`. |
+
+**Already TS (read by React; no migration needed):**
+- `plugins/ai/logic/{context,events,prompt,useChatByTab,useDynamicSuggestions,utils,index}.ts`
+- `plugins/ai/store/{conversation,index}.ts`
+- `plugins/ai/types/{context,conversation,index}.ts`
+- `plugins/ai/components/{state,editor-actions}.ts`
+- `plugins/ai/components/ChatView/{context,types,index}.ts`
+- `plugins/ai/components/ChatView/Markdown/{utils,index}.ts` — utils stays but loses the `h(...)` Vue imports (see §3).
+- `plugins/ai/components/HistoryPanel/index.ts`
+
+**External mount points (only two):**
+- `frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx:107` — `<VueMount component={AIChatToSQLBridgeHost} />`
+- `frontend/src/react/components/sql-editor/Panels/Panels.tsx:233` — same
+
+Both swap to `<AIChatToSQL />` in Phase 4.
+
+**Files that import the AI plugin from React (post-migration these
+keep importing from `plugins/ai/` — TS layers only):**
+- `react/components/sql-editor/OpenAIButton.tsx`
+- `react/components/sql-editor/StandardPanel/SQLEditor.tsx`
+- `react/components/sql-editor/Panels/common/CodeViewer.tsx`
+
+## 3. External deps & primitives
+
+| Vue dep | React replacement | Status |
+|---|---|---|
+| `NInput type="textarea"` autosize (PromptInput) | `react-textarea-autosize` (already a Stage-17 dep for the Monaco-adjacent prompt boxes) or a hand-rolled `<textarea>` with rows-by-content. Probably the autosize lib for parity. | Existing dep — verify |
+| `NPopover` (PromptInput suffix shortcut hint, CodeBlock action tooltips, ConversationList delete confirm) | Shared `Tooltip` from `@/react/components/ui/tooltip`. | ✓ |
+| `NPopconfirm` (ConversationList delete) | shadcn `AlertDialog` from `@/react/components/ui/alert-dialog`. | ✓ |
+| `NSpin` (ChatPanel loading, AIMessageView LOADING) | `Loader2` from `lucide-react` with `animate-spin`, matches Stage 17/18 pattern. | ✓ |
+| `Drawer` / `DrawerContent` (HistoryPanel) | shadcn `Sheet` from `@/react/components/ui/sheet` with `width="wide"` (the drawer is `w-[calc(100vw-8rem)] max-w-6xl`; ~the wide tier). | ✓ |
+| `Vue's provide / inject` (`provideAIContext`) | React Context. New file: `plugins/ai/react/context.tsx` exposing `<AIContextProvider>` + `useAIContext()`. The provider reads Pinia + module-level singletons via `useVueState` and Memoizes the `AIContext`-shaped value. | New |
+| `useElementSize` from `@vueuse/core` (CodeBlock, ChatView auto-scroll) | `ResizeObserver` in a `useResizeObserver` hook — already a pattern used by Stage 20's `useTableResize` and Stage 22's Navigator (`SchemaDiagram`). | Local hook |
+| `Vue h()` in `Markdown/utils.ts` | `React.createElement` (`createElement` / `cloneElement`). Same mdast-walk logic; replace `h(tag, props, children)` with `createElement(tag, props, children)` and `class` → `className`, plus React-style props (`onClick`, `aria-…`). | Rewrite |
+| `useEmitteryEventListener` composable | Plain `useEffect(() => { const off = events.on(name, cb); return off; }, deps)`. Pattern already in use across Stages 16-20. | ✓ |
+| `MonacoEditor` (Vue component, used by CodeBlock) | The React `MonacoEditor` shipped in Stage 14. Import path: `@/react/components/MonacoEditor`. | ✓ |
+| `CopyButton` from `@/components/v2` (CodeBlock copy action) | A small React copy icon button (lucide `Copy` + `navigator.clipboard.writeText`, with a 1-second "Copied" state). Either import the existing React `CopyButton` if one exists in `react/components/`, or inline it — it's ~20 LOC. | Verify / inline |
+| `HighlightCodeBlock` (Vue, used by Markdown for inline code) | React equivalent in `react/components/` if it exists, otherwise a thin styled `<code>` with the project's Shiki tokens. Inline code is short enough that a plain styled `<code>` is fine for parity. | Verify / inline |
+| `i18n-t` with `<template #create>` slot (ChatView's "select-or-create" prompt) | `Trans` component manual split (mirrors the SelectionCopyTooltips fix from Stage 20 — `Trans` v17 wipes slot children on empty placeholder tags). | Pattern already established |
+| `Suspense` around `<AIChatToSQL>` (BridgeHost) | `React.Suspense` around `React.lazy(() => import('./ChatPanel'))` inside `AIChatToSQL.tsx`. Mirrors the Vue `await import('./ChatPanel.vue')` pattern. | ✓ |
+
+## 4. Architecture & phases
+
+Single PR, four internal phases. Each phase is internally consistent
+(builds + lints cleanly) so review can pick up at phase boundaries.
+
+```
+plugins/ai/
+├── components/ ← deleted at end
+│ └── *.vue
+└── react/ ← NEW (the React tree)
+ ├── context.tsx ← AIContextProvider + useAIContext
+ ├── AIChatToSQL.tsx ← lazy + Suspense wrapper, gated on aiSetting.enabled
+ ├── ChatPanel.tsx ← orchestrator (requestAI), composes panels
+ ├── ActionBar.tsx
+ ├── PromptInput.tsx
+ ├── DynamicSuggestions.tsx
+ ├── ChatView/
+ │ ├── ChatView.tsx
+ │ ├── AIMessageView.tsx
+ │ ├── UserMessageView.tsx
+ │ ├── EmptyView.tsx
+ │ ├── context.tsx ← Mode context (CHAT | VIEW)
+ │ └── Markdown/
+ │ ├── Markdown.tsx
+ │ ├── AstToReact.tsx ← renamed from AstToVNode
+ │ ├── CodeBlock.tsx
+ │ ├── InsertAtCaretIcon.tsx
+ │ └── utils.ts ← walker rewritten on createElement
+ └── HistoryPanel/
+ ├── HistoryPanel.tsx
+ ├── ConversationList.tsx
+ └── ConversationRenameDialog.tsx
+```
+
+Re-exports from `plugins/ai/index.ts` flip from the Vue components to
+the React components at the end of Phase 4.
+
+### Phase 1 — React context provider (`plugins/ai/react/context.tsx`)
+
+Replaces `ProvideAIContext.vue`. The React provider:
+
+1. Reads Pinia / Vue refs via `useVueState`:
+ - `aiSetting` (from `settingV1Store.getSettingByName(AI)`), with `getOrFetchSettingByName(AI, true)` fired in a mount-effect.
+ - `instance` + `engine` (from `useConnectionOfCurrentSQLEditorTab()`).
+ - `database` + `databaseMetadata` (from `useMetadata`).
+ - `schema` (from `tabStore.currentTab?.connection.schema`).
+2. Sets up React-side state: `showHistoryDialog` (`useState(false)`),
+ `pendingSendChat` (`useRef<{content:string} | undefined>()` — these
+ are one-shot triggers, not rendered state, so refs suffice with a
+ `bumpSignal` counter for the dependent effects).
+3. Subscribes to `aiContextEvents`:
+ - `new-conversation` → "reuse if current chat is empty, otherwise
+ create" + flip `pendingPreInput`. Identical semantics to the Vue
+ `useEmitteryEventListener` block.
+ - `send-chat` → close history dialog, optionally create a new
+ conversation, then set `pendingSendChat`.
+4. `useCurrentChat(context)` is replaced by a React-side
+ `useCurrentChat()` hook that reads through the context, exposing
+ plain values (`list`, `ready`, `selected`, `setSelected`) instead of
+ Vue refs. The existing TS `useCurrentChat` Vue helper stays for
+ imports outside the React tree (none after this stage; will be
+ reviewed at the end of Phase 4).
+
+**Behavioural pitfalls to preserve:**
+- The `pendingSendChat` write is wrapped in `requestAnimationFrame(...)`
+ in the Vue version. The reason is the consumer (`ChatPanel`) has a
+ `watch([ready, pendingSendChat], …, { flush: "post" })` that fires
+ after the conversation creation settles. The React equivalent:
+ reuse the same `requestAnimationFrame` so the consumer effect runs
+ on the next frame, after `selected` mutates. **Don't** drop the rAF
+ — without it, a race fires the send-chat effect against the still-old
+ conversation.
+- `aiContextEvents` is a module-level singleton. The provider stores
+ the same reference; React's `useEffect(off, [])` cleanup unsubs.
+- `useChatByTab` keeps the module-level `chatsByTab: Map<string,
+ AIChatInfo>` cache. We don't move that cache into the React provider
+ — React mount/unmount cycles must NOT invalidate per-tab fetch state.
+
+### Phase 2 — Leaf components (Markdown + ChatView + HistoryPanel)
+
+Bottom-up. Each leaf has zero React siblings yet, so they slot into the
+still-Vue tree via `<ReactPageMount>` for in-progress testing if needed
+(but in practice the full Phase-2-through-4 chain lands together).
+
+**Markdown subtree** (4 files):
+- `utils.ts` — port the mdast walker from `h(...)` to
+ `createElement(...)`. Identical control flow. Slots become a small
+ `Slots` interface `{ code?: (node)=>ReactNode; inlineCode?: ...; image?: ...; }`.
+- `AstToReact.tsx` — receives `ast: Root` + `slots: Slots`, returns
+ `mdastToReact[ast.type](ast, { slots, definitionById: new Map() })`.
+- `Markdown.tsx` — `useMemo` over the `unified().use(remarkParse).use(remarkGfm).parse(content)` AST. Passes slots `{ code, inlineCode, image }`.
+- `CodeBlock.tsx`:
+ - Adaptive width via `useElementSize`-shaped local hook on the
+ nearest `.message` ancestor (`findAncestor(containerRef, ".message")`).
+ - `<MonacoEditor>` from the React port (autoHeight `min: 20`, `max:
+ 120`, `padding: 2`; same opts as Vue).
+ - Run button → `events.emit("run-statement", { statement: code })` +
+ `setShowHistoryDialog(false)`.
+ - Insert-at-caret button → `sqlEditorEvents.emit("insert-at-caret", { content: code })` +
+ `setShowHistoryDialog(false)`.
+ - Copy → `<CopyButton content={code} />` (use existing React copy
+ primitive; if none, inline ~15 LOC).
+- `InsertAtCaretIcon.tsx` — inline SVG, prop `size`.
+
+**ChatView subtree** (4 + 1):
+- `context.tsx` — React Context for `mode: "CHAT" | "VIEW"` (replaces
+ Vue's `provideChatViewContext`).
+- `ChatView.tsx` — scroller div + `auto-scroll-to-bottom` via
+ `useResizeObserver` on the inner container; renders a message-list
+ fork (`UserMessageView` / `AIMessageView`) keyed by `message.id`.
+- `AIMessageView.tsx` — LOADING → spinner; FAILED → `text-error` pill;
+ DONE → `<Markdown content={message.content} codeBlockProps={{ width: 0.85 }} />`.
+- `UserMessageView.tsx` — plain text bubble.
+- `EmptyView.tsx` — placeholder card.
+
+**HistoryPanel subtree** (3):
+- `HistoryPanel.tsx` — `<Sheet>` keyed off `showHistoryDialog`,
+ wide width tier. Two columns: `<ConversationList>` (sidebar) +
+ `<ChatView mode="VIEW" conversation={selected} />`.
+- `ConversationList.tsx` — list + rename + delete (AlertDialog confirm). State:
+ `editing: Conversation | undefined` drives the `ConversationRenameDialog`.
+- `ConversationRenameDialog.tsx` — simple shadcn `<Dialog>` + `<Input>` + Save/Cancel.
+
+### Phase 3 — Top panels
+
+- `ActionBar.tsx` — three Buttons: New chat (emits `new-conversation`),
+ History (toggles `showHistoryDialog`), Close (only when host listens
+ for a `close` event; verify against existing Vue `defineEmits` —
+ current ActionBar has no `close` so this is just New / History).
+- `PromptInput.tsx`:
+ - `react-textarea-autosize` (or a hand-rolled rows controller —
+ decision per the dep check in §3) bound to local state.
+ - Enter → `applyValue` if non-empty, Shift+Enter inserts newline.
+ - `useEffect` on mount focuses the textarea (`autoFocus` won't
+ survive a mode-switch remount in some flows; explicit focus is
+ safer).
+ - Reacts to `pendingPreInput`: when it transitions to a non-empty
+ string, set `state.value = pendingPreInput`, clear the ref,
+ optionally `requestAnimationFrame` so the parent effect fires
+ after layout. Mirrors the Vue `watch(pendingPreInput, … { flush: "post" })`.
+ - Listens for `new-conversation` to re-focus the input.
+- `DynamicSuggestions.tsx`:
+ - `useDynamicSuggestions()` already exists in `logic/`. Verify its
+ return shape works inside a React component — if it returns Vue
+ refs, wrap with `useVueState` getters. If it imperatively kicks
+ off a fetch on mount, wrap that call in `useEffect`.
+ - Renders up to 3 clickable suggestion chips. Click → `@enter`.
+- `ChatPanel.tsx`:
+ - The heavy `requestAI(query)` orchestrator ports as a `useCallback`
+ over `selectedConversation`, `tab`, `context`. Watch out:
+ `store.createMessage` mutates the conversation list — verify the
+ React state subscription (`useVueState(() => store.conversationList)`
+ triggers re-renders).
+ - The two Vue `watch` blocks:
+ - `watch([ready, conversationList], …)` — converts to a `useEffect`
+ with `[ready, conversationList.length === 0]` (we only need the
+ transition to "empty + ready", not full identity).
+ - `watch([ready, pendingSendChat], … { flush: "post" })` — converts
+ to a `useEffect` with a `setTimeout(0)` or `requestAnimationFrame`
+ to mimic `flush: "post"` (run after the next commit). The
+ pendingSendChat trigger comes via the provider's ref + bumpSignal;
+ the effect checks `if (!pendingSendChat.current) return;`.
+ - `onConnectionChanged` Vue helper → if it currently only sets
+ `showHistoryDialog.value = false`, a single `useEffect` on
+ `[currentTab?.connection.instance, currentTab?.connection.database]`
+ that calls `setShowHistoryDialog(false)` is sufficient.
+
+### Phase 4 — Outer wrapper + mount-point flip + cleanup
+
+- `plugins/ai/react/AIChatToSQL.tsx`:
+ ```tsx
+ const ChatPanel = lazy(() => import("./ChatPanel"));
+ export function AIChatToSQL() {
+ const { aiSetting } = useAIContext();
+ if (!aiSetting.enabled) return null;
+ return <Suspense fallback={null}><ChatPanel /></Suspense>;
+ }
+ ```
+- `plugins/ai/index.ts` — re-exports flip:
+ ```ts
+ export * from "./types";
+ export * from "./components/editor-actions";
+ export { AIChatToSQL } from "./react/AIChatToSQL";
+ export { AIContextProvider } from "./react/context";
+ // `AIChatToSQLBridgeHost` and `ProvideAIContext` no longer exported.
+ ```
+- Mount points:
+ - `StandardPanel/StandardPanel.tsx:107` —
+ ```diff
+ -<VueMount component={AIChatToSQLBridgeHost} />
+ +<AIContextProvider>
+ + <AIChatToSQL />
+ +</AIContextProvider>
+ ```
+ - `Panels/Panels.tsx:233` — identical change.
+- Delete:
+ - All 18 `.vue` files under `plugins/ai/components/`.
+ - `plugins/ai/components/AIChatToSQLBridgeHost.vue` (already counted).
+ - `frontend/src/react/components/VueMount.tsx` + its smoke tests (3
+ tests in `VueMount.test.tsx`) — no other consumers.
+- Update memory + any inline comments referencing `VueMount` / `Stage 22`
+ / "AI plugin stub" as live state.
+
+## 5. Per-phase checklist
+
+### Phase 1
+- [ ] `plugins/ai/react/context.tsx` with `AIContextProvider`, `useAIContext`.
+- [ ] React `useCurrentChat()` helper (returns `{ list, ready, selected, setSelected }`, all plain values).
+- [ ] `new-conversation` and `send-chat` listeners attached + cleaned up on unmount.
+- [ ] AI setting fetched on mount (`getOrFetchSettingByName(AI, true)`).
+- [ ] Type-check: `pnpm --dir frontend type-check` green.
+
+### Phase 2
+- [ ] `Markdown/utils.ts` ported (no `h(...)`, no `import "vue"`).
+- [ ] `Markdown.tsx`, `AstToReact.tsx`, `CodeBlock.tsx`, `InsertAtCaretIcon.tsx`.
+- [ ] `ChatView/{ChatView,AIMessageView,UserMessageView,EmptyView,context}.tsx`.
+- [ ] `HistoryPanel/{HistoryPanel,ConversationList,ConversationRenameDialog}.tsx`.
+- [ ] No `.vue` imports left in any new `.tsx` file under `plugins/ai/react/`.
+- [ ] `pnpm --dir frontend test` covering `Markdown` (renders code block / inline code / table / image), `CodeBlock` (run / insert / copy emits events), `ConversationList` (rename / delete confirm wiring).
+
+### Phase 3
+- [ ] `ActionBar.tsx`, `PromptInput.tsx`, `DynamicSuggestions.tsx`, `ChatPanel.tsx`.
+- [ ] `PromptInput` keyboard behaviour matches Vue: Enter = submit non-empty, Shift+Enter = newline, focus on mount + on `new-conversation`.
+- [ ] `ChatPanel.requestAI` builds the prompt-with-schema preamble on the first message exactly like Vue (`promptUtils.declaration(databaseMetadata, engine, schema)`).
+- [ ] `pendingSendChat` flush-post effect uses rAF/setTimeout-0 — verify with a manual test (send-chat → conversation auto-created → request fires once, not on the previous conversation).
+
+### Phase 4
+- [ ] `AIChatToSQL.tsx` with lazy `ChatPanel` + Suspense fallback.
+- [ ] `plugins/ai/index.ts` exports updated.
+- [ ] `StandardPanel.tsx` + `Panels.tsx` swapped.
+- [ ] `plugins/ai/components/` directory deleted.
+- [ ] `react/components/VueMount.tsx` + `VueMount.test.tsx` deleted.
+- [ ] `pnpm --dir frontend check` (no raw `bg-*` colors, no `space-x-*` between buttons, etc.) green.
+- [ ] `pnpm --dir frontend type-check` green.
+- [ ] `pnpm --dir frontend test` green.
+- [ ] No `import.*\.vue` left under `frontend/src/plugins/ai/` (`grep -rn '\.vue"' frontend/src/plugins/ai/` should be empty).
+
+## 6. Manual UX verification
+
+Cover the full happy path + the historically-touchy seams:
+
+1. **Open SQL editor → AI side pane**. `aiSetting.enabled = true`. Panel
+ mounts, prompt input focused, `ActionBar` visible.
+2. **Type a prompt → Enter**. New conversation auto-created if list
+ empty, USER message appears immediately, AI message in LOADING,
+ spinner. AICompletion resolves → markdown rendered, code block
+ shows with Run / Insert-at-Caret / Copy actions.
+3. **Run** the code block → SQL editor receives `run-statement` event,
+ statement executes.
+4. **Insert-at-caret** the code block → SQL editor caret receives the
+ snippet (the existing `insert-at-caret` event on `sqlEditorEvents`).
+5. **Copy** the code block → clipboard contains the snippet, ephemeral
+ "Copied" indicator.
+6. **History** button → drawer opens; conversation list on the left,
+ selected conversation on the right (`mode="VIEW"`, no input).
+7. **Rename** a conversation → dialog opens with current title, save
+ updates the list.
+8. **Delete** a conversation → AlertDialog confirm, then removed from
+ the list.
+9. **Switch tabs / databases**: conversation list updates to the
+ per-`(instance, database)` cached value. The module-level
+ `chatsByTab` cache survives the React unmount/remount cycle.
+10. **`Shift+Enter`** in PromptInput inserts a newline; `Enter` on
+ empty input is a no-op.
+11. **`pendingPreInput`**: triggered when an external action emits
+ `new-conversation` with an `input` payload (e.g., from
+ `OpenAIButton.tsx`'s "Ask AI about this query"). The PromptInput
+ populates with the seed text without auto-submitting.
+12. **`aiSetting.enabled = false`** → `<AIChatToSQL />` renders `null`;
+ the side pane shows nothing (or the host's "disabled" state).
+
+## 7. Out of scope (deferred)
+
+- Streaming markdown / incremental Monaco code-block render — Vue does
+ one-shot render after `aICompletion` resolves; React mirror does
+ the same. Future enhancement.
+- Conversation export / sharing.
+- Multi-model selection UI — the AI setting picker lives in workspace
+ settings, not in this side pane.
+- Replacing `unified() + remark-parse + remark-gfm` with a lighter
+ parser. Same dep on both sides; revisit only if bundle size becomes
+ a concern.
+
+## 8. Risks & open questions
+
+- **`useDynamicSuggestions()` return shape** — currently a Vue ref
+ bundle. The React port either needs a thin React wrapper that
+ subscribes via `useVueState`, or the original helper needs to be
+ re-shaped to expose plain values. Resolve during Phase 3 by reading
+ the helper source. If the helper is internal-only (no other
+ consumer), refactor in place.
+
+- **`HighlightCodeBlock` Vue dep** — used by `Markdown.vue` for inline
+ code highlighting. Need to either (a) port the Vue component to React,
+ or (b) substitute a plain `<code>` for inline code (Vue inline code
+ uses the highlighter for short snippets where the highlighter usually
+ no-ops anyway). Prefer (b) for parity-with-less-work; revisit if QA
+ shows missing highlights.
+
+- **`CopyButton` import path** — `@/components/v2` is Vue. If no React
+ equivalent exists in `react/components/`, inline a small `<button>`
+ + `lucide` `Copy` icon + clipboard call inside `CodeBlock.tsx`.
+ Decision deferred to first encounter in Phase 2.
+
+- **`<Suspense>` placement** — Vue wraps `<AIChatToSQL>` itself in
+ `<Suspense>` from outside. React's `lazy()` requires the consumer to
+ wrap in `<Suspense>`. The current design puts the boundary inside
+ `AIChatToSQL.tsx`. Alternative: defer the `lazy()` import and ship
+ `ChatPanel` synchronously — saves one Suspense boundary but inflates
+ the initial bundle of every SQL Editor page load (the Vue pattern
+ defers ChatPanel + its mdast deps until the side pane opens). Stick
+ with `lazy()`.
+
+- **Memory update** — `project_sql_editor_react_migration_roadmap.md`
+ needs a Stage 22 status entry once this lands. The "(post-Stage-21,
+ optional)" framing flips to "Complete (2026-MM-DD): AI plugin ported,
+ VueMount bridge deleted." Roadmap is now closed.
diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjs
index cd19d0c95a..5291a10600 100644
--- a/frontend/scripts/check-react-i18n.mjs
+++ b/frontend/scripts/check-react-i18n.mjs
@@ -31,6 +31,11 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const REACT_DIR = resolve(ROOT, "src/react");
const LOCALES_DIR = resolve(REACT_DIR, "locales");
+// Additional React-side source roots outside `src/react/`. The AI plugin
+// keeps its React tree co-located with its framework-agnostic logic at
+// `src/plugins/ai/react/`; include those files when scanning for `t(...)`
+// usage so its i18n keys don't read as "unused".
+const EXTRA_REACT_DIRS = [resolve(ROOT, "src/plugins/ai/react")];
const LOCALES = ["en-US", "zh-CN", "es-ES", "ja-JP", "vi-VN"];
let errors = 0;
@@ -85,6 +90,10 @@ function collectSourceKeys() {
const files = [
...findFiles(REACT_DIR, ".tsx"),
...findFiles(REACT_DIR, ".ts"),
+ ...EXTRA_REACT_DIRS.flatMap((dir) => [
+ ...findFiles(dir, ".tsx"),
+ ...findFiles(dir, ".ts"),
+ ]),
];
const keys = new Set();
// Only match single/double quoted strings — template literals with ${} are dynamic keys
diff --git a/frontend/src/plugins/ai/components/AIChatToSQL.vue b/frontend/src/plugins/ai/components/AIChatToSQL.vue
deleted file mode 100644
index 6a8edf3a1e..0000000000
--- a/frontend/src/plugins/ai/components/AIChatToSQL.vue
+++ /dev/null
@@ -1,10 +0,0 @@
-<template>
- <ChatPanel v-if="aiSetting.enabled" />
-</template>
-
-<script lang="ts" setup>
-import { useAIContext } from "../logic";
-
-const [{ default: ChatPanel }] = await Promise.all([import("./ChatPanel.vue")]);
-const { aiSetting } = useAIContext();
-</script>
diff --git a/frontend/src/plugins/ai/components/AIChatToSQLBridgeHost.vue b/frontend/src/plugins/ai/components/AIChatToSQLBridgeHost.vue
deleted file mode 100644
index abe046942b..0000000000
--- a/frontend/src/plugins/ai/components/AIChatToSQLBridgeHost.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<template>
- <ProvideAIContext>
- <Suspense>
- <AIChatToSQL />
- </Suspense>
- </ProvideAIContext>
-</template>
-
-<script lang="ts" setup>
-/**
- * Self-contained AI chat panel host for use inside a `VueMount` bridge.
- * The bridge spawns an isolated Vue 3 app whose component tree can't see
- * the outer Vue's provide chain — so we re-establish `ProvideAIContext`
- * at the bridge boundary. Pinia + the module-level `aiContextEvents`
- * are singletons, so duplicating the provide doesn't fork state.
- *
- * Mounted from the post-Stage-21 React shells (`StandardPanel`,
- * `Panels`) via `<VueMount component={AIChatToSQLBridgeHost} />`.
- * Removed alongside Stage 22 if/when the AI plugin is ported to React.
- */
-import AIChatToSQL from "./AIChatToSQL.vue";
-import ProvideAIContext from "./ProvideAIContext.vue";
-</script>
diff --git a/frontend/src/plugins/ai/components/ActionBar.vue b/frontend/src/plugins/ai/components/ActionBar.vue
deleted file mode 100644
index f601e3277a..0000000000
--- a/frontend/src/plugins/ai/components/ActionBar.vue
+++ /dev/null
@@ -1,58 +0,0 @@
-<template>
- <div
- class="w-full flex flex-wrap gap-y-1 justify-between sm:items-center px-1 py-1 border-b bg-white"
- >
- <div
- class="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center pl-1"
- >
- <h3>{{ $t("plugin.ai.ai-assistant") }}</h3>
- </div>
-
- <div
- class="action-right gap-x-1 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center"
- >
- <NPopover placement="bottom">
- <template #trigger>
- <NButton
- size="small"
- quaternary
- style="--n-padding: 0 5px"
- @click="showHistoryDialog = true"
- >
- <template #icon>
- <ClockIcon class="w-4 h-4" />
- </template>
- </NButton>
- </template>
- <template #default>
- {{ $t("plugin.ai.conversation.view-history-conversations") }}
- </template>
- </NPopover>
- <NPopover placement="bottom">
- <template #trigger>
- <NButton
- size="small"
- quaternary
- style="--n-padding: 0 5px"
- @click="events.emit('new-conversation', { input: '' })"
- >
- <template #icon>
- <PlusIcon class="w-4 h-4" />
- </template>
- </NButton>
- </template>
- <template #default>
- {{ $t("plugin.ai.conversation.new-conversation") }}
- </template>
- </NPopover>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { ClockIcon, PlusIcon } from "lucide-vue-next";
-import { NButton, NPopover } from "naive-ui";
-import { useAIContext } from "../logic";
-
-const { events, showHistoryDialog } = useAIContext();
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatPanel.vue b/frontend/src/plugins/ai/components/ChatPanel.vue
deleted file mode 100644
index d88a5c257b..0000000000
--- a/frontend/src/plugins/ai/components/ChatPanel.vue
+++ /dev/null
@@ -1,187 +0,0 @@
-<template>
- <div
- v-if="aiSetting.enabled"
- class="w-full h-full flex-1 flex flex-col overflow-hidden"
- >
- <ActionBar />
-
- <ChatView
- v-if="ready"
- :conversation="selectedConversation"
- class="pt-2"
- @enter="requestAI"
- />
- <div
- v-else
- class="flex-1 overflow-hidden relative flex items-center justify-center"
- >
- <NSpin size="small" />
- </div>
-
- <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>
-
- <HistoryPanel />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { create as createProto } from "@bufbuild/protobuf";
-import { head } from "lodash-es";
-import { NSpin } from "naive-ui";
-import { storeToRefs } from "pinia";
-import { reactive, watch } from "vue";
-import { sqlServiceClientConnect } from "@/connect";
-import { useSQLEditorTabStore } from "@/store";
-import {
- type AICompletionRequest_Message,
- AICompletionRequest_MessageSchema,
- AICompletionRequestSchema,
-} from "@/types/proto-es/v1/sql_service_pb";
-import { nextAnimationFrame } from "@/utils";
-import { onConnectionChanged, useAIContext, useCurrentChat } from "../logic";
-import * as promptUtils from "../logic/prompt";
-import { useConversationStore } from "../store";
-import ActionBar from "./ActionBar.vue";
-import ChatView from "./ChatView";
-import DynamicSuggestions from "./DynamicSuggestions.vue";
-import HistoryPanel from "./HistoryPanel";
-import PromptInput from "./PromptInput.vue";
-
-type LocalState = {
- loading: boolean;
-};
-
-const state = reactive<LocalState>({
- loading: false,
-});
-
-const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());
-const store = useConversationStore();
-
-const context = useAIContext();
-const { aiSetting, showHistoryDialog, pendingSendChat } = context;
-const {
- list: conversationList,
- ready,
- selected: selectedConversation,
-} = useCurrentChat();
-
-const requestAI = async (query: string) => {
- const conversation = selectedConversation.value;
- if (!conversation) return;
- const t = tab.value;
- if (!t) return;
-
- const { messageList } = conversation;
- if (messageList.length === 0) {
- // For the first message of a conversation,
- // add extra database schema metadata info if possible
- const engine = context.engine.value;
- const databaseMetadata = context.databaseMetadata.value;
- const schema = context.schema.value;
-
- const prompts: string[] = [];
- prompts.push(promptUtils.declaration(databaseMetadata, engine, schema));
- prompts.push(query);
- const prompt = prompts.join("\n");
- await store.createMessage({
- conversation_id: conversation.id,
- content: query,
- prompt,
- author: "USER",
- error: "",
- status: "DONE",
- });
- 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({
- author: "AI",
- prompt: "",
- content: "",
- error: "",
- conversation_id: conversation.id,
- status: "LOADING",
- });
- const messages: AICompletionRequest_Message[] = [];
- conversation.messageList.forEach((message) => {
- const { author, prompt } = message;
- messages.push(
- createProto(AICompletionRequest_MessageSchema, {
- role: author === "USER" ? "user" : "assistant",
- content: prompt,
- })
- );
- });
- state.loading = true;
- try {
- const request = createProto(AICompletionRequestSchema, { messages });
- const response = await sqlServiceClientConnect.aICompletion(request);
- const text = head(head(response.candidates)?.content?.parts)?.text?.trim();
- console.debug("[AI Assistant] answer:", text);
- if (text) {
- answer.content = text;
- answer.prompt = text;
- }
-
- answer.status = "DONE";
- } catch (err) {
- answer.error = String(err);
- answer.status = "FAILED";
- } finally {
- state.loading = false;
- await store.updateMessage(answer);
- if (conversation.id === conversation.id) {
- if (answer.status === "FAILED") {
- context.events.emit("error", answer.error);
- }
- }
- }
-};
-
-onConnectionChanged(() => {
- showHistoryDialog.value = false;
-});
-
-watch(
- [ready, conversationList],
- async ([ready, list]) => {
- if (ready && list.length === 0) {
- store.createConversation({
- name: "",
- instance: tab.value?.connection.instance ?? "",
- database: tab.value?.connection.database ?? "",
- });
- }
- },
- { immediate: true }
-);
-
-watch(
- [ready, pendingSendChat],
- async ([ready]) => {
- if (!ready) return;
-
- await nextAnimationFrame();
- if (!pendingSendChat.value) return;
- requestAI(pendingSendChat.value.content);
- pendingSendChat.value = undefined;
- },
- {
- immediate: true,
- flush: "post",
- }
-);
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue b/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
deleted file mode 100644
index cda3f82040..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/AIMessageView.vue
+++ /dev/null
@@ -1,42 +0,0 @@
-<template>
- <div
- class="border rounded-sm shadow-sm py-1 px-1 bg-gray-50 border-gray-400"
- :class="[
- message.status === 'DONE'
- ? 'w-full min-w-36'
- : message.status === 'FAILED'
- ? 'max-w-[40%] min-w-36'
- : 'w-auto',
- ]"
- >
- <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>
- <template v-else>
- <div class="text-warning flex items-center gap-x-1">
- <TriangleAlertIcon class="inline-block w-4 h-4 shrink-0" />
- <span class="text-sm">
- {{ message.error }}
- </span>
- </div>
- </template>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { TriangleAlertIcon } from "lucide-vue-next";
-import { BBSpin } from "@/bbkit";
-import type { Message } from "../../types";
-import Markdown from "./Markdown";
-
-defineProps<{
- message: Message;
-}>();
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/ChatView.vue b/frontend/src/plugins/ai/components/ChatView/ChatView.vue
deleted file mode 100644
index 70b05a5a1b..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/ChatView.vue
+++ /dev/null
@@ -1,92 +0,0 @@
-<template>
- <div ref="scrollerRef" class="flex-1 overflow-y-auto">
- <template v-if="conversation">
- <template v-if="conversation.messageList.length === 0">
- <EmptyView v-if="mode === 'VIEW'" />
- </template>
- <div
- v-else
- ref="containerRef"
- class="flex flex-col justify-end px-2 gap-y-4"
- >
- <div
- v-for="message in conversation?.messageList"
- :key="message.id"
- class="flex message"
- :class="[message.author === 'AI' ? 'justify-start' : 'justify-end']"
- >
- <UserMessageView
- v-if="message.author === 'USER'"
- :message="message"
- />
- <AIMessageView v-if="message.author === 'AI'" :message="message" />
- </div>
- </div>
- </template>
- <template v-else-if="mode === 'CHAT'">
- <div class="w-full h-full flex flex-col justify-end items-center pb-8">
- <i18n-t
- keypath="plugin.ai.conversation.select-or-create"
- tag="p"
- class="textinfolabel"
- >
- <template #create>
- <button
- class="normal-link"
- @click="events.emit('new-conversation', { input: '' })"
- >
- {{ $t("common.create") }}
- </button>
- </template>
- </i18n-t>
- </div>
- </template>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { ref, toRef, watch } from "vue";
-import { useAIContext } from "../../logic";
-import type { Conversation } from "../../types";
-import AIMessageView from "./AIMessageView.vue";
-import { provideChatViewContext } from "./context";
-import EmptyView from "./EmptyView.vue";
-import type { Mode } from "./types";
-import UserMessageView from "./UserMessageView.vue";
-
-const props = withDefaults(
- defineProps<{
- mode?: Mode;
- conversation?: Conversation;
- }>(),
- {
- mode: "CHAT",
- conversation: undefined,
- }
-);
-
-defineEmits<{
- (event: "enter", value: string): void;
-}>();
-
-const scrollerRef = ref<HTMLDivElement>();
-const containerRef = ref<HTMLDivElement>();
-
-const { events } = useAIContext();
-
-const { height: containerHeight } = useElementSize(containerRef);
-
-const scrollToLast = () => {
- const scroller = scrollerRef.value;
- const container = containerRef.value;
- if (!scroller) return;
- if (!container) return;
- scroller.scrollTo(0, container.scrollHeight);
-};
-watch(containerHeight, scrollToLast, { immediate: true });
-
-provideChatViewContext({
- mode: toRef(props, "mode"),
-});
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/EmptyView.vue b/frontend/src/plugins/ai/components/ChatView/EmptyView.vue
deleted file mode 100644
index 9ab24bd364..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/EmptyView.vue
+++ /dev/null
@@ -1,16 +0,0 @@
-<template>
- <div class="w-full h-full flex flex-col justify-center items-center">
- <div class="w-[20rem] mx-auto">
- <p>
- <NEmpty class="py-6" />
- </p>
- <p class="text-center textinfolabel">
- {{ $t("plugin.ai.conversation.no-message") }}
- </p>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { NEmpty } from "naive-ui";
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/AstToVNode.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/AstToVNode.vue
deleted file mode 100644
index 02f228fa11..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/AstToVNode.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <AstToMarkdown />
-</template>
-
-<script setup lang="ts">
-import type { Root } from "mdast";
-import { type CustomRender, mdastToVNode, type State } from "./utils";
-
-const props = defineProps<{
- ast: Root;
-}>();
-
-const slots = defineSlots<CustomRender>();
-
-function AstToMarkdown() {
- const state: State = {
- slots,
- definitionById: new Map(),
- };
- const result = mdastToVNode[props.ast.type](props.ast, state);
-
- return result;
-}
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
deleted file mode 100644
index 73a5fb7ff1..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
+++ /dev/null
@@ -1,129 +0,0 @@
-<template>
- <div
- ref="containerRef"
- class="flex flex-col overflow-x-hidden border border-gray-500 rounded-sm bg-white"
- :data-message-wrapper-width="messageWrapperWidth"
- :style="`width: ${combinedWidth}px`"
- >
- <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>
- <CopyButton :content="code" />
- </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="{
- 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>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { PlayIcon } from "lucide-vue-next";
-import { NPopover } from "naive-ui";
-import { computed, ref } from "vue";
-import { MonacoEditor } from "@/components/MonacoEditor";
-import { CopyButton } from "@/components/v2";
-import { useAIContext } from "@/plugins/ai/logic";
-import { findAncestor } from "@/utils";
-import { sqlEditorEvents } from "@/views/sql-editor/events";
-import InsertAtCaretIcon from "./InsertAtCaretIcon.vue";
-
-export type CodeBlockProps = {
- width: number;
-};
-
-const props = defineProps<
- CodeBlockProps & {
- code: string;
- }
->();
-
-const { events, showHistoryDialog } = useAIContext();
-// `sqlEditorEvents` is a module-level singleton — the AI plugin runs
-// inside its own Vue app (via the React→Vue bridge), so a Vue inject
-// of `useSQLEditorContext` wouldn't reach the host's provide chain.
-const editorEvents = sqlEditorEvents;
-const containerRef = ref<HTMLElement>();
-const messageWrapperRef = computed(() =>
- findAncestor(containerRef.value, ".message")
-);
-const { width: messageWrapperWidth } = useElementSize(messageWrapperRef);
-const combinedWidth = computed(() => {
- const PADDING = 8;
- const min = 8 * 16; /* 8rem */
- const auto = messageWrapperWidth.value * props.width - PADDING * 2;
- return Math.max(min, auto);
-});
-
-const handleExecute = () => {
- events.emit("run-statement", {
- statement: props.code,
- });
- showHistoryDialog.value = false;
-};
-
-const handleInsertAtCaret = () => {
- const { code } = props;
- editorEvents.emit("insert-at-caret", {
- content: code,
- });
- showHistoryDialog.value = false;
-};
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue
deleted file mode 100644
index 8e3d6ced9c..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue
+++ /dev/null
@@ -1,28 +0,0 @@
-<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
deleted file mode 100644
index f18df482b2..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/Markdown.vue
+++ /dev/null
@@ -1,38 +0,0 @@
-<template>
- <AstToMarkdown :ast="mdast" class="text-sm">
- <template #code="parsedAst">
- <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"
- />
- </template>
- <template #image="parsedAst">
- <img :src="parsedAst.url" />
- </template>
- </AstToMarkdown>
-</template>
-
-<script lang="ts" setup>
-import remarkGfm from "remark-gfm";
-import remarkParse from "remark-parse";
-import { unified } from "unified";
-import { computed } from "vue";
-import HighlightCodeBlock from "@/components/HighlightCodeBlock.vue";
-import AstToMarkdown from "./AstToVNode.vue";
-import CodeBlock, { type CodeBlockProps } from "./CodeBlock.vue";
-
-const props = defineProps<{
- content: string;
- codeBlockProps: CodeBlockProps;
-}>();
-
-const processor = unified().use(remarkParse).use(remarkGfm);
-
-const mdast = computed(() => {
- const tree = processor.parse(props.content ?? "");
- return tree;
-});
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/index.ts b/frontend/src/plugins/ai/components/ChatView/Markdown/index.ts
deleted file mode 100644
index 9cf4ba582b..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import Markdown from "./Markdown.vue";
-
-export default Markdown;
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/utils.ts b/frontend/src/plugins/ai/components/ChatView/Markdown/utils.ts
deleted file mode 100644
index a31fa8258e..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/utils.ts
+++ /dev/null
@@ -1,599 +0,0 @@
-import type {
- AlignType,
- Definition,
- Root,
- RootContent,
- RootContentMap,
- Text,
-} from "mdast";
-import { normalizeUri } from "micromark-util-sanitize-uri";
-import { h, type VNode } from "vue";
-
-export type CustomRender = {
- blockquote(node: RootContentMap["blockquote"], state?: State): VNode | string;
- break(node: RootContentMap["break"], state?: State): VNode | string;
- code(node: RootContentMap["code"], state?: State): VNode | string;
- delete(node: RootContentMap["delete"], state?: State): VNode | string;
- emphasis(node: RootContentMap["emphasis"], state?: State): VNode | string;
- footnoteDefinition(
- node: RootContentMap["footnoteDefinition"],
- state?: State
- ): VNode | string;
- footnoteReference(
- node: RootContentMap["footnoteReference"],
- state?: State
- ): VNode | string;
- heading(node: RootContentMap["heading"], state?: State): VNode | string;
- html(node: RootContentMap["html"], state?: State): VNode | string;
- image(node: RootContentMap["image"], state?: State): VNode | string;
- definition(node: RootContentMap["definition"], state?: State): VNode | string;
- imageReference(
- node: RootContentMap["imageReference"],
- state?: State
- ): VNode | string;
- inlineCode(node: RootContentMap["inlineCode"], state?: State): VNode | string;
- link(node: RootContentMap["link"], state?: State): VNode | string;
- linkReference(
- node: RootContentMap["linkReference"],
- state?: State
- ): VNode | string;
- list(node: RootContentMap["list"], state?: State): VNode | string;
- listItem(node: RootContentMap["listItem"], state?: State): VNode | string;
- paragraph(node: RootContentMap["paragraph"], state?: State): VNode | string;
- strong(node: RootContentMap["strong"], state?: State): VNode | string;
- table(node: RootContentMap["table"], state?: State): VNode | string;
- text(node: RootContentMap["text"], state?: State): VNode | string;
- thematicBreak(
- node: RootContentMap["thematicBreak"],
- state?: State
- ): VNode | string;
-};
-
-export type State = {
- slots: CustomRender;
- definitionById: Map<string, Definition>;
-};
-
-type GenericNodeHandler = (node: RootContent, state?: State) => VNode | string;
-
-function defaultMdNodeToVNode(
- node: RootContent,
- state?: State
-): VNode | string {
- const { type } = node;
-
- const customSlot = state?.slots[type as keyof CustomRender] as
- | GenericNodeHandler
- | undefined;
-
- if (customSlot) {
- return customSlot(node, state);
- }
-
- const handler = (mdastToVNode[type as keyof typeof mdastToVNode] ??
- mdastToVNode.unknown) as GenericNodeHandler;
-
- return handler(node, state);
-}
-
-function rootToVNode(node: Root, state?: State): VNode | string {
- const properties = {
- class: ["markdown"],
- };
-
- return h(
- "div",
- properties,
- node.children.map((child) => defaultMdNodeToVNode(child, state))
- );
-}
-
-function blockquoteToVNode(
- node: RootContentMap["blockquote"],
- state?: State
-): VNode | string {
- return h(
- "blockquote",
- undefined,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function breakToVNode(): VNode | string {
- // 貌似这货还需要多一个\n的字符……?不过看起来好像没必要……
- // {type: 'text', value: '\n'}
- return h("br");
-}
-
-function codeToVNode(node: RootContentMap["code"]): VNode | string {
- const value = node.value ? node.value + "\n" : "";
- const properties: Record<string, string> = {};
-
- if (node.lang) {
- properties.className = `language-${node.lang}`;
- }
-
- const result = h("code", properties, [value]);
-
- return h("pre", undefined, [result]);
-}
-
-function deleteToVNode(
- node: RootContentMap["delete"],
- state?: State
-): VNode | string {
- return h(
- "del",
- undefined,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function emphasisToVNode(
- node: RootContentMap["emphasis"],
- state?: State
-): VNode | string {
- return h(
- "em",
- undefined,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function footnoteDefinitionToVNode(
- node: RootContentMap["footnoteDefinition"]
-): VNode | string {
- // footnoteDefinition的children只有一个child并且为text,这里强行转一下
- const text = node.children[0] as unknown as Text;
- return h("div", { class: "footnote-definition" }, [text.value]);
-
- // const clobberPrefix = "user-content-";
- // const id = String(node.identifier).toUpperCase();
- // const safeId = normalizeUri(id.toLowerCase());
- // const index = state?.footnoteOrder.indexOf(id) ?? 0;
- // let counter;
-
- // let reuseCounter = state?.footnoteCounts.get(id);
-
- // if (reuseCounter === undefined) {
- // reuseCounter = 0;
- // state?.footnoteOrder.push(id);
- // counter = state?.footnoteOrder.length;
- // } else {
- // counter = index + 1;
- // }
-
- // reuseCounter += 1;
- // state?.footnoteCounts.set(id, reuseCounter);
-
- // // footnoteDefinition的children只有一个child并且为text,这里强行转一下
- // const text = node.children[0] as unknown as Text;
-
- // return h("span", undefined, [
- // text.value,
- // h(
- // "a",
- // {
- // href: "#" + clobberPrefix + "fn-" + safeId,
- // id:
- // clobberPrefix +
- // "fnref-" +
- // safeId +
- // (reuseCounter > 1 ? "-" + reuseCounter : ""),
- // dataFootnoteRef: true,
- // ariaDescribedBy: ["footnote-label"],
- // },
- // [String(counter)]
- // ),
- // ]);
-}
-
-function footnoteReferenceToVNode(): VNode | string {
- return "";
-
- // const clobberPrefix = "user-content-";
- // const id = String(node.identifier).toUpperCase();
- // const safeId = normalizeUri(id.toLowerCase());
- // // TODO后面实验一下,现在LLM铁定进不到这个分支里
- // const index = state?.footnoteOrder.indexOf(id) ?? 0;
- // let counter;
- // let reuseCounter = state?.footnoteCounts.get(id);
- // if (reuseCounter === undefined) {
- // reuseCounter = 0;
- // state?.footnoteOrder.push(id);
- // counter = state?.footnoteOrder.length;
- // } else {
- // counter = index + 1;
- // }
- // reuseCounter += 1;
- // state?.footnoteCounts.set(id, reuseCounter);
- // return h("sup", undefined, [
- // h(
- // "a",
- // {
- // href: "#" + clobberPrefix + "fn-" + safeId,
- // id:
- // clobberPrefix +
- // "fnref-" +
- // safeId +
- // (reuseCounter > 1 ? "-" + reuseCounter : ""),
- // dataFootnoteRef: true,
- // ariaDescribedBy: ["footnote-label"],
- // },
- // [String(counter)]
- // ),
- // ]);
-}
-
-function headingToVNode(
- node: RootContentMap["heading"],
- state?: State
-): VNode | string {
- const tagName = `h${node.depth}`;
- return h(
- tagName,
- undefined,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function htmlToVNode(node: RootContentMap["html"]): VNode | string {
- return node.value;
-}
-
-type ImageProps = {
- src: string;
- alt?: string;
- title?: string;
-};
-
-function imageToVNode(node: RootContentMap["image"]): VNode | string {
- const properties: ImageProps = {
- src: normalizeUri(node.url),
- };
-
- if (node.alt !== null && node.alt !== undefined) {
- properties.alt = node.alt;
- }
-
- if (node.title !== null && node.title !== undefined) {
- properties.title = node.title;
- }
-
- return h("img", properties);
-}
-
-function definitionToVNode(
- node: RootContentMap["definition"],
- state?: State
-): VNode | string {
- const id = String(node.identifier).toUpperCase();
-
- state?.definitionById.set(id, {
- url: node.url,
- type: "definition",
- identifier: node.identifier,
- });
-
- return "";
-}
-
-function referenceToText(
- node: RootContentMap["imageReference"] | RootContentMap["linkReference"],
- state?: State
-) {
- if (node.type === "imageReference") {
- return `![${node.alt ?? ""}]`;
- }
-
- const children = node.children.map((node) =>
- defaultMdNodeToVNode(node, state)
- );
-
- const hasVnode = children.some((node) => typeof node !== "string");
-
- return hasVnode
- ? h("span", undefined, ["[", ...children, "]"])
- : `[${children.join("")}]`;
-}
-
-function imageReferenceToVNode(
- node: RootContentMap["imageReference"],
- state?: State
-): VNode | string {
- const id = String(node.identifier).toUpperCase();
- const definition = state?.definitionById.get(id);
-
- if (!definition) {
- return referenceToText(node, state);
- }
-
- const properties: ImageProps = {
- src: normalizeUri(definition.url || ""),
- };
- if (node.alt) {
- properties.alt = node.alt;
- }
-
- if (definition.title !== null && definition.title !== undefined) {
- properties.title = definition.title;
- }
-
- return h("img", properties);
-}
-
-function inlineCodeToVNode(node: RootContentMap["inlineCode"]): VNode | string {
- const value = node.value.replace(/\r?\n|\r/g, " ");
- return h("code", undefined, [value]);
-}
-
-type LinkProps = {
- href: string;
- target: string;
- rel: string;
- title?: string;
-};
-
-function linkToVNode(
- node: RootContentMap["link"],
- state?: State
-): VNode | string {
- const properties: LinkProps = {
- href: normalizeUri(node.url),
- target: "_blank",
- rel: "noreferrer nofollow noopener",
- };
-
- if (node.title !== null && node.title !== undefined) {
- properties.title = node.title;
- }
-
- return h(
- "a",
- properties,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function linkReferenceToVNode(
- node: RootContentMap["linkReference"],
- state?: State
-): VNode | string {
- const id = String(node.identifier).toUpperCase();
- const definition = state?.definitionById.get(id);
-
- if (!definition) {
- return referenceToText(node, state);
- }
-
- const properties: LinkProps = {
- href: normalizeUri(definition.url || ""),
- target: "_blank",
- rel: "noreferrer nofollow noopener",
- };
-
- if (definition.title !== null && definition.title !== undefined) {
- properties.title = definition.title;
- }
-
- return h(
- "a",
- properties,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-type ListProps = {
- start?: number;
-};
-
-function listToVNode(
- node: RootContentMap["list"],
- state?: State
-): VNode | string {
- const properties: ListProps = {};
-
- const children = node.children.map((node) =>
- defaultMdNodeToVNode(node, state)
- );
-
- if (node.ordered) {
- if (typeof node.start === "number" && node.start !== 1) {
- properties.start = node.start;
- } else {
- properties.start = 1;
- }
- }
-
- return h(
- node.ordered ? "ol" : "ul",
- {
- style: `list-style: ${node.ordered ? "auto" : "initial"}; margin-left: 1rem;`,
- ...properties,
- },
- children
- );
-}
-
-type ListItemProps = {
- className?: string;
-};
-
-function listItemToVNode(
- node: RootContentMap["listItem"],
- state?: State
-): VNode | string {
- const children = node.children.map((node) =>
- defaultMdNodeToVNode(node, state)
- );
-
- const properties: ListItemProps = {};
-
- if (typeof node.checked === "boolean") {
- const head = children[0];
-
- const checkedVNode = h("input", {
- type: "checkbox",
- checked: node.checked,
- disabled: true,
- });
-
- if (typeof head !== "string" && head?.type === "p") {
- head.children = [checkedVNode, ...((head.children as VNode[]) ?? [])];
- } else {
- children.unshift(h("p", undefined, [checkedVNode]));
- }
-
- // According to github-markdown-css, this class hides bullet.
- // See: <https://github.com/sindresorhus/github-markdown-css>.
- properties.className = "task-list-item";
- }
-
- return h("li", properties, children);
-}
-
-function paragraphToVNode(
- node: RootContentMap["paragraph"],
- state?: State
-): VNode | string {
- return h(
- // 避免出现p套p的情况,尤其是各种扩展组件(比如mermaid)之类的会出现
- "div",
- { class: "paragraph" },
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function strongToVNode(
- node: RootContentMap["strong"],
- state?: State
-): VNode | string {
- return h(
- "strong",
- undefined,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
-}
-
-function tableRowToVNode(
- node: RootContentMap["tableRow"],
- align: AlignType[],
- rowIndex: number,
- state?: State
-): VNode | string {
- const tagName = rowIndex === 0 ? "th" : "td";
-
- const children = node.children.map((node, index) => {
- const alignInfo = align[index];
- const properties = alignInfo
- ? {
- align: alignInfo,
- }
- : undefined;
-
- return h(
- tagName,
- properties,
- node.children.map((node) => defaultMdNodeToVNode(node, state))
- );
- });
-
- return h("tr", undefined, children);
-}
-
-function tableToVNode(
- node: RootContentMap["table"],
- state?: State
-): VNode | string {
- const tableHeadChildren: Array<VNode | string> = [];
- const tableContentChildren: Array<VNode | string> = [];
-
- const align = node.align ?? [];
-
- node.children.forEach((node, index) => {
- const vnode = tableRowToVNode(node, align, index, state);
-
- if (index === 0) {
- tableHeadChildren.push(vnode);
- } else {
- tableContentChildren.push(vnode);
- }
- });
-
- const children: Array<VNode | string> = [];
- if (tableHeadChildren.length > 0) {
- children.push(h("thead", undefined, tableHeadChildren));
- }
-
- if (tableContentChildren.length > 0) {
- children.push(h("tbody", undefined, tableContentChildren));
- }
-
- return h("table", undefined, children);
-}
-
-function textToVNode(node: RootContentMap["text"]): VNode | string {
- return node.value;
-}
-
-function thematicBreakToVNode(): VNode | string {
- return h("hr");
-}
-
-function defaultUnknownHandler(
- node: RootContent,
- state?: State
-): VNode | string {
- if ("children" in node) {
- const properties: Record<string, unknown> =
- "properties" in node ? (node.properties as Record<string, unknown>) : {};
-
- if ("className" in properties && Array.isArray(properties.className)) {
- properties.className = properties.className.join(" ");
- }
-
- return h(
- "div",
- properties,
- node.children.map((child) => defaultMdNodeToVNode(child, state))
- );
- }
-
- if ("value" in node) {
- return node.value;
- }
-
- return "";
-}
-
-export const mdastToVNode = {
- root: rootToVNode,
- blockquote: blockquoteToVNode,
- break: breakToVNode,
- code: codeToVNode,
- delete: deleteToVNode,
- emphasis: emphasisToVNode,
-
- footnoteDefinition: footnoteDefinitionToVNode,
- footnoteReference: footnoteReferenceToVNode,
-
- heading: headingToVNode,
- html: htmlToVNode,
- image: imageToVNode,
-
- // TODO同上
- definition: definitionToVNode,
- imageReference: imageReferenceToVNode,
-
- inlineCode: inlineCodeToVNode,
- link: linkToVNode,
- linkReference: linkReferenceToVNode,
- list: listToVNode,
- listItem: listItemToVNode,
- paragraph: paragraphToVNode,
- strong: strongToVNode,
- table: tableToVNode,
- text: textToVNode,
- thematicBreak: thematicBreakToVNode,
- unknown: defaultUnknownHandler,
-};
diff --git a/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue b/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue
deleted file mode 100644
index 32da5c59b4..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/UserMessageView.vue
+++ /dev/null
@@ -1,21 +0,0 @@
-<template>
- <div
- class="user-message max-w-[60%] min-w-36 border rounded-sm shadow-sm py-1 px-2 bg-indigo-100 border-indigo-400"
- >
- <Markdown
- :content="message.content"
- :code-block-props="{
- width: 0.6,
- }"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import type { Message } from "../../types";
-import Markdown from "./Markdown";
-
-defineProps<{
- message: Message;
-}>();
-</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/context.ts b/frontend/src/plugins/ai/components/ChatView/context.ts
deleted file mode 100644
index e6d38300ac..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/context.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { InjectionKey, Ref } from "vue";
-import { inject, provide } from "vue";
-import type { 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/index.ts b/frontend/src/plugins/ai/components/ChatView/index.ts
deleted file mode 100644
index dd4fe6f11e..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import ChatView from "./ChatView.vue";
-
-export default ChatView;
diff --git a/frontend/src/plugins/ai/components/ChatView/types.ts b/frontend/src/plugins/ai/components/ChatView/types.ts
deleted file mode 100644
index 315f7cb66a..0000000000
--- a/frontend/src/plugins/ai/components/ChatView/types.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type Mode = "CHAT" | "VIEW";
diff --git a/frontend/src/plugins/ai/components/DynamicSuggestions.vue b/frontend/src/plugins/ai/components/DynamicSuggestions.vue
deleted file mode 100644
index a4a27168e3..0000000000
--- a/frontend/src/plugins/ai/components/DynamicSuggestions.vue
+++ /dev/null
@@ -1,102 +0,0 @@
-<template>
- <div v-if="show" class="flex items-center overflow-hidden h-[22px]">
- <template v-if="dynamicSuggestions && !ready">
- <BBSpin :size="16" class="mr-2" />
- <span class="text-sm">
- {{ $t("plugin.ai.conversation.tips.suggest-prompt") }}
- </span>
- </template>
-
- <div
- v-if="ready && showSuggestion"
- 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="w-full truncate leading-[22px]">
- {{ current }}
- </div>
- </NButton>
-
- <BBSpin v-if="state === 'LOADING'" :size="16" class="shrink-0" />
- <div v-if="state === 'IDLE'" class="flex items-center">
- <NButton
- size="tiny"
- type="primary"
- quaternary
- class="shrink-0"
- @click="dynamicSuggestions?.consume()"
- >
- <RefreshCwIcon class="w-3.5 h-3.5" />
- </NButton>
- <NButton
- size="tiny"
- type="primary"
- quaternary
- class="shrink-0"
- @click="() => (showSuggestion = false)"
- >
- <XIcon class="w-3.5 h-3.5" />
- </NButton>
- </div>
- <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 { RefreshCwIcon, XIcon } from "lucide-vue-next";
-import { NButton } from "naive-ui";
-import { computed, onMounted } from "vue";
-import { BBSpin } from "@/bbkit";
-import { useCurrentUserV1 } from "@/store";
-import {
- storageKeySqlEditorAiSuggestion,
- useDynamicLocalStorage,
-} from "@/utils";
-import { useDynamicSuggestions } from "../logic";
-
-const emit = defineEmits<{
- (event: "enter", query: string): void;
-}>();
-
-const dynamicSuggestions = useDynamicSuggestions();
-const currentUser = useCurrentUserV1();
-
-onMounted(() => {
- const suggestion = dynamicSuggestions.value;
- if (suggestion && suggestion.suggestions.length === 0) {
- suggestion.fetch();
- }
-});
-
-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 showSuggestion = useDynamicLocalStorage<boolean>(
- computed(() => storageKeySqlEditorAiSuggestion(currentUser.value.email)),
- true
-);
-
-const show = computed(() => {
- if (!ready.value) return true; // show a spinner
- return suggestions.value.length > 0 || state.value === "LOADING";
-});
-
-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/ConversationList.vue b/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
deleted file mode 100644
index 155c83f94f..0000000000
--- a/frontend/src/plugins/ai/components/HistoryPanel/ConversationList.vue
+++ /dev/null
@@ -1,129 +0,0 @@
-<template>
- <div class="h-full overflow-hidden flex flex-col">
- <div class="flex-1 overflow-y-auto p-1 flex flex-col gap-y-2">
- <template v-if="ready">
- <div
- 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="[
- selected?.id === conversation.id &&
- 'bg-indigo-100 border-indigo-400',
- ]"
- @click="selected = conversation"
- >
- <div
- v-if="conversation.name"
- class="text-sm flex-1 whitespace-pre-wrap wrap-break-word break-all"
- >
- {{ conversation.name }}
- </div>
- <div v-else class="text-sm flex-1 truncate text-gray-500 italic">
- {{
- head(conversation.messageList)?.content ||
- $t("plugin.ai.conversation.untitled")
- }}
- </div>
- <div class="flex items-center gap-x-px">
- <button
- class="flex items-center p-0.5 border border-transparent rounded-sm text-gray-500 hover:text-accent hover:bg-indigo-50 hover:border-accent cursor-pointer"
- @click.stop="state.rename = conversation"
- >
- <PencilIcon class="w-3 h-3" />
- </button>
- <NPopconfirm
- @positive-click="handleDeleteConversation(conversation)"
- >
- <template #trigger>
- <button
- class="flex items-center p-0.5 border border-transparent rounded-sm text-gray-500 hover:text-accent hover:bg-indigo-50 hover:border-accent cursor-pointer"
- @click.stop=""
- >
- <TrashIcon class="w-3 h-3" />
- </button>
- </template>
- <span>{{ $t("plugin.ai.conversation.delete") }}</span>
- </NPopconfirm>
- </div>
- </div>
-
- <div
- class="sticky bottom-0 btn-normal items-center justify-center gap-x-1"
- @click="events.emit('new-conversation', { input: '' })"
- >
- <PlusIcon class="w-4 h-4" />
- <span class="pr-2">
- {{ $t("plugin.ai.conversation.new-conversation") }}
- </span>
- </div>
- </template>
- <template v-else>
- <BBSpin class="self-center mt-8" />
- </template>
- </div>
-
- <ConversationRenameDialog
- v-if="state.rename"
- :conversation="state.rename"
- @cancel="state.rename = undefined"
- @updated="state.rename = undefined"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { head } from "lodash-es";
-import { PencilIcon, PlusIcon, TrashIcon } from "lucide-vue-next";
-import { NPopconfirm } from "naive-ui";
-import scrollIntoView from "scroll-into-view-if-needed";
-import { reactive, watch } from "vue";
-import { BBSpin } from "@/bbkit";
-import { useCurrentSQLEditorTab } from "@/store";
-import { useAIContext, useCurrentChat } from "../../logic";
-import { useConversationStore } from "../../store";
-import type { Conversation } from "../../types";
-import ConversationRenameDialog from "./ConversationRenameDialog.vue";
-
-type LocalState = {
- rename: Conversation | undefined;
-};
-
-const tab = useCurrentSQLEditorTab();
-const store = useConversationStore();
-const { events } = useAIContext();
-const { list, ready, selected } = useCurrentChat();
-
-const state = reactive<LocalState>({
- rename: undefined,
-});
-
-watch(
- [() => tab.value?.connection.instance, () => tab.value?.connection.database],
- () => {
- state.rename = undefined;
- },
- { immediate: true }
-);
-
-const handleDeleteConversation = async (conversation: Conversation) => {
- // 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);
- selected.value = list.value[index];
-};
-
-watch(
- [() => selected.value?.id, list],
- ([id, list]) => {
- if (!id) return;
- if (list.length === 0) return;
- requestAnimationFrame(() => {
- const elem = document.querySelector(`[data-conversation-id="${id}"]`);
- if (!elem) return;
- scrollIntoView(elem, { scrollMode: "if-needed" });
- });
- },
- { immediate: true }
-);
-</script>
diff --git a/frontend/src/plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue b/frontend/src/plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue
deleted file mode 100644
index 141fe360c5..0000000000
--- a/frontend/src/plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue
+++ /dev/null
@@ -1,88 +0,0 @@
-<template>
- <BBModal
- :title="$t('plugin.ai.conversation.rename')"
- @close="$emit('cancel')"
- >
- <div class="w-[18rem] flex flex-col items-start gap-y-2">
- <div class="textlabel">{{ $t("common.name") }}</div>
- <div class="w-full">
- <NInput
- v-model:value="state.name"
- class="bb-ai-conversation-rename-input w-full"
- @keypress.enter="handleRename"
- />
- </div>
- <div
- class="w-full flex items-center justify-end gap-x-2 mt-4 pt-2 border-t"
- >
- <NButton @click="$emit('cancel')">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton type="primary" @click="handleRename">
- {{ $t("common.update") }}
- </NButton>
- </div>
- <div
- v-if="state.loading"
- class="absolute inset-0 bg-white/50 flex flex-col items-center justify-center rounded-lg"
- >
- <BBSpin />
- </div>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { head } from "lodash-es";
-import { NButton, NInput } from "naive-ui";
-import { onMounted, reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import { BBModal, BBSpin } from "@/bbkit";
-import { useConversationStore } from "../../store";
-import type { Conversation } from "../../types";
-
-type LocalState = {
- name: string;
- loading: boolean;
-};
-
-const props = defineProps<{
- conversation: Conversation;
-}>();
-
-const emit = defineEmits<{
- (event: "cancel"): void;
- (event: "updated"): void;
-}>();
-
-const { t } = useI18n();
-
-const state = reactive<LocalState>({
- name:
- props.conversation.name ||
- head(props.conversation.messageList)?.content ||
- t("plugin.ai.conversation.untitled"),
- loading: false,
-});
-const store = useConversationStore();
-
-const handleRename = async () => {
- const { conversation } = props;
- const { name } = state;
- conversation.name = name;
- state.loading = true;
- 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
deleted file mode 100644
index e58f05da04..0000000000
--- a/frontend/src/plugins/ai/components/HistoryPanel/HistoryPanel.vue
+++ /dev/null
@@ -1,29 +0,0 @@
-<template>
- <Drawer v-model:show="showHistoryDialog">
- <DrawerContent
- :title="$t('plugin.ai.conversation.history-conversations')"
- class="w-[calc(100vw-8rem)] max-w-6xl"
- body-content-style="padding: 0"
- >
- <div class="flex h-full">
- <aside class="hidden lg:flex lg:flex-col w-[14em] border-l border-b">
- <ConversationList />
- </aside>
-
- <div class="flex-1 flex flex-col py-2 bg-gray-100 overflow-hidden">
- <ChatView mode="VIEW" :conversation="selected" />
- </div>
- </div>
- </DrawerContent>
- </Drawer>
-</template>
-
-<script lang="ts" setup>
-import { Drawer, DrawerContent } from "@/components/v2";
-import { useAIContext, useCurrentChat } from "../../logic";
-import ChatView from "../ChatView";
-import ConversationList from "./ConversationList.vue";
-
-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
deleted file mode 100644
index 20aae55311..0000000000
--- a/frontend/src/plugins/ai/components/HistoryPanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-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
deleted file mode 100644
index 5c50181361..0000000000
--- a/frontend/src/plugins/ai/components/PromptInput.vue
+++ /dev/null
@@ -1,116 +0,0 @@
-<template>
- <NInput
- ref="inputRef"
- v-model:value="state.value"
- :disabled="disabled"
- :placeholder="$t('plugin.ai.text-to-sql-placeholder')"
- :autosize="{
- minRows: 1,
- maxRows: 10,
- }"
- :input-props="{
- style: 'box-shadow: none !important',
- }"
- size="small"
- type="textarea"
- style="--n-padding-left: 6px; --n-padding-right: 0px"
- @keypress.enter="handlePressEnter"
- >
- <template #suffix>
- <NPopover placement="bottom" style="--n-padding: 6px 8px">
- <template #trigger>
- <NButton
- :quaternary="true"
- :disabled="!state.value"
- type="primary"
- size="small"
- style="--n-padding: 0 6px"
- @click="handlePressEnter()"
- >
- ⏎
- </NButton>
- </template>
- <template #default>
- <div class="text-xs flex flex-col gap-1">
- <p class="flex items-center gap-1">
- <span>{{ $t("plugin.ai.send") }}</span>
- <span>({{ keyboardShortcutStr("⏎") }})</span>
- </p>
- <p class="flex items-center gap-1">
- <span>{{ $t("plugin.ai.new-line") }}</span>
- <span>({{ keyboardShortcutStr("shift+⏎") }})</span>
- </p>
- </div>
- </template>
- </NPopover>
- </template>
- </NInput>
-</template>
-
-<script lang="ts" setup>
-import { type InputInst, NButton, NInput, NPopover } from "naive-ui";
-import { onMounted, reactive, ref, watch } from "vue";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { keyboardShortcutStr, nextAnimationFrame } from "@/utils";
-import { useAIContext } from "../logic";
-
-type LocalState = {
- value: string;
-};
-
-withDefaults(
- defineProps<{
- disabled?: boolean;
- }>(),
- {
- disabled: false,
- }
-);
-
-const emit = defineEmits<{
- (event: "enter", value: string): void;
-}>();
-
-const state = reactive<LocalState>({
- value: "",
-});
-
-const { pendingPreInput, events } = useAIContext();
-const inputRef = ref<InputInst>();
-
-const applyValue = (value: string) => {
- state.value = "";
- emit("enter", value);
-};
-
-const handlePressEnter = (e?: KeyboardEvent) => {
- if (e?.shiftKey) {
- return;
- }
- e?.preventDefault();
- if (!state.value.trim()) return;
- applyValue(state.value);
-};
-
-onMounted(() => {
- inputRef.value?.focus();
-});
-
-watch(
- pendingPreInput,
- async () => {
- await nextAnimationFrame();
- if (!pendingPreInput.value) return;
- state.value = pendingPreInput.value;
- pendingPreInput.value = undefined;
- },
- {
- immediate: true,
- flush: "post",
- }
-);
-
-useEmitteryEventListener(events, "new-conversation", () => {
- inputRef.value?.focus();
-});
-</script>
diff --git a/frontend/src/plugins/ai/components/ProvideAIContext.vue b/frontend/src/plugins/ai/components/ProvideAIContext.vue
deleted file mode 100644
index b95bc2dab8..0000000000
--- a/frontend/src/plugins/ai/components/ProvideAIContext.vue
+++ /dev/null
@@ -1,124 +0,0 @@
-<template>
- <slot />
-</template>
-
-<script lang="ts" setup>
-import { create } from "@bufbuild/protobuf";
-import { storeToRefs } from "pinia";
-import { computed, onMounted, reactive, ref, toRef } from "vue";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useMetadata,
- useSettingV1Store,
- useSQLEditorTabStore,
-} from "@/store";
-import {
- AISettingSchema,
- Setting_SettingName,
-} from "@/types/proto-es/v1/setting_service_pb";
-import { wrapRefAsPromise } from "@/utils";
-import {
- aiContextEvents,
- provideAIContext,
- useChatByTab,
- useCurrentChat,
-} from "../logic";
-import { useConversationStore } from "../store";
-import type { AIContext, AIContextEvents } from "../types";
-
-type LocalState = {
- showHistoryDialog: boolean;
-};
-
-const state = reactive<LocalState>({
- showHistoryDialog: false,
-});
-
-const settingV1Store = useSettingV1Store();
-
-onMounted(async () => {
- await settingV1Store.getOrFetchSettingByName(Setting_SettingName.AI, true);
-});
-
-const aiSetting = computed(() => {
- const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);
- if (setting?.value?.value?.case === "ai") {
- return setting.value.value.value;
- }
- return create(AISettingSchema, {});
-});
-const { instance, database } = useConnectionOfCurrentSQLEditorTab();
-
-const databaseMetadata = useMetadata(
- computed(() => database.value.name),
- false /* !skipCache */
-);
-
-// Reuse the module-level singleton so React consumers (e.g. OpenAIButton.tsx)
-// share this event bus without needing Vue's provide/inject.
-const events: AIContextEvents = aiContextEvents;
-const chat = useChatByTab();
-const showHistoryDialog = toRef(state, "showHistoryDialog");
-const pendingSendChat = ref<{ content: string }>();
-const pendingPreInput = ref<string>();
-
-const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());
-const schema = computed(() => tab.value?.connection.schema);
-const store = useConversationStore();
-
-const context: AIContext = {
- aiSetting: aiSetting,
- engine: computed(() => instance.value.engine),
- databaseMetadata,
- schema,
- showHistoryDialog,
- chat,
- pendingSendChat,
- pendingPreInput,
- events,
-};
-provideAIContext(context);
-
-const { ready, selected: selectedConversation } = useCurrentChat(context);
-
-useEmitteryEventListener(events, "new-conversation", async ({ input }) => {
- if (!tab.value) return;
- await wrapRefAsPromise(ready, /* expected */ true);
- showHistoryDialog.value = false;
-
- if (
- !selectedConversation.value ||
- selectedConversation.value.messageList.length !== 0
- ) {
- // reuse if current chat is empty
- // create new chat otherwise
- const c = await store.createConversation({
- name: "",
- ...tab.value.connection,
- });
- selectedConversation.value = c;
- }
- if (input) {
- requestAnimationFrame(() => {
- pendingPreInput.value = input;
- });
- }
-});
-
-useEmitteryEventListener(events, "send-chat", async ({ content, newChat }) => {
- if (!tab.value) return;
- await wrapRefAsPromise(ready, /* expected */ true);
- if (newChat) {
- showHistoryDialog.value = false;
- const c = await store.createConversation({
- name: "",
- ...tab.value.connection,
- });
- selectedConversation.value = c;
- }
- requestAnimationFrame(() => {
- pendingSendChat.value = { content };
- });
-});
-</script>
diff --git a/frontend/src/plugins/ai/components/editor-actions.ts b/frontend/src/plugins/ai/components/editor-actions.ts
deleted file mode 100644
index 9648a9ceee..0000000000
--- a/frontend/src/plugins/ai/components/editor-actions.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import * as monaco from "monaco-editor";
-import type { MaybeRef } from "vue";
-import { computed, shallowRef, unref, watchEffect } from "vue";
-import type { MonacoModule } from "@/components/MonacoEditor";
-import {
- useSelectedContent,
- useSelection,
-} from "@/components/MonacoEditor/composables";
-import { useTextModelLanguage } from "@/components/MonacoEditor/composables/common";
-import { useEditorContextKey } from "@/components/MonacoEditor/utils";
-import type { AIContext, ChatAction } from "../types";
-
-type AIActionsOptions = {
- actions: ChatAction[];
- callback: (
- action: ChatAction,
- monaco: MonacoModule,
- editor: monaco.editor.IStandaloneCodeEditor
- ) => void;
-};
-
-export const useAIActions = async (
- monaco: MonacoModule,
- editor: monaco.editor.IStandaloneCodeEditor,
- context: AIContext,
- options: MaybeRef<AIActionsOptions>
-) => {
- const language = useTextModelLanguage(editor);
- const actions = shallowRef<monaco.IDisposable[]>([]);
-
- const checkContentEmpty = () => {
- const content = editor.getModel()?.getValue() ?? "";
- return content.length === 0;
- };
- const contentEmpty = useEditorContextKey(
- editor,
- "bb.ai.contentEmpty",
- checkContentEmpty()
- );
- editor.onDidChangeModelContent(() => {
- contentEmpty.set(checkContentEmpty());
- });
-
- const selection = useSelection(editor);
- const selectedContent = useSelectedContent(editor, selection);
- useEditorContextKey(
- editor,
- "bb.ai.selectedContentEmpty",
- computed(() => selectedContent.value.length === 0)
- );
-
- watchEffect(() => {
- const opts = unref(options);
- actions.value.forEach((action) => {
- action.dispose();
- });
- actions.value = [];
-
- if (!context.aiSetting.value.enabled) {
- return;
- }
-
- if (language.value === "sql") {
- if (opts.actions.includes("explain-code")) {
- const action = editor.addAction({
- id: "explain-code",
- label: "Explain code",
- precondition: "!bb.ai.contentEmpty",
- contextMenuGroupId: "2_ai_assistant",
- contextMenuOrder: 1,
- run: async () => {
- opts.callback("explain-code", monaco, editor);
- },
- });
- actions.value.push(action);
- }
- if (opts.actions.includes("find-problems")) {
- const action = editor.addAction({
- id: "find-problems",
- label: "Find problems",
- precondition: "!bb.ai.contentEmpty",
- contextMenuGroupId: "2_ai_assistant",
- contextMenuOrder: 2,
- run: async () => {
- opts.callback("find-problems", monaco, editor);
- },
- });
- actions.value.push(action);
- }
- if (opts.actions.includes("new-chat")) {
- const action = editor.addAction({
- id: "new-chat-using-selection",
- label: "New chat using selection",
- precondition: "!bb.ai.selectedContentEmpty",
- contextMenuGroupId: "2_ai_assistant",
- contextMenuOrder: 2,
- run: async () => {
- opts.callback("new-chat", monaco, editor);
- },
- });
- actions.value.push(action);
- }
- } else {
- // When the language is "javascript" we do not have AI Assistant actions
- }
- });
-};
diff --git a/frontend/src/plugins/ai/components/state.ts b/frontend/src/plugins/ai/components/state.ts
deleted file mode 100644
index 5777e0e2fc..0000000000
--- a/frontend/src/plugins/ai/components/state.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { useLocalStorage } from "@vueuse/core";
-import { STORAGE_KEY_AI_DISMISS } from "@/utils";
-
-export const DISMISS_PLACEHOLDER = useLocalStorage(
- STORAGE_KEY_AI_DISMISS,
- false
-);
diff --git a/frontend/src/plugins/ai/index.ts b/frontend/src/plugins/ai/index.ts
index 0b633790d3..49c88fce73 100644
--- a/frontend/src/plugins/ai/index.ts
+++ b/frontend/src/plugins/ai/index.ts
@@ -1,7 +1,5 @@
-import AIChatToSQL from "./components/AIChatToSQL.vue";
-import AIChatToSQLBridgeHost from "./components/AIChatToSQLBridgeHost.vue";
-import ProvideAIContext from "./components/ProvideAIContext.vue";
-
+// Plugin-wide barrel. Only re-exports framework-agnostic surfaces here
+// so the Vue tsconfig (which still picks up this file) doesn't have to
+// pull in React `.tsx` modules through imports. React callers reach the
+// component entry points via `@/plugins/ai/react` directly.
export * from "./types";
-export * from "./components/editor-actions";
-export { AIChatToSQL, AIChatToSQLBridgeHost, ProvideAIContext };
diff --git a/frontend/src/plugins/ai/logic/context.ts b/frontend/src/plugins/ai/logic/context.ts
deleted file mode 100644
index 5327cdb108..0000000000
--- a/frontend/src/plugins/ai/logic/context.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { type InjectionKey, inject, provide } from "vue";
-import type { AIContext } from "../types";
-
-export const KEY = Symbol("bb.plugin.ai") as InjectionKey<AIContext>;
-
-export const useAIContext = () => {
- return inject(KEY)!;
-};
-
-export const provideAIContext = (context: AIContext) => {
- provide(KEY, context);
-};
diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.ts
index 4c72723616..48832c8775 100644
--- a/frontend/src/plugins/ai/logic/index.ts
+++ b/frontend/src/plugins/ai/logic/index.ts
@@ -1,6 +1,4 @@
-export * from "./context";
export * from "./events";
export * from "./useChatByTab";
export * from "./useDynamicSuggestions";
-export * from "./utils";
export * from "./prompt";
diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.ts
index 0c899af298..f98030bee6 100644
--- a/frontend/src/plugins/ai/logic/useChatByTab.ts
+++ b/frontend/src/plugins/ai/logic/useChatByTab.ts
@@ -4,7 +4,6 @@ import { useSQLEditorTabStore } from "@/store";
import type { SQLEditorTab } from "@/types";
import { useConversationStore } from "../store";
import type { AIChatInfo, Conversation } from "../types";
-import { useAIContext } from "./context";
const chatsByTab = new Map<string, AIChatInfo>();
@@ -61,18 +60,3 @@ export const useChatByTab = () => {
return getChatByTab(tab);
});
};
-
-export const useCurrentChat = (context = useAIContext()) => {
- const { chat } = context;
- 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/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
index b537ad64b4..675d760370 100644
--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
@@ -1,17 +1,18 @@
import { create as createProto } from "@bufbuild/protobuf";
import { createContextValues } from "@connectrpc/connect";
import { head, uniq, values } from "lodash-es";
-import { computed, reactive, ref } from "vue";
+import { computed, type MaybeRefOrGetter, reactive, ref, toValue } from "vue";
import { hashCode } from "@/bbkit/BBUtil";
import { sqlServiceClientConnect } from "@/connect";
import { silentContextKey } from "@/connect/context-key";
+import type { Engine } from "@/types/proto-es/v1/common_pb";
+import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
import {
type AICompletionRequest_Message,
AICompletionRequest_MessageSchema,
AICompletionRequestSchema,
} from "@/types/proto-es/v1/sql_service_pb";
import { storageKeyAiSuggestions } from "@/utils";
-import { useAIContext } from "./context";
import * as promptUtils from "./prompt";
export type SuggestionContext = {
@@ -49,13 +50,25 @@ const MAX_STORED_SUGGESTIONS = 10;
const keyOf = (metadata: string) => String(hashCode(metadata));
-export const useDynamicSuggestions = () => {
- const context = useAIContext();
+/**
+ * Per-(database, engine, schema) cache of LLM-suggested prompt chips.
+ *
+ * Originally took its inputs via Vue's `useAIContext()` provide/inject.
+ * After Stage 22 the AI plugin's components are React, and the React
+ * provider doesn't set up a Vue inject chain — so callers pass
+ * `databaseMetadata` / `engine` / `schema` directly (or via Vue refs /
+ * getters, which makes this helper still usable from Vue surfaces that
+ * outlive this migration).
+ */
+export const useDynamicSuggestions = (params: {
+ databaseMetadata: MaybeRefOrGetter<DatabaseMetadata | undefined>;
+ engine: MaybeRefOrGetter<Engine | undefined>;
+ schema: MaybeRefOrGetter<string | undefined>;
+}) => {
const metadata = computed(() => {
- const meta = context.databaseMetadata.value;
- const engine = context.engine.value;
- const schema = context.schema.value;
-
+ const meta = toValue(params.databaseMetadata);
+ const engine = toValue(params.engine);
+ const schema = toValue(params.schema);
if (meta && engine) {
return promptUtils.databaseMetadataToText(meta, engine, schema);
}
diff --git a/frontend/src/plugins/ai/logic/utils.ts b/frontend/src/plugins/ai/logic/utils.ts
deleted file mode 100644
index d479f35c87..0000000000
--- a/frontend/src/plugins/ai/logic/utils.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { watch } from "vue";
-import { useCurrentSQLEditorTab } from "@/store";
-import type { SQLEditorConnection } from "@/types";
-
-export const onConnectionChanged = (
- fn: (
- newConn: SQLEditorConnection,
- oldConn: SQLEditorConnection | undefined
- ) => void,
- immediate = false
-) => {
- const tab = useCurrentSQLEditorTab();
- return watch(
- [
- () => tab.value?.connection.instance,
- () => tab.value?.connection.database,
- ],
- (newValues, oldValues) => {
- fn(
- { instance: newValues[0] ?? "", database: newValues[1] ?? "" },
- oldValues[0] && oldValues[1]
- ? { instance: oldValues[0] ?? "", database: oldValues[1] ?? "" }
- : undefined
- );
- },
- { immediate }
- );
-};
diff --git a/frontend/src/plugins/ai/react/AIChatToSQL.tsx b/frontend/src/plugins/ai/react/AIChatToSQL.tsx
new file mode 100644
index 0000000000..9cab8462dd
--- /dev/null
+++ b/frontend/src/plugins/ai/react/AIChatToSQL.tsx
@@ -0,0 +1,28 @@
+import { lazy, Suspense } from "react";
+import { useAIContext } from "./context";
+
+// `ChatPanel` pulls in the markdown parser (`unified`, `remark-parse`,
+// `remark-gfm`) and the React `MonacoEditor` — both heavy enough that
+// gating them behind `lazy()` keeps the initial SQL Editor bundle slim
+// when the AI side pane is collapsed. Matches the Vue version's
+// `await import("./ChatPanel.vue")` deferred-import pattern.
+const ChatPanel = lazy(() =>
+ import("./ChatPanel").then((m) => ({ default: m.ChatPanel }))
+);
+
+/**
+ * React port of `plugins/ai/components/AIChatToSQL.vue`.
+ *
+ * Top-level entry point for the AI chat side pane. Must be rendered
+ * inside `<AIContextProvider>`. Returns `null` when the workspace's AI
+ * setting is disabled (the host shows nothing).
+ */
+export function AIChatToSQL() {
+ const { aiSetting } = useAIContext();
+ if (!aiSetting.enabled) return null;
+ return (
+ <Suspense fallback={null}>
+ <ChatPanel />
+ </Suspense>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ActionBar.tsx b/frontend/src/plugins/ai/react/ActionBar.tsx
new file mode 100644
index 0000000000..7a5e2e2ce8
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ActionBar.tsx
@@ -0,0 +1,53 @@
+import { ClockIcon, PlusIcon } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useAIContext } from "./context";
+
+/**
+ * React port of `plugins/ai/components/ActionBar.vue`.
+ * Top bar above the chat: "AI Assistant" heading on the left,
+ * History + New-conversation buttons on the right.
+ */
+export function ActionBar() {
+ const { t } = useTranslation();
+ const { events, setShowHistoryDialog } = useAIContext();
+
+ return (
+ <div className="w-full flex flex-wrap gap-y-1 justify-between sm:items-center px-1 py-1 border-b bg-background">
+ <div className="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center pl-1">
+ <h3 className="text-sm font-medium">{t("plugin.ai.ai-assistant")}</h3>
+ </div>
+ <div className="action-right gap-x-1 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center">
+ <Tooltip
+ content={t("plugin.ai.conversation.view-history-conversations")}
+ side="bottom"
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-1.5"
+ onClick={() => setShowHistoryDialog(true)}
+ aria-label={t("plugin.ai.conversation.view-history-conversations")}
+ >
+ <ClockIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip
+ content={t("plugin.ai.conversation.new-conversation")}
+ side="bottom"
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-1.5"
+ onClick={() => events.emit("new-conversation", { input: "" })}
+ aria-label={t("plugin.ai.conversation.new-conversation")}
+ >
+ <PlusIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatPanel.tsx b/frontend/src/plugins/ai/react/ChatPanel.tsx
new file mode 100644
index 0000000000..7f4a18c4bf
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatPanel.tsx
@@ -0,0 +1,241 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { head } from "lodash-es";
+import { Loader2 } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { sqlServiceClientConnect } from "@/connect";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useSQLEditorTabStore } from "@/store";
+import {
+ type AICompletionRequest_Message,
+ AICompletionRequest_MessageSchema,
+ AICompletionRequestSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import { nextAnimationFrame } from "@/utils";
+import * as promptUtils from "../logic/prompt";
+import { useConversationStore } from "../store";
+import { ActionBar } from "./ActionBar";
+import { ChatView } from "./ChatView/ChatView";
+import { useAIContext } from "./context";
+import { DynamicSuggestions } from "./DynamicSuggestions";
+import { HistoryPanel } from "./HistoryPanel/HistoryPanel";
+import { PromptInput } from "./PromptInput";
+
+/**
+ * React port of `plugins/ai/components/ChatPanel.vue`.
+ *
+ * The chat surface: ActionBar on top, ChatView in the middle (or a
+ * spinner while the per-tab fetch lands), DynamicSuggestions +
+ * PromptInput at the bottom, and the HistoryPanel drawer mounted once.
+ *
+ * `requestAI(query)` is the orchestrator:
+ * 1. Push a USER message. On the FIRST message of a conversation,
+ * prepend the schema declaration so the model has context. Subsequent
+ * messages use the bare query.
+ * 2. Push an AI message in `LOADING` state.
+ * 3. Call `sqlServiceClientConnect.aICompletion` with the full history.
+ * 4. Update the AI message with the response (DONE) or error (FAILED).
+ * 5. On FAILED, emit `error` on `aiContextEvents` for the host to
+ * surface (e.g. toast).
+ *
+ * Two `flush: "post"` watch blocks from the Vue version translate to
+ * `useEffect` + rAF in React:
+ * - Auto-create an empty conversation when the per-tab fetch resolves
+ * to an empty list.
+ * - Fire `requestAI` when the `send-chat` event handler in the
+ * provider stashes a `pendingSendChat` payload.
+ */
+export function ChatPanel() {
+ const tabStore = useSQLEditorTabStore();
+ const store = useConversationStore();
+ // Reactive bridge for `tabStore.currentTab` — Pinia mutates the tab
+ // proxy in place when the connection changes, so a plain
+ // `tabStore.currentTab` read at render time would miss updates.
+ const hasCurrentTab = useVueState(() => tabStore.currentTab != null);
+
+ const context = useAIContext();
+ const {
+ aiSetting,
+ chat,
+ setShowHistoryDialog,
+ pendingSendChat,
+ setPendingSendChat,
+ events,
+ } = context;
+ const { list: conversationList, ready, selected } = chat;
+
+ const [loading, setLoading] = useState(false);
+
+ // Reactive tab/connection signal so we can hide history on
+ // (instance, database) change. Reading the connection fields via
+ // `useVueState` gives us a stable string key the effect can depend on.
+ const connectionKey = useVueState(() => {
+ const tab = tabStore.currentTab;
+ if (!tab) return "";
+ return `${tab.connection.instance}|${tab.connection.database}`;
+ });
+ useEffect(() => {
+ setShowHistoryDialog(false);
+ }, [connectionKey, setShowHistoryDialog]);
+
+ // Pull the latest `requestAI` into a ref so the pending-send-chat
+ // effect doesn't need to depend on its identity (the callback closes
+ // over `selected`, `aiSetting`, etc. — wiring those as effect deps
+ // would re-run the effect on every conversation tweak).
+ const requestAIRef = useRef<(query: string) => Promise<void>>(async () => {});
+
+ const requestAI = useCallback(
+ async (query: string) => {
+ const conversation = selected;
+ if (!conversation) return;
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+
+ const { messageList } = conversation;
+ if (messageList.length === 0) {
+ const engine = context.engine;
+ const databaseMetadata = context.databaseMetadata;
+ const schema = context.schema;
+ const prompts: string[] = [
+ 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",
+ });
+ 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({
+ author: "AI",
+ prompt: "",
+ content: "",
+ error: "",
+ conversation_id: conversation.id,
+ status: "LOADING",
+ });
+ const messages: AICompletionRequest_Message[] =
+ conversation.messageList.map((message) =>
+ createProto(AICompletionRequest_MessageSchema, {
+ role: message.author === "USER" ? "user" : "assistant",
+ content: message.prompt,
+ })
+ );
+ setLoading(true);
+ try {
+ const request = createProto(AICompletionRequestSchema, { messages });
+ const response = await sqlServiceClientConnect.aICompletion(request);
+ const text = head(
+ head(response.candidates)?.content?.parts
+ )?.text?.trim();
+ console.debug("[AI Assistant] answer:", text);
+ if (text) {
+ answer.content = text;
+ answer.prompt = text;
+ }
+ answer.status = "DONE";
+ } catch (err) {
+ answer.error = String(err);
+ answer.status = "FAILED";
+ } finally {
+ setLoading(false);
+ await store.updateMessage(answer);
+ if (answer.status === "FAILED") {
+ events.emit("error", answer.error);
+ }
+ }
+ },
+ [
+ selected,
+ tabStore,
+ store,
+ context.engine,
+ context.databaseMetadata,
+ context.schema,
+ events,
+ ]
+ );
+ requestAIRef.current = requestAI;
+
+ // Auto-create an empty conversation when the per-tab fetch resolves
+ // to an empty list. Mirrors the Vue `watch([ready, conversationList],
+ // ..., { immediate: true })` — `requestAnimationFrame` defers to the
+ // next paint so any concurrent provider-side `new-conversation` flow
+ // gets a chance to claim the slot first.
+ useEffect(() => {
+ if (!ready) return;
+ if (conversationList.length > 0) return;
+ void store.createConversation({
+ name: "",
+ instance: tabStore.currentTab?.connection.instance ?? "",
+ database: tabStore.currentTab?.connection.database ?? "",
+ });
+ // We intentionally watch only the boolean transition + the empty
+ // condition, not the full `conversationList` reference — Vue's
+ // version reacts on identity; the React version reacts on the
+ // length so we don't fire each time a new message arrives.
+ }, [ready, conversationList.length, store, tabStore]);
+
+ // Fire `requestAI` when a pending send-chat lands. The Vue version
+ // used `watch(..., { flush: "post" })` — we approximate by waiting
+ // for the next animation frame so the conversation creation in the
+ // provider's `send-chat` handler has settled.
+ useEffect(() => {
+ if (!ready) return;
+ if (!pendingSendChat) return;
+ let cancelled = false;
+ void (async () => {
+ await nextAnimationFrame();
+ if (cancelled) return;
+ const payload = pendingSendChat;
+ setPendingSendChat(undefined);
+ if (!payload) return;
+ void requestAIRef.current(payload.content);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [ready, pendingSendChat, setPendingSendChat]);
+
+ if (!aiSetting.enabled) return null;
+
+ return (
+ <div className="w-full h-full flex-1 flex flex-col overflow-hidden">
+ <ActionBar />
+
+ {ready ? (
+ <ChatView conversation={selected} />
+ ) : (
+ <div className="flex-1 overflow-hidden relative flex items-center justify-center">
+ <Loader2 className="size-5 animate-spin text-control-light" />
+ </div>
+ )}
+
+ <div className="px-2 pb-2 pt-1 flex flex-col gap-1">
+ <DynamicSuggestions onEnter={(value) => void requestAI(value)} />
+ {hasCurrentTab && (
+ <PromptInput
+ disabled={loading}
+ onEnter={(value) => void requestAI(value)}
+ />
+ )}
+ </div>
+
+ <HistoryPanel />
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/AIMessageView.tsx b/frontend/src/plugins/ai/react/ChatView/AIMessageView.tsx
new file mode 100644
index 0000000000..95341b9ad5
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/AIMessageView.tsx
@@ -0,0 +1,51 @@
+import { Loader2, TriangleAlertIcon } from "lucide-react";
+import { cn } from "@/react/lib/utils";
+import type { Message } from "../../types";
+import { Markdown } from "./Markdown/Markdown";
+
+type Props = {
+ readonly message: Message;
+};
+
+/**
+ * React port of `plugins/ai/components/ChatView/AIMessageView.vue`.
+ *
+ * Three render states keyed off `message.status`:
+ * - DONE → `<Markdown>` of `message.content`, full-width bubble.
+ * - LOADING → small spinner, content-width bubble.
+ * - FAILED → warning icon + error text, capped at 40% width.
+ *
+ * `codeBlockProps.width: 1.0` because the AI bubble already spans the
+ * row, so an embedded code card uses 100% of the bubble width.
+ */
+export function AIMessageView({ message }: Props) {
+ const isDone = message.status === "DONE";
+ const isLoading = message.status === "LOADING";
+ const isFailed = message.status === "FAILED";
+
+ return (
+ <div
+ className={cn(
+ "border rounded-sm shadow-sm py-1 px-1 bg-gray-50 border-gray-400",
+ isDone && "w-full min-w-36",
+ isFailed && "max-w-[40%] min-w-36",
+ !isDone && !isFailed && "w-auto"
+ )}
+ >
+ {isDone && (
+ <Markdown content={message.content} codeBlockProps={{ width: 1.0 }} />
+ )}
+ {isLoading && (
+ <div className="flex items-center">
+ <Loader2 className="mx-1 size-[18px] animate-spin" />
+ </div>
+ )}
+ {isFailed && (
+ <div className="text-warning flex items-center gap-x-1">
+ <TriangleAlertIcon className="inline-block size-4 shrink-0" />
+ <span className="text-sm">{message.error}</span>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/ChatView.tsx b/frontend/src/plugins/ai/react/ChatView/ChatView.tsx
new file mode 100644
index 0000000000..e73ec0e65e
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/ChatView.tsx
@@ -0,0 +1,109 @@
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import type { Conversation } from "../../types";
+import { useAIContext } from "../context";
+import { AIMessageView } from "./AIMessageView";
+import { ChatViewProvider, type Mode } from "./context";
+import { EmptyView } from "./EmptyView";
+import { UserMessageView } from "./UserMessageView";
+
+type Props = {
+ readonly mode?: Mode;
+ readonly conversation?: Conversation;
+};
+
+/**
+ * React port of `plugins/ai/components/ChatView/ChatView.vue`.
+ *
+ * Scrollable message list. Auto-scrolls to the bottom whenever the
+ * inner container's height changes (a new message arrives, an AI
+ * response streams in, etc.) — same `useElementSize` trigger as the
+ * Vue version, ported to a `ResizeObserver`.
+ *
+ * Two empty paths:
+ * - `mode="VIEW"` with a conversation that has no messages → `<EmptyView>`.
+ * - `mode="CHAT"` with no conversation at all → "select or create"
+ * prompt with a clickable Create. The `select-or-create` i18n
+ * string uses a `{create}` interpolation slot; we split manually
+ * because `react-i18next`'s `Trans` v17 wipes child slots on
+ * empty placeholder tags (see SelectionCopyTooltips for the same
+ * fix in Stage 20).
+ */
+export function ChatView({ mode = "CHAT", conversation }: Props) {
+ const { t } = useTranslation();
+ const { events } = useAIContext();
+
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ const scroller = scrollerRef.current;
+ if (!container || !scroller) return;
+ const scrollToBottom = () => {
+ scroller.scrollTo(0, container.scrollHeight);
+ };
+ scrollToBottom();
+ const observer = new ResizeObserver(scrollToBottom);
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, [conversation?.id, conversation?.messageList.length]);
+
+ const chatViewValue = useMemo(() => ({ mode }), [mode]);
+
+ // i18n: "Select or {create} a conversation to start." — split on the
+ // placeholder so we can render the localized prefix/suffix around a
+ // clickable button. Matches every locale's structure since they all
+ // keep the same `{create}` placeholder.
+ const selectOrCreateTemplate = t("plugin.ai.conversation.select-or-create");
+ const selectOrCreateParts = selectOrCreateTemplate.split("{create}");
+
+ return (
+ <ChatViewProvider value={chatViewValue}>
+ <div ref={scrollerRef} className="flex-1 overflow-y-auto">
+ {conversation ? (
+ conversation.messageList.length === 0 ? (
+ mode === "VIEW" ? (
+ <EmptyView />
+ ) : null
+ ) : (
+ <div
+ ref={containerRef}
+ className="flex flex-col justify-end px-2 gap-y-4"
+ >
+ {conversation.messageList.map((message) => (
+ <div
+ key={message.id}
+ className={`flex message ${
+ message.author === "AI" ? "justify-start" : "justify-end"
+ }`}
+ >
+ {message.author === "USER" && (
+ <UserMessageView message={message} />
+ )}
+ {message.author === "AI" && (
+ <AIMessageView message={message} />
+ )}
+ </div>
+ ))}
+ </div>
+ )
+ ) : mode === "CHAT" ? (
+ <div className="w-full h-full flex flex-col justify-end items-center pb-8">
+ <p className="text-sm text-control-light">
+ {selectOrCreateParts[0]}
+ <button
+ type="button"
+ className="text-accent underline hover:text-accent-hover cursor-pointer"
+ onClick={() => events.emit("new-conversation", { input: "" })}
+ >
+ {t("common.create")}
+ </button>
+ {selectOrCreateParts[1] ?? ""}
+ </p>
+ </div>
+ ) : null}
+ </div>
+ </ChatViewProvider>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/EmptyView.tsx b/frontend/src/plugins/ai/react/ChatView/EmptyView.tsx
new file mode 100644
index 0000000000..e6d341c133
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/EmptyView.tsx
@@ -0,0 +1,23 @@
+import { Inbox } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+/**
+ * React port of `plugins/ai/components/ChatView/EmptyView.vue`.
+ * Empty-state placeholder shown when a `mode="VIEW"` conversation has
+ * no messages. Replaces naive-ui's `NEmpty` with a simple inline icon +
+ * caption — the only place in the AI plugin that used `NEmpty` so
+ * keeping naive-ui just for this would be wasteful.
+ */
+export function EmptyView() {
+ const { t } = useTranslation();
+ return (
+ <div className="w-full h-full flex flex-col justify-center items-center">
+ <div className="w-[20rem] mx-auto flex flex-col items-center gap-y-2 py-6">
+ <Inbox className="size-12 text-control-placeholder" />
+ <p className="text-center text-sm text-control-light">
+ {t("plugin.ai.conversation.no-message")}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/Markdown/AstToReact.tsx b/frontend/src/plugins/ai/react/ChatView/Markdown/AstToReact.tsx
new file mode 100644
index 0000000000..51a10e7707
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/Markdown/AstToReact.tsx
@@ -0,0 +1,22 @@
+import type { Root } from "mdast";
+import { type CustomSlots, mdastToReact, type State } from "./utils";
+
+type Props = {
+ readonly ast: Root;
+ readonly slots?: CustomSlots;
+};
+
+/**
+ * React port of `plugins/ai/components/ChatView/Markdown/AstToVNode.vue`.
+ * Walks the mdast root via `mdastToReact[node.type]` and returns the
+ * React tree. `slots` overrides the default renderer for specific node
+ * types (`code`, `inlineCode`, `image`) — same hook the Vue version
+ * exposed via `defineSlots`.
+ */
+export function AstToReact({ ast, slots = {} }: Props) {
+ const state: State = {
+ slots,
+ definitionById: new Map(),
+ };
+ return <>{mdastToReact[ast.type](ast, state)}</>;
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/Markdown/CodeBlock.tsx b/frontend/src/plugins/ai/react/ChatView/Markdown/CodeBlock.tsx
new file mode 100644
index 0000000000..2697c6c53b
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/Markdown/CodeBlock.tsx
@@ -0,0 +1,206 @@
+import { Check, Copy, PlayIcon } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { MonacoEditor } from "@/react/components/monaco/MonacoEditor";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { findAncestor } from "@/utils";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
+import { useAIContext } from "../../context";
+
+export type CodeBlockProps = {
+ /** Fraction (0..1) of the parent `.message` width the snippet card occupies. */
+ width: number;
+};
+
+type Props = CodeBlockProps & {
+ code: string;
+};
+
+const MIN_WIDTH_PX = 8 * 16; // 8rem — same minimum as the Vue source.
+const PADDING_PX = 8;
+
+/**
+ * React port of `plugins/ai/components/ChatView/Markdown/CodeBlock.vue`.
+ *
+ * Renders a SQL snippet inside a read-only `MonacoEditor` with three
+ * actions:
+ * - Run: `aiContextEvents.emit("run-statement", { statement })`
+ * (the SQL editor host listens and executes the snippet)
+ * - Insert-at-caret: `sqlEditorEvents.emit("insert-at-caret", { content })`
+ * - Copy: writes to the clipboard with an ephemeral "Copied" indicator.
+ *
+ * Width is adaptive: measure the nearest `.message` ancestor (set by
+ * `ChatView`) via ResizeObserver and clamp to `[MIN_WIDTH_PX, ...]`.
+ * `width` is the fraction of the message bubble this card occupies —
+ * `AIMessageView` passes `0.85`.
+ */
+export function CodeBlock({ code, width }: Props) {
+ const { t } = useTranslation();
+ const { events, setShowHistoryDialog } = useAIContext();
+
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ // The message wrapper element is mounted by `ChatView` with the
+ // `.message` class. We measure it (not our own container) so the
+ // snippet can size relative to the bubble even when the bubble shrinks
+ // due to a sibling layout change.
+ const [messageWidth, setMessageWidth] = useState(0);
+
+ useEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const messageEl = findAncestor(el, ".message");
+ if (!(messageEl instanceof HTMLElement)) return;
+ const update = () => setMessageWidth(messageEl.clientWidth);
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(messageEl);
+ return () => observer.disconnect();
+ }, []);
+
+ const computedWidth = Math.max(
+ MIN_WIDTH_PX,
+ messageWidth * width - PADDING_PX * 2
+ );
+
+ const handleExecute = () => {
+ events.emit("run-statement", { statement: code });
+ setShowHistoryDialog(false);
+ };
+
+ const handleInsertAtCaret = () => {
+ sqlEditorEvents.emit("insert-at-caret", { content: code });
+ setShowHistoryDialog(false);
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ className="flex flex-col overflow-x-hidden border border-gray-500 rounded-sm bg-white"
+ style={{ width: `${computedWidth}px` }}
+ >
+ <div className="flex items-center justify-between px-1 pt-1">
+ <div className="text-xs">SQL</div>
+ <div className="flex items-center justify-end gap-2">
+ <Tooltip content={t("common.run")} side="bottom">
+ <button
+ type="button"
+ className="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ onClick={handleExecute}
+ aria-label={t("common.run")}
+ >
+ <PlayIcon className="size-3.5" />
+ </button>
+ </Tooltip>
+ <Tooltip
+ content={t("plugin.ai.actions.insert-at-caret")}
+ side="bottom"
+ >
+ <button
+ type="button"
+ className="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ onClick={handleInsertAtCaret}
+ aria-label={t("plugin.ai.actions.insert-at-caret")}
+ >
+ <InsertAtCaretIconCompact />
+ </button>
+ </Tooltip>
+ <Tooltip content={t("common.copy")} side="bottom">
+ <CopyButton content={code} />
+ </Tooltip>
+ </div>
+ </div>
+
+ <MonacoEditor
+ content={code}
+ readOnly
+ autoFocus={false}
+ autoHeight
+ min={20}
+ max={120}
+ options={{
+ fontSize: 12,
+ lineHeight: 14,
+ lineNumbers: "off",
+ wordWrap: "on",
+ scrollbar: {
+ vertical: "hidden",
+ horizontal: "hidden",
+ useShadows: false,
+ verticalScrollbarSize: 0,
+ horizontalScrollbarSize: 0,
+ alwaysConsumeMouseWheel: false,
+ },
+ }}
+ className="h-auto"
+ />
+ </div>
+ );
+}
+
+/**
+ * Inline copy of `InsertAtCaretIcon` at a fixed 14px to match the other
+ * action buttons. Avoids an extra import + size prop juggling.
+ */
+function InsertAtCaretIconCompact() {
+ return (
+ <span
+ style={{ width: 14, height: 14 }}
+ className="relative inline-block"
+ aria-hidden="true"
+ >
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <line x1="21" y1="6" x2="3" y2="6" />
+ <line x1="15" y1="12" x2="3" y2="12" />
+ <line x1="17" y1="18" x2="3" y2="18" />
+ </svg>
+ </span>
+ );
+}
+
+/**
+ * Inline 20-LOC copy primitive. No shared `CopyButton` exists in
+ * `react/components/` yet; extracting one is out of scope for Stage 22.
+ * Falls back silently when `navigator.clipboard` is missing (SSR / older
+ * browsers) — same conservative behaviour as `TableSchemaViewer.tsx`.
+ */
+function CopyButton({ content }: { content: string }) {
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ if (!copied) return;
+ const handle = window.setTimeout(() => setCopied(false), 1500);
+ return () => window.clearTimeout(handle);
+ }, [copied]);
+
+ const handleClick = async () => {
+ if (typeof navigator === "undefined" || !navigator.clipboard) return;
+ try {
+ await navigator.clipboard.writeText(content);
+ setCopied(true);
+ } catch {
+ // ignore — same posture as TableSchemaViewer.tsx
+ }
+ };
+
+ return (
+ <button
+ type="button"
+ className="inline-flex items-center justify-center hover:text-accent cursor-pointer"
+ onClick={handleClick}
+ >
+ {copied ? (
+ <Check className="size-3.5 text-success" />
+ ) : (
+ <Copy className="size-3.5" />
+ )}
+ </button>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/Markdown/InsertAtCaretIcon.tsx b/frontend/src/plugins/ai/react/ChatView/Markdown/InsertAtCaretIcon.tsx
new file mode 100644
index 0000000000..14b6b0c98d
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/Markdown/InsertAtCaretIcon.tsx
@@ -0,0 +1,30 @@
+import { AlignLeftIcon, ArrowLeftIcon } from "lucide-react";
+
+type Props = {
+ readonly size?: number;
+};
+
+/**
+ * React port of `plugins/ai/components/ChatView/Markdown/InsertAtCaretIcon.vue`.
+ *
+ * Composite icon = `AlignLeftIcon` (paragraph lines) with an accent-colored
+ * `ArrowLeftIcon` overlaid in the bottom-right. Visualizes "insert this
+ * snippet at the editor's caret position".
+ */
+export function InsertAtCaretIcon({ size = 16 }: Props) {
+ return (
+ <div className="inline-block relative">
+ <AlignLeftIcon style={{ width: `${size}px`, height: `${size}px` }} />
+ <ArrowLeftIcon
+ className="text-accent absolute"
+ strokeWidth={4}
+ style={{
+ width: `${size * 0.7}px`,
+ height: `${size * 0.7}px`,
+ right: `${size * -0.2}px`,
+ bottom: `${size * 0.035}px`,
+ }}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/Markdown/Markdown.tsx b/frontend/src/plugins/ai/react/ChatView/Markdown/Markdown.tsx
new file mode 100644
index 0000000000..0755dcd52c
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/Markdown/Markdown.tsx
@@ -0,0 +1,47 @@
+import { createElement, useMemo } from "react";
+import remarkGfm from "remark-gfm";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+import { AstToReact } from "./AstToReact";
+import { CodeBlock, type CodeBlockProps } from "./CodeBlock";
+import type { CustomSlots } from "./utils";
+
+const processor = unified().use(remarkParse).use(remarkGfm);
+
+type Props = {
+ readonly content: string;
+ readonly codeBlockProps: CodeBlockProps;
+};
+
+/**
+ * React port of `plugins/ai/components/ChatView/Markdown/Markdown.vue`.
+ *
+ * Parses the message content with `remark-parse` + `remark-gfm` and
+ * walks the AST via `AstToReact`. Three slots customize rendering:
+ * - `code` (block-level fenced code) → `<CodeBlock>` (interactive,
+ * SQL editor with Run/Insert/Copy)
+ * - `inlineCode` → plain styled `<code>` (the Vue version used
+ * `HighlightCodeBlock`; for parity we render the same gray pill
+ * without syntax highlighting — short snippets rarely benefit)
+ * - `image` → unstyled `<img>`
+ */
+export function Markdown({ content, codeBlockProps }: Props) {
+ const ast = useMemo(() => processor.parse(content ?? ""), [content]);
+
+ const slots: CustomSlots = useMemo(
+ () => ({
+ code: (node) =>
+ createElement(CodeBlock, { code: node.value, ...codeBlockProps }),
+ inlineCode: (node) =>
+ createElement(
+ "code",
+ { className: "inline-block bg-gray-200 px-0.5 mx-0.5" },
+ node.value.replace(/\r?\n|\r/g, " ")
+ ),
+ image: (node) => createElement("img", { src: node.url }),
+ }),
+ [codeBlockProps]
+ );
+
+ return <AstToReact ast={ast} slots={slots} />;
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/Markdown/utils.ts b/frontend/src/plugins/ai/react/ChatView/Markdown/utils.ts
new file mode 100644
index 0000000000..fe8c0c8a4a
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/Markdown/utils.ts
@@ -0,0 +1,430 @@
+import type {
+ AlignType,
+ Definition,
+ Root,
+ RootContent,
+ RootContentMap,
+ Text,
+} from "mdast";
+import { normalizeUri } from "micromark-util-sanitize-uri";
+import type { ReactNode } from "react";
+import { createElement, Fragment } from "react";
+
+/**
+ * React port of `plugins/ai/components/ChatView/Markdown/utils.ts`.
+ *
+ * Same mdast walker as the Vue version; `h(...)` is swapped for
+ * `React.createElement(...)`. Differences from the Vue source:
+ *
+ * - `class` becomes `className`; HTML attributes use React's
+ * camelCased form (`htmlFor`, `tabIndex`, etc. — none of those
+ * actually appear here).
+ * - `style` props use a CSS object instead of a string.
+ * - Arrays of children get explicit `key`s (React warns when keys are
+ * missing; Vue auto-keys by index).
+ * - `slots` is a plain mapped object (`{ code?, inlineCode?, image? }`)
+ * instead of Vue's `defineSlots<CustomRender>`.
+ */
+
+export type CustomSlotRenderer<K extends keyof RootContentMap> = (
+ node: RootContentMap[K],
+ state: State
+) => ReactNode;
+
+export type CustomSlots = Partial<{
+ blockquote: CustomSlotRenderer<"blockquote">;
+ break: CustomSlotRenderer<"break">;
+ code: CustomSlotRenderer<"code">;
+ delete: CustomSlotRenderer<"delete">;
+ emphasis: CustomSlotRenderer<"emphasis">;
+ footnoteDefinition: CustomSlotRenderer<"footnoteDefinition">;
+ footnoteReference: CustomSlotRenderer<"footnoteReference">;
+ heading: CustomSlotRenderer<"heading">;
+ html: CustomSlotRenderer<"html">;
+ image: CustomSlotRenderer<"image">;
+ definition: CustomSlotRenderer<"definition">;
+ imageReference: CustomSlotRenderer<"imageReference">;
+ inlineCode: CustomSlotRenderer<"inlineCode">;
+ link: CustomSlotRenderer<"link">;
+ linkReference: CustomSlotRenderer<"linkReference">;
+ list: CustomSlotRenderer<"list">;
+ listItem: CustomSlotRenderer<"listItem">;
+ paragraph: CustomSlotRenderer<"paragraph">;
+ strong: CustomSlotRenderer<"strong">;
+ table: CustomSlotRenderer<"table">;
+ text: CustomSlotRenderer<"text">;
+ thematicBreak: CustomSlotRenderer<"thematicBreak">;
+}>;
+
+export type State = {
+ slots: CustomSlots;
+ definitionById: Map<string, Definition>;
+};
+
+type GenericNodeHandler = (node: RootContent, state: State) => ReactNode;
+
+function withKeys(children: ReactNode[]): ReactNode[] {
+ return children.map((child, index) => {
+ if (child === null || child === undefined || child === false) return child;
+ if (typeof child === "string" || typeof child === "number") {
+ // Strings can't carry keys directly — wrap in a Fragment with key
+ // so React's reconciler is happy across re-renders.
+ return createElement(Fragment, { key: index }, child);
+ }
+ // Element nodes already get an index-based key via cloneElement-by-key.
+ // We rely on the caller mapping unique indices.
+ return child;
+ });
+}
+
+function mapChildren<T extends { type: string }>(
+ children: T[],
+ state: State
+): ReactNode[] {
+ return withKeys(
+ children.map((child) => defaultMdNodeToReact(child as RootContent, state))
+ );
+}
+
+function defaultMdNodeToReact(node: RootContent, state: State): ReactNode {
+ const { type } = node;
+ const customSlot = state.slots[type as keyof CustomSlots] as
+ | GenericNodeHandler
+ | undefined;
+ if (customSlot) {
+ return customSlot(node, state);
+ }
+ const handler = (mdastToReact[type as keyof typeof mdastToReact] ??
+ mdastToReact.unknown) as GenericNodeHandler;
+ return handler(node, state);
+}
+
+function rootToReact(node: Root, state: State): ReactNode {
+ return createElement(
+ "div",
+ { className: "markdown" },
+ mapChildren(node.children, state)
+ );
+}
+
+function blockquoteToReact(
+ node: RootContentMap["blockquote"],
+ state: State
+): ReactNode {
+ return createElement("blockquote", null, mapChildren(node.children, state));
+}
+
+function breakToReact(): ReactNode {
+ return createElement("br");
+}
+
+function codeToReact(node: RootContentMap["code"]): ReactNode {
+ const value = node.value ? node.value + "\n" : "";
+ const codeProps: { className?: string } = {};
+ if (node.lang) {
+ codeProps.className = `language-${node.lang}`;
+ }
+ return createElement("pre", null, createElement("code", codeProps, value));
+}
+
+function deleteToReact(
+ node: RootContentMap["delete"],
+ state: State
+): ReactNode {
+ return createElement("del", null, mapChildren(node.children, state));
+}
+
+function emphasisToReact(
+ node: RootContentMap["emphasis"],
+ state: State
+): ReactNode {
+ return createElement("em", null, mapChildren(node.children, state));
+}
+
+function footnoteDefinitionToReact(
+ node: RootContentMap["footnoteDefinition"]
+): ReactNode {
+ // Same shape as the Vue source — render the first text child inside a
+ // `<div class="footnote-definition">`. The richer footnote-numbering
+ // path was commented out in Vue and isn't needed for LLM output.
+ const text = node.children[0] as unknown as Text;
+ return createElement("div", { className: "footnote-definition" }, text.value);
+}
+
+function footnoteReferenceToReact(): ReactNode {
+ return null;
+}
+
+function headingToReact(
+ node: RootContentMap["heading"],
+ state: State
+): ReactNode {
+ const tagName = `h${node.depth}`;
+ return createElement(tagName, null, mapChildren(node.children, state));
+}
+
+function htmlToReact(node: RootContentMap["html"]): ReactNode {
+ return node.value;
+}
+
+type ImageProps = {
+ src: string;
+ alt?: string;
+ title?: string;
+};
+
+function imageToReact(node: RootContentMap["image"]): ReactNode {
+ const props: ImageProps = { src: normalizeUri(node.url) };
+ if (node.alt) props.alt = node.alt;
+ if (node.title) props.title = node.title;
+ return createElement("img", props);
+}
+
+function definitionToReact(
+ node: RootContentMap["definition"],
+ state: State
+): ReactNode {
+ const id = String(node.identifier).toUpperCase();
+ state.definitionById.set(id, {
+ url: node.url,
+ type: "definition",
+ identifier: node.identifier,
+ });
+ return null;
+}
+
+function referenceToText(
+ node: RootContentMap["imageReference"] | RootContentMap["linkReference"],
+ state: State
+): ReactNode {
+ if (node.type === "imageReference") {
+ return `![${node.alt ?? ""}]`;
+ }
+ const children = mapChildren(node.children, state);
+ const hasReactNode = children.some(
+ (c) => typeof c !== "string" && typeof c !== "number"
+ );
+ return hasReactNode
+ ? createElement("span", null, "[", ...children, "]")
+ : `[${children.join("")}]`;
+}
+
+function imageReferenceToReact(
+ node: RootContentMap["imageReference"],
+ state: State
+): ReactNode {
+ const id = String(node.identifier).toUpperCase();
+ const definition = state.definitionById.get(id);
+ if (!definition) {
+ return referenceToText(node, state);
+ }
+ const props: ImageProps = { src: normalizeUri(definition.url || "") };
+ if (node.alt) props.alt = node.alt;
+ if (definition.title) props.title = definition.title;
+ return createElement("img", props);
+}
+
+function inlineCodeToReact(node: RootContentMap["inlineCode"]): ReactNode {
+ const value = node.value.replace(/\r?\n|\r/g, " ");
+ return createElement("code", null, value);
+}
+
+type LinkProps = {
+ href: string;
+ target: string;
+ rel: string;
+ title?: string;
+};
+
+function linkToReact(node: RootContentMap["link"], state: State): ReactNode {
+ const props: LinkProps = {
+ href: normalizeUri(node.url),
+ target: "_blank",
+ rel: "noreferrer nofollow noopener",
+ };
+ if (node.title) props.title = node.title;
+ return createElement("a", props, mapChildren(node.children, state));
+}
+
+function linkReferenceToReact(
+ node: RootContentMap["linkReference"],
+ state: State
+): ReactNode {
+ const id = String(node.identifier).toUpperCase();
+ const definition = state.definitionById.get(id);
+ if (!definition) {
+ return referenceToText(node, state);
+ }
+ const props: LinkProps = {
+ href: normalizeUri(definition.url || ""),
+ target: "_blank",
+ rel: "noreferrer nofollow noopener",
+ };
+ if (definition.title) props.title = definition.title;
+ return createElement("a", props, mapChildren(node.children, state));
+}
+
+function listToReact(node: RootContentMap["list"], state: State): ReactNode {
+ const children = mapChildren(node.children, state);
+ const ordered = node.ordered === true;
+ const startProp =
+ ordered && typeof node.start === "number" && node.start !== 1
+ ? { start: node.start }
+ : ordered
+ ? { start: 1 }
+ : {};
+ return createElement(
+ ordered ? "ol" : "ul",
+ {
+ style: {
+ listStyle: ordered ? "auto" : "initial",
+ marginLeft: "1rem",
+ },
+ ...startProp,
+ },
+ children
+ );
+}
+
+function listItemToReact(
+ node: RootContentMap["listItem"],
+ state: State
+): ReactNode {
+ const children = mapChildren(node.children, state);
+ const liProps: { className?: string } = {};
+ if (typeof node.checked === "boolean") {
+ // GitHub-style task list items: prepend a disabled checkbox + use
+ // `task-list-item` so github-markdown-css hides the bullet.
+ children.unshift(
+ createElement("input", {
+ key: "task-checkbox",
+ type: "checkbox",
+ checked: node.checked,
+ disabled: true,
+ // React expects `readOnly` when a controlled `checked` is set
+ // without an `onChange`; suppress the warning.
+ readOnly: true,
+ })
+ );
+ liProps.className = "task-list-item";
+ }
+ return createElement("li", liProps, children);
+}
+
+function paragraphToReact(
+ node: RootContentMap["paragraph"],
+ state: State
+): ReactNode {
+ // Match the Vue version's `<div class="paragraph">` (avoids `<p>` inside
+ // surrounding `<p>` when host components nest markdown).
+ return createElement(
+ "div",
+ { className: "paragraph" },
+ mapChildren(node.children, state)
+ );
+}
+
+function strongToReact(
+ node: RootContentMap["strong"],
+ state: State
+): ReactNode {
+ return createElement("strong", null, mapChildren(node.children, state));
+}
+
+function tableRowToReact(
+ node: RootContentMap["tableRow"],
+ align: AlignType[],
+ rowIndex: number,
+ state: State
+): ReactNode {
+ const tagName = rowIndex === 0 ? "th" : "td";
+ const cells = node.children.map((cell, cellIndex) => {
+ const cellAlign = align[cellIndex];
+ const cellProps = cellAlign
+ ? { key: cellIndex, align: cellAlign as string }
+ : { key: cellIndex };
+ return createElement(tagName, cellProps, mapChildren(cell.children, state));
+ });
+ return createElement("tr", null, cells);
+}
+
+function tableToReact(node: RootContentMap["table"], state: State): ReactNode {
+ const align = node.align ?? [];
+ const headCells: ReactNode[] = [];
+ const bodyRows: ReactNode[] = [];
+ node.children.forEach((row, rowIndex) => {
+ const tr = tableRowToReact(row, align, rowIndex, state);
+ if (rowIndex === 0) headCells.push(tr);
+ else bodyRows.push(tr);
+ });
+ const sections: ReactNode[] = [];
+ if (headCells.length > 0) {
+ sections.push(createElement("thead", { key: "thead" }, headCells));
+ }
+ if (bodyRows.length > 0) {
+ sections.push(createElement("tbody", { key: "tbody" }, bodyRows));
+ }
+ return createElement("table", null, sections);
+}
+
+function textToReact(node: RootContentMap["text"]): ReactNode {
+ return node.value;
+}
+
+function thematicBreakToReact(): ReactNode {
+ return createElement("hr");
+}
+
+function defaultUnknownHandler(node: RootContent, state: State): ReactNode {
+ if ("children" in node) {
+ const childrenArray = (node as { children: RootContent[] }).children;
+ const props: { className?: string } & Record<string, unknown> = {};
+ if ("properties" in node) {
+ const properties = (node as { properties?: Record<string, unknown> })
+ .properties;
+ if (properties && typeof properties === "object") {
+ Object.assign(props, properties);
+ if (
+ "className" in properties &&
+ Array.isArray((properties as Record<string, unknown>).className)
+ ) {
+ props.className = (
+ (properties as Record<string, unknown>).className as unknown[]
+ ).join(" ");
+ }
+ }
+ }
+ return createElement("div", props, mapChildren(childrenArray, state));
+ }
+ if ("value" in node) {
+ return (node as { value: unknown }).value as ReactNode;
+ }
+ return null;
+}
+
+export const mdastToReact = {
+ root: rootToReact,
+ blockquote: blockquoteToReact,
+ break: breakToReact,
+ code: codeToReact,
+ delete: deleteToReact,
+ emphasis: emphasisToReact,
+ footnoteDefinition: footnoteDefinitionToReact,
+ footnoteReference: footnoteReferenceToReact,
+ heading: headingToReact,
+ html: htmlToReact,
+ image: imageToReact,
+ definition: definitionToReact,
+ imageReference: imageReferenceToReact,
+ inlineCode: inlineCodeToReact,
+ link: linkToReact,
+ linkReference: linkReferenceToReact,
+ list: listToReact,
+ listItem: listItemToReact,
+ paragraph: paragraphToReact,
+ strong: strongToReact,
+ table: tableToReact,
+ text: textToReact,
+ thematicBreak: thematicBreakToReact,
+ unknown: defaultUnknownHandler,
+};
diff --git a/frontend/src/plugins/ai/react/ChatView/UserMessageView.tsx b/frontend/src/plugins/ai/react/ChatView/UserMessageView.tsx
new file mode 100644
index 0000000000..8068b24e3b
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/UserMessageView.tsx
@@ -0,0 +1,19 @@
+import type { Message } from "../../types";
+import { Markdown } from "./Markdown/Markdown";
+
+type Props = {
+ readonly message: Message;
+};
+
+/**
+ * React port of `plugins/ai/components/ChatView/UserMessageView.vue`.
+ * User-authored message bubble. Width clamped to 60% of the row so an
+ * AI response (`w-full`) and a user prompt visually contrast.
+ */
+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-indigo-100 border-indigo-400">
+ <Markdown content={message.content} codeBlockProps={{ width: 0.6 }} />
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/ChatView/context.tsx b/frontend/src/plugins/ai/react/ChatView/context.tsx
new file mode 100644
index 0000000000..e6b0410117
--- /dev/null
+++ b/frontend/src/plugins/ai/react/ChatView/context.tsx
@@ -0,0 +1,21 @@
+import { createContext, useContext } from "react";
+
+export type Mode = "CHAT" | "VIEW";
+
+export type ChatViewContext = {
+ mode: Mode;
+};
+
+const ChatViewReactContext = createContext<ChatViewContext | null>(null);
+
+export const ChatViewProvider = ChatViewReactContext.Provider;
+
+export function useChatViewContext(): ChatViewContext {
+ const ctx = useContext(ChatViewReactContext);
+ if (!ctx) {
+ throw new Error(
+ "useChatViewContext must be used inside <ChatViewProvider>"
+ );
+ }
+ return ctx;
+}
diff --git a/frontend/src/plugins/ai/react/DynamicSuggestions.tsx b/frontend/src/plugins/ai/react/DynamicSuggestions.tsx
new file mode 100644
index 0000000000..d4128da4e5
--- /dev/null
+++ b/frontend/src/plugins/ai/react/DynamicSuggestions.tsx
@@ -0,0 +1,160 @@
+import { Loader2, RefreshCwIcon, XIcon } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useCurrentUserV1 } from "@/store";
+import { storageKeySqlEditorAiSuggestion } from "@/utils";
+import { useDynamicSuggestions } from "../logic";
+import { useAIContext } from "./context";
+
+type Props = {
+ readonly onEnter: (query: string) => void;
+};
+
+/**
+ * React port of `plugins/ai/components/DynamicSuggestions.vue`.
+ *
+ * Shows up to one "suggested prompt" pill (LLM-generated) with refresh
+ * / dismiss controls. Clicking the pill emits the suggestion to the
+ * parent (`ChatPanel`) which submits it via `requestAI(query)`.
+ *
+ * `useDynamicSuggestions()` returns a Vue `ComputedRef<SuggestionContext>`
+ * where the inner object is a Pinia/Vue `reactive(...)` — we read each
+ * field via its own `useVueState` getter so React only re-renders when
+ * the specific field changes.
+ */
+export function DynamicSuggestions({ onEnter }: Props) {
+ const { t } = useTranslation();
+ const { databaseMetadata, engine, schema } = useAIContext();
+ // `useDynamicSuggestions` returns a Vue `ComputedRef<SuggestionContext>`
+ // whose `metadata` getter reads our params. We pass them via
+ // `MaybeRefOrGetter` getters so Vue's reactivity follows React's
+ // useVueState-bridged values (the React `databaseMetadata` etc. are
+ // already plain values that re-read on each call).
+ const suggestionsRef = useDynamicSuggestions({
+ databaseMetadata: () => databaseMetadata,
+ engine: () => engine,
+ schema: () => schema,
+ });
+ const currentUserRef = useCurrentUserV1();
+ const currentUserEmail = useVueState(() => currentUserRef.value.email);
+
+ const ready = useVueState(() => suggestionsRef.value?.ready ?? false);
+ const state = useVueState<"LOADING" | "IDLE" | "ENDED">(
+ () => suggestionsRef.value?.state ?? "IDLE"
+ );
+ const suggestionsCount = useVueState(
+ () => suggestionsRef.value?.suggestions.length ?? 0
+ );
+ const current = useVueState(() => suggestionsRef.value?.current());
+
+ // Kick off the initial fetch when the component mounts and the cache
+ // is empty — matches the Vue `onMounted` block.
+ useEffect(() => {
+ const suggestion = suggestionsRef.value;
+ if (suggestion && suggestion.suggestions.length === 0) {
+ void suggestion.fetch();
+ }
+ }, [suggestionsRef]);
+
+ // Per-user dismissable flag persisted to localStorage. Defaults to
+ // visible. Same storage key the Vue version used (`useDynamicLocalStorage`
+ // backed by `vueuse.useStorage`); we keep the key compatible so a user
+ // who dismissed in Vue stays dismissed in React.
+ const storageKey = useMemo(
+ () => storageKeySqlEditorAiSuggestion(currentUserEmail),
+ [currentUserEmail]
+ );
+ const [showSuggestion, setShowSuggestion] = useState<boolean>(() => {
+ try {
+ const raw = localStorage.getItem(storageKey);
+ if (raw === null) return true;
+ return JSON.parse(raw) as boolean;
+ } catch {
+ return true;
+ }
+ });
+ useEffect(() => {
+ try {
+ localStorage.setItem(storageKey, JSON.stringify(showSuggestion));
+ } catch {
+ // ignore
+ }
+ }, [storageKey, showSuggestion]);
+
+ const show = !ready || suggestionsCount > 0 || state === "LOADING";
+ if (!show) return null;
+
+ const handleConsume = () => {
+ const suggestion = suggestionsRef.value;
+ if (!suggestion) return;
+ const curr = suggestion.current();
+ if (!curr) return;
+ onEnter(curr);
+ suggestion.consume();
+ };
+
+ const handleRefresh = () => {
+ suggestionsRef.value?.consume();
+ };
+
+ return (
+ <div className="flex items-center overflow-hidden h-[22px]">
+ {!ready && (
+ <>
+ <Loader2 className="mr-2 size-4 animate-spin" />
+ <span className="text-sm">
+ {t("plugin.ai.conversation.tips.suggest-prompt")}
+ </span>
+ </>
+ )}
+
+ {ready && showSuggestion && (
+ <div className="relative flex items-center gap-1 overflow-hidden text-xs leading-4">
+ {current && (
+ <Button
+ variant="outline"
+ size="xs"
+ className="flex-1 overflow-hidden h-[22px]"
+ onClick={handleConsume}
+ >
+ <span className="w-full truncate leading-[22px]">{current}</span>
+ </Button>
+ )}
+
+ {state === "LOADING" && (
+ <Loader2 className="shrink-0 size-4 animate-spin" />
+ )}
+ {state === "IDLE" && (
+ <div className="flex items-center">
+ <Button
+ variant="ghost"
+ size="xs"
+ className="shrink-0 h-[22px] px-1.5"
+ onClick={handleRefresh}
+ aria-label={t("plugin.ai.conversation.tips.suggest-prompt")}
+ >
+ <RefreshCwIcon className="size-3.5" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="xs"
+ className="shrink-0 h-[22px] px-1.5"
+ onClick={() => setShowSuggestion(false)}
+ aria-label={t("common.close")}
+ >
+ <XIcon className="size-3.5" />
+ </Button>
+ </div>
+ )}
+ {state === "ENDED" && (
+ <span className="shrink-0 text-gray-500">
+ {t("plugin.ai.conversation.tips.no-more")}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx b/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx
new file mode 100644
index 0000000000..9749b78cdf
--- /dev/null
+++ b/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx
@@ -0,0 +1,194 @@
+import { head } from "lodash-es";
+import { Loader2, PencilIcon, PlusIcon, TrashIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import scrollIntoView from "scroll-into-view-if-needed";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/react/components/ui/alert-dialog";
+import { Button } from "@/react/components/ui/button";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { useSQLEditorTabStore } from "@/store";
+import { useConversationStore } from "../../store";
+import type { Conversation } from "../../types";
+import { useAIContext } from "../context";
+import { ConversationRenameDialog } from "./ConversationRenameDialog";
+
+/**
+ * React port of `plugins/ai/components/HistoryPanel/ConversationList.vue`.
+ *
+ * Per-tab list of historical conversations with select / rename / delete
+ * actions and a sticky "New conversation" footer.
+ *
+ * Behavioural pitfalls preserved from the Vue source:
+ * - On tab switch (`(instance, database)` change) the rename dialog is
+ * dismissed — a half-completed rename for a previous tab's
+ * conversation shouldn't survive a context change.
+ * - When the selected conversation changes the row scrolls into view
+ * (`scrollIntoView({ scrollMode: "if-needed" })`) so the user can
+ * spot the active conversation in a long list. rAF defers to the
+ * next paint so the freshly-inserted node is measurable.
+ * - On delete, the next-selected conversation matches the Vue
+ * `list[index]` heuristic (try to keep the cursor near where it
+ * was). Falls back to undefined when the list empties.
+ */
+export function ConversationList() {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const store = useConversationStore();
+ const { events, chat } = useAIContext();
+ const { list, ready, selected, setSelected } = chat;
+
+ const [rename, setRename] = useState<Conversation | undefined>(undefined);
+ const [deleteCandidate, setDeleteCandidate] = useState<
+ Conversation | undefined
+ >(undefined);
+
+ // Dismiss the rename dialog whenever the active tab's connection
+ // changes — a stale dialog tied to a different tab's conversation
+ // would mutate the wrong record on Save.
+ const connectionKey = useVueState(() => {
+ const tab = tabStore.currentTab;
+ if (!tab) return "";
+ return `${tab.connection.instance}|${tab.connection.database}`;
+ });
+ useEffect(() => {
+ setRename(undefined);
+ setDeleteCandidate(undefined);
+ }, [connectionKey]);
+
+ // Scroll the selected row into view when it changes.
+ useEffect(() => {
+ if (!selected?.id || list.length === 0) return;
+ const raf = requestAnimationFrame(() => {
+ const elem = document.querySelector(
+ `[data-conversation-id="${selected.id}"]`
+ );
+ if (elem) scrollIntoView(elem, { scrollMode: "if-needed" });
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [selected?.id, list]);
+
+ const handleConfirmDelete = async () => {
+ if (!deleteCandidate) return;
+ const index = list.findIndex((c) => c.id === selected?.id);
+ await store.deleteConversation(deleteCandidate.id);
+ setDeleteCandidate(undefined);
+ setSelected(list[index] ?? undefined);
+ };
+
+ return (
+ <div className="h-full overflow-hidden flex flex-col">
+ <div className="flex-1 overflow-y-auto p-1 flex flex-col gap-y-2">
+ {ready ? (
+ <>
+ {list.map((conversation) => {
+ const isActive = selected?.id === conversation.id;
+ const previewTitle =
+ head(conversation.messageList)?.content ||
+ t("plugin.ai.conversation.untitled");
+ return (
+ <div
+ key={conversation.id}
+ data-conversation-id={conversation.id}
+ className={cn(
+ "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",
+ isActive && "bg-indigo-100 border-indigo-400"
+ )}
+ onClick={() => setSelected(conversation)}
+ >
+ {conversation.name ? (
+ <div className="text-sm flex-1 whitespace-pre-wrap wrap-break-word break-all">
+ {conversation.name}
+ </div>
+ ) : (
+ <div className="text-sm flex-1 truncate text-gray-500 italic">
+ {previewTitle}
+ </div>
+ )}
+ <div className="flex items-center gap-x-px">
+ <button
+ type="button"
+ className="flex items-center p-0.5 border border-transparent rounded-sm text-gray-500 hover:text-accent hover:bg-indigo-50 hover:border-accent cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ setRename(conversation);
+ }}
+ aria-label={t("plugin.ai.conversation.rename")}
+ >
+ <PencilIcon className="size-3" />
+ </button>
+ <button
+ type="button"
+ className="flex items-center p-0.5 border border-transparent rounded-sm text-gray-500 hover:text-accent hover:bg-indigo-50 hover:border-accent cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ setDeleteCandidate(conversation);
+ }}
+ aria-label={t("plugin.ai.conversation.delete")}
+ >
+ <TrashIcon className="size-3" />
+ </button>
+ </div>
+ </div>
+ );
+ })}
+
+ <Button
+ variant="outline"
+ size="sm"
+ className="sticky bottom-0 flex items-center justify-center gap-x-1"
+ onClick={() => events.emit("new-conversation", { input: "" })}
+ >
+ <PlusIcon className="size-4" />
+ <span className="pr-2">
+ {t("plugin.ai.conversation.new-conversation")}
+ </span>
+ </Button>
+ </>
+ ) : (
+ <Loader2 className="self-center mt-8 size-5 animate-spin" />
+ )}
+ </div>
+
+ {rename && (
+ <ConversationRenameDialog
+ conversation={rename}
+ onCancel={() => setRename(undefined)}
+ onUpdated={() => setRename(undefined)}
+ />
+ )}
+
+ <AlertDialog
+ open={!!deleteCandidate}
+ onOpenChange={(open) => !open && setDeleteCandidate(undefined)}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {t("plugin.ai.conversation.delete")}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("bbkit.confirm-button.sure-to-delete")}
+ </AlertDialogDescription>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ render={<Button variant="outline">{t("common.cancel")}</Button>}
+ />
+ <Button
+ variant="destructive"
+ onClick={() => void handleConfirmDelete()}
+ >
+ {t("common.delete")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/HistoryPanel/ConversationRenameDialog.tsx b/frontend/src/plugins/ai/react/HistoryPanel/ConversationRenameDialog.tsx
new file mode 100644
index 0000000000..88f8086156
--- /dev/null
+++ b/frontend/src/plugins/ai/react/HistoryPanel/ConversationRenameDialog.tsx
@@ -0,0 +1,100 @@
+import { head } from "lodash-es";
+import { Loader2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import { useConversationStore } from "../../store";
+import type { Conversation } from "../../types";
+
+type Props = {
+ readonly conversation: Conversation;
+ readonly onCancel: () => void;
+ readonly onUpdated: () => void;
+};
+
+/**
+ * React port of `plugins/ai/components/HistoryPanel/ConversationRenameDialog.vue`.
+ *
+ * Single-field rename modal. The name initializes to:
+ * 1. The current conversation name, or
+ * 2. The first message's content (often the user's seed prompt), or
+ * 3. The localized "Untitled conversation" placeholder.
+ *
+ * Mirrors the Vue version exactly. Auto-focuses the input on mount via
+ * a ref + rAF so the input is interactive immediately when the dialog
+ * portal mounts.
+ */
+export function ConversationRenameDialog({
+ conversation,
+ onCancel,
+ onUpdated,
+}: Props) {
+ const { t } = useTranslation();
+ const store = useConversationStore();
+
+ const [name, setName] = useState(
+ conversation.name ||
+ head(conversation.messageList)?.content ||
+ t("plugin.ai.conversation.untitled")
+ );
+ const [loading, setLoading] = useState(false);
+
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ useEffect(() => {
+ const raf = requestAnimationFrame(() => {
+ inputRef.current?.focus();
+ });
+ return () => cancelAnimationFrame(raf);
+ }, []);
+
+ const handleRename = async () => {
+ setLoading(true);
+ conversation.name = name;
+ await store.updateConversation(conversation);
+ onUpdated();
+ };
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onCancel()}>
+ <DialogContent className="w-[18rem] p-6">
+ <DialogTitle>{t("plugin.ai.conversation.rename")}</DialogTitle>
+ <div className="relative flex flex-col items-start gap-y-2 mt-3">
+ <div className="text-sm text-control">{t("common.name")}</div>
+ <div className="w-full">
+ <Input
+ ref={inputRef}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void handleRename();
+ }
+ }}
+ className="w-full"
+ />
+ </div>
+ <div className="w-full flex items-center justify-end gap-x-2 mt-4 pt-2 border-t">
+ <Button variant="outline" onClick={onCancel}>
+ {t("common.cancel")}
+ </Button>
+ <Button onClick={() => void handleRename()} disabled={loading}>
+ {t("common.update")}
+ </Button>
+ </div>
+ {loading && (
+ <div className="absolute inset-0 bg-background/50 flex items-center justify-center rounded-sm">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/HistoryPanel/HistoryPanel.tsx b/frontend/src/plugins/ai/react/HistoryPanel/HistoryPanel.tsx
new file mode 100644
index 0000000000..6a01ab2379
--- /dev/null
+++ b/frontend/src/plugins/ai/react/HistoryPanel/HistoryPanel.tsx
@@ -0,0 +1,47 @@
+import { useTranslation } from "react-i18next";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { ChatView } from "../ChatView/ChatView";
+import { useAIContext } from "../context";
+import { ConversationList } from "./ConversationList";
+
+/**
+ * React port of `plugins/ai/components/HistoryPanel/HistoryPanel.vue`.
+ *
+ * Side drawer with two columns: the conversation list on the left and
+ * the selected conversation rendered in `mode="VIEW"` on the right.
+ * The drawer is the only place wide enough to render the full history
+ * — `ChatPanel` mounts it once and toggles open via
+ * `showHistoryDialog` from the React AIContext.
+ */
+export function HistoryPanel() {
+ const { t } = useTranslation();
+ const { showHistoryDialog, setShowHistoryDialog, chat } = useAIContext();
+
+ return (
+ <Sheet
+ open={showHistoryDialog}
+ onOpenChange={(open) => setShowHistoryDialog(open)}
+ >
+ <SheetContent width="wide" className="w-[calc(100vw-8rem)] max-w-6xl p-0">
+ <SheetHeader className="px-4 py-3 border-b">
+ <SheetTitle>
+ {t("plugin.ai.conversation.history-conversations")}
+ </SheetTitle>
+ </SheetHeader>
+ <div className="flex h-full">
+ <aside className="hidden lg:flex lg:flex-col w-[14em] border-l border-b">
+ <ConversationList />
+ </aside>
+ <div className="flex-1 flex flex-col py-2 bg-gray-100 overflow-hidden">
+ <ChatView mode="VIEW" conversation={chat.selected} />
+ </div>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/PromptInput.tsx b/frontend/src/plugins/ai/react/PromptInput.tsx
new file mode 100644
index 0000000000..f247123cf3
--- /dev/null
+++ b/frontend/src/plugins/ai/react/PromptInput.tsx
@@ -0,0 +1,150 @@
+import { CornerDownLeft } from "lucide-react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import { keyboardShortcutStr } from "@/utils";
+import { useAIContext } from "./context";
+
+type Props = {
+ readonly disabled?: boolean;
+ readonly onEnter: (value: string) => void;
+};
+
+const LINE_HEIGHT_PX = 20;
+const MIN_ROWS = 1;
+const MAX_ROWS = 10;
+
+/**
+ * React port of `plugins/ai/components/PromptInput.vue`.
+ *
+ * Autosizing textarea (1-10 visible rows) bound to local state. Enter
+ * submits; Shift+Enter inserts a newline. The trailing button is a
+ * tooltipped ⏎ that submits when clicked.
+ *
+ * Naive UI's `NInput type="textarea" autosize` isn't available; we
+ * hand-roll the autosize by measuring `scrollHeight` after each value
+ * change and clamping to `[MIN_ROWS, MAX_ROWS] * lineHeight`. Adding a
+ * runtime dep (`react-textarea-autosize`) just for this surface isn't
+ * worth it — the hand-rolled version is ~10 lines and behaves
+ * identically for plain text input.
+ *
+ * Reacts to two external triggers from `AIContext`:
+ * - `pendingPreInput`: a one-shot seed value (e.g. `OpenAIButton`
+ * "Ask AI about this query"). Cleared after consumption.
+ * - `new-conversation` event: re-focuses the textarea so the user can
+ * immediately type into a freshly-created conversation.
+ */
+export function PromptInput({ disabled = false, onEnter }: Props) {
+ const { t } = useTranslation();
+ const { pendingPreInput, setPendingPreInput, events } = useAIContext();
+
+ const [value, setValue] = useState("");
+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);
+
+ // Focus on mount + on `new-conversation` so the user can start typing
+ // immediately.
+ useEffect(() => {
+ textareaRef.current?.focus();
+ }, []);
+ useEffect(() => {
+ const off = events.on("new-conversation", () => {
+ textareaRef.current?.focus();
+ });
+ return () => {
+ off();
+ };
+ }, [events]);
+
+ // Consume `pendingPreInput`: when the provider sets it, copy into
+ // local state and clear the trigger. rAF mirrors the Vue version's
+ // `flush: "post"` watch — defers to the next paint so any conversation
+ // creation that triggered the seed has landed first.
+ useEffect(() => {
+ if (!pendingPreInput) return;
+ const raf = requestAnimationFrame(() => {
+ setValue(pendingPreInput);
+ setPendingPreInput(undefined);
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [pendingPreInput, setPendingPreInput]);
+
+ // Autosize: after every value change, set height to scrollHeight,
+ // clamped to [MIN_ROWS, MAX_ROWS] lines.
+ useLayoutEffect(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ el.style.height = "auto";
+ const minHeight = MIN_ROWS * LINE_HEIGHT_PX;
+ const maxHeight = MAX_ROWS * LINE_HEIGHT_PX;
+ const next = Math.min(maxHeight, Math.max(minHeight, el.scrollHeight));
+ el.style.height = `${next}px`;
+ }, [value]);
+
+ const applyValue = (raw: string) => {
+ setValue("");
+ onEnter(raw);
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key !== "Enter") return;
+ if (e.shiftKey) return; // Shift+Enter → newline
+ e.preventDefault();
+ if (!value.trim()) return;
+ applyValue(value);
+ };
+
+ const handleSubmitClick = () => {
+ if (!value.trim()) return;
+ applyValue(value);
+ };
+
+ const tooltipContent = useMemo(
+ () => (
+ <div className="text-xs flex flex-col gap-1">
+ <p className="flex items-center gap-1">
+ <span>{t("plugin.ai.send")}</span>
+ <span>({keyboardShortcutStr("⏎")})</span>
+ </p>
+ <p className="flex items-center gap-1">
+ <span>{t("plugin.ai.new-line")}</span>
+ <span>({keyboardShortcutStr("shift+⏎")})</span>
+ </p>
+ </div>
+ ),
+ [t]
+ );
+
+ return (
+ <div className="relative w-full">
+ <textarea
+ ref={textareaRef}
+ value={value}
+ disabled={disabled}
+ placeholder={t("plugin.ai.text-to-sql-placeholder")}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ rows={MIN_ROWS}
+ className={cn(
+ "w-full resize-none rounded-xs border border-control-border bg-background pl-2 pr-9 py-1 text-sm",
+ "leading-5 text-main placeholder:text-control-placeholder",
+ "focus:outline-none focus:border-accent focus:ring-0",
+ "disabled:opacity-50 disabled:cursor-not-allowed"
+ )}
+ />
+ <Tooltip content={tooltipContent} side="top">
+ <Button
+ variant="ghost"
+ size="xs"
+ className="absolute right-1 bottom-1 h-6 px-1.5 text-accent"
+ disabled={!value || disabled}
+ onClick={handleSubmitClick}
+ aria-label={t("plugin.ai.send")}
+ >
+ <CornerDownLeft className="size-3.5" />
+ </Button>
+ </Tooltip>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/context.tsx b/frontend/src/plugins/ai/react/context.tsx
new file mode 100644
index 0000000000..07d4ac7d9f
--- /dev/null
+++ b/frontend/src/plugins/ai/react/context.tsx
@@ -0,0 +1,290 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import type { ReactNode } from "react";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDBSchemaV1Store,
+ useSettingV1Store,
+ useSQLEditorTabStore,
+} from "@/store";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
+import type { AISetting } from "@/types/proto-es/v1/setting_service_pb";
+import {
+ AISettingSchema,
+ Setting_SettingName,
+} from "@/types/proto-es/v1/setting_service_pb";
+import { wrapRefAsPromise } from "@/utils";
+import { aiContextEvents, useChatByTab } from "../logic";
+import { useConversationStore } from "../store";
+import type { AIContextEvents, Conversation } from "../types";
+
+/**
+ * React-shaped slice of the AI plugin's per-tab state. Mirrors the Vue
+ * `AIChatInfo` (refs) with plain values + an explicit setter so consumers
+ * don't have to know about Vue's reactivity.
+ */
+export type ReactAIChatInfo = {
+ list: Conversation[];
+ ready: boolean;
+ selected: Conversation | undefined;
+ setSelected: (next: Conversation | undefined) => void;
+};
+
+/**
+ * React-shaped AI plugin context. Replaces the Vue `AIContext` defined in
+ * `plugins/ai/types/context.ts` for components under `plugins/ai/react/`.
+ * Same fields, plain values, paired setters for mutable state.
+ */
+export type ReactAIContext = {
+ aiSetting: AISetting;
+ engine: Engine | undefined;
+ databaseMetadata: DatabaseMetadata | undefined;
+ schema: string | undefined;
+
+ showHistoryDialog: boolean;
+ setShowHistoryDialog: (next: boolean) => void;
+
+ chat: ReactAIChatInfo;
+
+ /**
+ * One-shot trigger written by the `send-chat` event handler — the
+ * downstream `ChatPanel` effect reads this and dispatches the actual
+ * AICompletion request, then clears it via `setPendingSendChat(undefined)`.
+ * Same pattern as the Vue `pendingSendChat` ref.
+ */
+ pendingSendChat: { content: string } | undefined;
+ setPendingSendChat: (next: { content: string } | undefined) => void;
+
+ /**
+ * One-shot trigger written by the `new-conversation` event handler when
+ * the host pre-fills a seed prompt (e.g. `OpenAIButton.tsx` "Ask AI
+ * about this query"). `PromptInput` reads + clears it on mount /
+ * pending-pre-input change.
+ */
+ pendingPreInput: string | undefined;
+ setPendingPreInput: (next: string | undefined) => void;
+
+ events: AIContextEvents;
+};
+
+const AIContextReactContext = createContext<ReactAIContext | null>(null);
+
+export function useAIContext(): ReactAIContext {
+ const ctx = useContext(AIContextReactContext);
+ if (!ctx) {
+ throw new Error(
+ "useAIContext (React) must be used inside <AIContextProvider>"
+ );
+ }
+ return ctx;
+}
+
+const EMPTY_AI_SETTING: AISetting = createProto(AISettingSchema, {});
+
+export function AIContextProvider({ children }: { children: ReactNode }) {
+ // ---- Vue-side state bridged via useVueState ----------------------------
+
+ const settingV1Store = useSettingV1Store();
+ // The original Vue ProvideAIContext fetched the AI setting on mount.
+ // Mirror that here. `getOrFetchSettingByName` is idempotent; firing it
+ // again on remount is cheap.
+ useEffect(() => {
+ void settingV1Store.getOrFetchSettingByName(
+ Setting_SettingName.AI,
+ /* silent */ true
+ );
+ }, [settingV1Store]);
+
+ const aiSetting = useVueState<AISetting>(() => {
+ const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);
+ if (setting?.value?.value?.case === "ai") {
+ return setting.value.value.value;
+ }
+ return EMPTY_AI_SETTING;
+ });
+
+ const { instance: instanceRef, database: databaseRef } =
+ useConnectionOfCurrentSQLEditorTab();
+
+ const engine = useVueState<Engine | undefined>(
+ () => instanceRef.value.engine
+ );
+
+ // Fetch database metadata on database change (mirrors Vue
+ // `useMetadata`'s `watchEffect` + cache read). `useDBSchemaV1Store`
+ // dedupes concurrent fetches, so firing this from the React effect
+ // doesn't race with another caller. We read the cache via
+ // `useVueState` so cache hydration triggers a re-render.
+ const databaseName = useVueState(() => databaseRef.value.name);
+ const dbSchemaStore = useDBSchemaV1Store();
+ useEffect(() => {
+ if (!databaseName) return;
+ void dbSchemaStore.getOrFetchDatabaseMetadata({ database: databaseName });
+ }, [databaseName, dbSchemaStore]);
+ const databaseMetadata = useVueState<DatabaseMetadata | undefined>(() =>
+ databaseName ? dbSchemaStore.getDatabaseMetadata(databaseName) : undefined
+ );
+
+ const tabStore = useSQLEditorTabStore();
+ const schema = useVueState<string | undefined>(
+ () => tabStore.currentTab?.connection.schema
+ );
+
+ // ---- Per-tab chat info -------------------------------------------------
+ //
+ // `useChatByTab()` returns a Vue `ComputedRef<AIChatInfo>` where the
+ // inner `AIChatInfo` itself holds Vue refs (`list`, `ready`, `selected`).
+ // We hold the ComputedRef across renders and read each inner ref via
+ // its own `useVueState` getter — that way React subscribes to the right
+ // dep granularity (chat list mutations don't churn `ready`, and so on).
+ const chatByTabRef = useChatByTab();
+
+ const chatList = useVueState<Conversation[]>(
+ () => chatByTabRef.value.list.value,
+ { deep: true }
+ );
+ const chatReady = useVueState<boolean>(() => chatByTabRef.value.ready.value);
+ const chatSelected = useVueState<Conversation | undefined>(
+ () => chatByTabRef.value.selected.value
+ );
+ const setChatSelected = useCallback(
+ (next: Conversation | undefined) => {
+ chatByTabRef.value.selected.value = next;
+ },
+ [chatByTabRef]
+ );
+ const chat = useMemo<ReactAIChatInfo>(
+ () => ({
+ list: chatList,
+ ready: chatReady,
+ selected: chatSelected,
+ setSelected: setChatSelected,
+ }),
+ [chatList, chatReady, chatSelected, setChatSelected]
+ );
+
+ // ---- React-side state --------------------------------------------------
+
+ const [showHistoryDialog, setShowHistoryDialog] = useState(false);
+ const [pendingSendChat, setPendingSendChat] = useState<
+ { content: string } | undefined
+ >(undefined);
+ const [pendingPreInput, setPendingPreInput] = useState<string | undefined>(
+ undefined
+ );
+
+ // Stable reference to `aiContextEvents` — singleton, but keep typed.
+ const events: AIContextEvents = aiContextEvents;
+
+ // ---- Event listeners (mirror ProvideAIContext.vue) ---------------------
+
+ const conversationStore = useConversationStore();
+
+ // We need access to the latest chat refs from inside the listeners.
+ // `chatByTabRef` is stable across renders (it's a ComputedRef captured
+ // by useMemo([]) inside `useChatByTab`), but `tab` is a live Pinia
+ // value we read via `tabStore.currentTab` at fire time.
+ useEffect(() => {
+ const offNewConversation = events.on(
+ "new-conversation",
+ async ({ input }) => {
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ // Wait until the per-tab chat fetch has resolved before deciding
+ // whether to reuse or create. Without this guard a brand-new tab
+ // sees `selected === undefined` and creates a duplicate empty
+ // conversation when one would have hydrated a beat later.
+ await wrapRefAsPromise(chatByTabRef.value.ready, /* expected */ true);
+ setShowHistoryDialog(false);
+
+ const sel = chatByTabRef.value.selected.value;
+ if (!sel || sel.messageList.length !== 0) {
+ // Reuse if the current chat is empty, otherwise create a fresh one.
+ const c = await conversationStore.createConversation({
+ name: "",
+ ...tab.connection,
+ });
+ chatByTabRef.value.selected.value = c;
+ }
+ if (input) {
+ // rAF mirrors the Vue version — gives `PromptInput`'s
+ // pending-pre-input effect a frame to land after the conversation
+ // creation settles. Without it the seed text can be dropped if
+ // the effect fires before `selected` updates.
+ requestAnimationFrame(() => {
+ setPendingPreInput(input);
+ });
+ }
+ }
+ );
+
+ const offSendChat = events.on("send-chat", async ({ content, newChat }) => {
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ await wrapRefAsPromise(chatByTabRef.value.ready, /* expected */ true);
+ if (newChat) {
+ setShowHistoryDialog(false);
+ const c = await conversationStore.createConversation({
+ name: "",
+ ...tab.connection,
+ });
+ chatByTabRef.value.selected.value = c;
+ }
+ requestAnimationFrame(() => {
+ setPendingSendChat({ content });
+ });
+ });
+
+ return () => {
+ offNewConversation();
+ offSendChat();
+ };
+ // `events`, `tabStore`, `chatByTabRef`, `conversationStore` are stable
+ // singletons / Pinia store references — fine to depend on them.
+ }, [events, tabStore, chatByTabRef, conversationStore]);
+
+ // ---- Memoized value bundle --------------------------------------------
+
+ const value = useMemo<ReactAIContext>(
+ () => ({
+ aiSetting,
+ engine,
+ databaseMetadata,
+ schema,
+ showHistoryDialog,
+ setShowHistoryDialog,
+ chat,
+ pendingSendChat,
+ setPendingSendChat,
+ pendingPreInput,
+ setPendingPreInput,
+ events,
+ }),
+ [
+ aiSetting,
+ engine,
+ databaseMetadata,
+ schema,
+ showHistoryDialog,
+ chat,
+ pendingSendChat,
+ pendingPreInput,
+ events,
+ ]
+ );
+
+ return (
+ <AIContextReactContext.Provider value={value}>
+ {children}
+ </AIContextReactContext.Provider>
+ );
+}
diff --git a/frontend/src/plugins/ai/react/index.ts b/frontend/src/plugins/ai/react/index.ts
new file mode 100644
index 0000000000..d8aa4ed383
--- /dev/null
+++ b/frontend/src/plugins/ai/react/index.ts
@@ -0,0 +1,6 @@
+// React-only barrel for the AI plugin. The plugin's root `index.ts`
+// keeps framework-agnostic re-exports (types) so the Vue tsconfig
+// doesn't have to traverse `.tsx` modules; React consumers import
+// from `@/plugins/ai/react` instead.
+export { AIChatToSQL } from "./AIChatToSQL";
+export { AIContextProvider, useAIContext } from "./context";
diff --git a/frontend/src/react/components/VueMount.test.tsx b/frontend/src/react/components/VueMount.test.tsx
deleted file mode 100644
index 2026ce61e6..0000000000
--- a/frontend/src/react/components/VueMount.test.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { describe, expect, test, vi } from "vitest";
-import { defineComponent, h, nextTick } from "vue";
-
-(
- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
-).IS_REACT_ACT_ENVIRONMENT = true;
-
-vi.mock("@/store", () => ({
- pinia: { install: vi.fn() },
-}));
-vi.mock("@/plugins/i18n", () => ({
- default: { install: vi.fn() },
-}));
-vi.mock("@/plugins/naive-ui", () => ({
- default: { install: vi.fn() },
-}));
-
-import { VueMount } from "./VueMount";
-
-const renderIntoContainer = (element: React.ReactElement) => {
- const container = document.createElement("div");
- document.body.appendChild(container);
- const root = createRoot(container);
- return {
- container,
- render: () =>
- act(() => {
- root.render(element);
- }),
- rerender: (next: React.ReactElement) =>
- act(() => {
- root.render(next);
- }),
- unmount: () => {
- act(() => {
- root.unmount();
- });
- container.remove();
- },
- };
-};
-
-const Greet = defineComponent({
- props: { name: { type: String, default: "world" } },
- setup(props) {
- return () => h("span", { class: "greet" }, `hello ${props.name}`);
- },
-});
-
-describe("VueMount", () => {
- test("mounts a Vue component into the React container", () => {
- const { container, render, unmount } = renderIntoContainer(
- <VueMount component={Greet} props={{ name: "Stage 21" }} />
- );
- render();
- const span = container.querySelector("span.greet");
- expect(span?.textContent).toBe("hello Stage 21");
- unmount();
- });
-
- test("propagates prop changes without remounting", async () => {
- const { container, render, rerender, unmount } = renderIntoContainer(
- <VueMount component={Greet} props={{ name: "first" }} />
- );
- render();
- const before = container.querySelector("span.greet");
- expect(before?.textContent).toBe("hello first");
-
- rerender(<VueMount component={Greet} props={{ name: "second" }} />);
- await nextTick();
- const after = container.querySelector("span.greet");
- expect(after?.textContent).toBe("hello second");
- expect(after).toBe(before); // same DOM node — Vue updated in place.
- unmount();
- });
-
- test("unmounts the Vue app when React unmounts", () => {
- const teardown = vi.fn();
- const Probe = defineComponent({
- setup() {
- return () => h("span", { class: "probe" }, "alive");
- },
- beforeUnmount: teardown,
- });
-
- const { container, render, unmount } = renderIntoContainer(
- <VueMount component={Probe} />
- );
- render();
- expect(container.querySelector("span.probe")?.textContent).toBe("alive");
-
- unmount();
- expect(teardown).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/frontend/src/react/components/VueMount.tsx b/frontend/src/react/components/VueMount.tsx
deleted file mode 100644
index 5a9a0dce50..0000000000
--- a/frontend/src/react/components/VueMount.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { useEffect, useRef } from "react";
-import type { Component } from "vue";
-import { createApp, h, reactive } from "vue";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { cn } from "@/react/lib/utils";
-import { pinia } from "@/store";
-
-interface VueMountProps<P extends Record<string, unknown>> {
- /**
- * Vue component to mount. Component identity must be stable across renders;
- * passing a fresh inline definition will tear down and re-create the inner
- * Vue app every render. Module-level imports satisfy this naturally.
- */
- component: Component;
- /**
- * Props forwarded to the Vue component. Treated reactively — assigning new
- * keys/values updates the running Vue app in place via Vue's reactivity,
- * no remount. The object reference itself doesn't need to be stable; only
- * the keys/values are diffed.
- */
- props?: P;
- className?: string;
-}
-
-/**
- * Reverse mount bridge: hosts a Vue 3 component subtree inside a React tree.
- * Mirrors `ReactPageMount.vue`'s lifecycle in reverse — used by the SQL
- * Editor host shells (post-Stage-21) to keep the still-Vue AI plugin
- * (`AIChatToSQL`, `ChatPanel`, etc.) running without porting it yet.
- *
- * The inner Vue app installs the same singleton plugins as the outer Vue
- * app (Pinia, i18n, NaiveUI) so Pinia stores, translations, and Naive UI
- * services are shared — no "two sources of truth" surprises.
- */
-export function VueMount<P extends Record<string, unknown>>({
- component,
- props,
- className,
-}: VueMountProps<P>) {
- const containerRef = useRef<HTMLDivElement | null>(null);
- const reactivePropsRef = useRef<Record<string, unknown> | null>(null);
-
- useEffect(() => {
- const el = containerRef.current;
- if (!el) return;
-
- const reactiveProps = reactive<Record<string, unknown>>({
- ...(props ?? {}),
- });
- reactivePropsRef.current = reactiveProps;
-
- const app = createApp({
- render: () => h(component, reactiveProps),
- });
- app.use(pinia);
- app.use(i18n);
- app.use(NaiveUI);
- app.mount(el);
-
- return () => {
- reactivePropsRef.current = null;
- app.unmount();
- };
- // Re-create the Vue app only when component identity changes; prop
- // updates flow through the reactive proxy in the next effect.
- }, [component]);
-
- // Sync prop changes into the live Vue app without remounting.
- useEffect(() => {
- const target = reactivePropsRef.current;
- if (!target) return;
- const next = props ?? {};
- // Add/overwrite keys.
- for (const [k, v] of Object.entries(next)) {
- target[k] = v;
- }
- // Drop keys removed from the new props snapshot.
- for (const k of Object.keys(target)) {
- if (!(k in next)) {
- delete target[k];
- }
- }
- }, [props]);
-
- return <div ref={containerRef} className={cn(className)} />;
-}
diff --git a/frontend/src/react/components/sql-editor/Panels/Panels.tsx b/frontend/src/react/components/sql-editor/Panels/Panels.tsx
index e02130a84c..3f84c3246e 100644
--- a/frontend/src/react/components/sql-editor/Panels/Panels.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/Panels.tsx
@@ -7,8 +7,8 @@ import {
Separator as PanelResizeHandle,
} from "react-resizable-panels";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import { AIChatToSQLBridgeHost } from "@/plugins/ai";
import { aiContextEvents } from "@/plugins/ai/logic";
+import { AIChatToSQL, AIContextProvider } from "@/plugins/ai/react";
import { resizeHandleClass } from "@/react/components/SchemaEditorLite/resize";
import { DatabaseChooser } from "@/react/components/sql-editor/DatabaseChooser";
import { DiagramPanel } from "@/react/components/sql-editor/DiagramPanel";
@@ -25,7 +25,6 @@ import { TerminalPanel } from "@/react/components/sql-editor/TerminalPanel/Termi
import { TriggersPanel } from "@/react/components/sql-editor/TriggersPanel";
import { ViewsPanel } from "@/react/components/sql-editor/ViewsPanel";
import { Alert } from "@/react/components/ui/alert";
-import { VueMount } from "@/react/components/VueMount";
import { useVueState } from "@/react/hooks/useVueState";
import {
useConnectionOfCurrentSQLEditorTab,
@@ -230,10 +229,9 @@ export function Panels() {
>
<div className="h-full overflow-hidden flex flex-col">
<Suspense fallback={<AIPaneFallback />}>
- <VueMount
- component={AIChatToSQLBridgeHost}
- className="h-full"
- />
+ <AIContextProvider>
+ <AIChatToSQL />
+ </AIContextProvider>
</Suspense>
</div>
</Panel>
diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
index 4a25dac1fc..a41cebbaad 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
@@ -54,12 +54,10 @@ import { sqlEditorEvents } from "@/views/sql-editor/events";
* content into `pendingInsertAtCaret`; the React `<SQLEditor>` reads
* that ref and inserts at the cursor.
*
- * Vue stragglers (`Quickstart`, `IAMRemindModal`) mount via
- * `<VueMount>` so the Stage 22 ports can stay deferred without
- * blocking this stage. The Vue Router route entry lives in
- * `router/sqlEditor.ts` as a tiny inline `defineComponent` whose
- * sole job is to mount this React tree via `<ReactPageMount
- * page="SQLEditorHomePage">` — no per-route `.vue` file remains.
+ * The Vue Router route entry lives in `router/sqlEditor.ts` as a
+ * tiny inline `defineComponent` whose sole job is to mount this
+ * React tree via `<ReactPageMount page="SQLEditorHomePage">` — no
+ * per-route `.vue` file remains.
*/
export function SQLEditorHomePage() {
const { t } = useTranslation();
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
index 03f4232939..f13bcea561 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
@@ -5,10 +5,9 @@ import {
Group as PanelGroup,
Separator as PanelResizeHandle,
} from "react-resizable-panels";
-import { AIChatToSQLBridgeHost } from "@/plugins/ai";
+import { AIChatToSQL, AIContextProvider } from "@/plugins/ai/react";
import { resizeHandleClass } from "@/react/components/SchemaEditorLite/resize";
import { ResultPanel } from "@/react/components/sql-editor/ResultPanel/ResultPanel";
-import { VueMount } from "@/react/components/VueMount";
import { useVueState } from "@/react/hooks/useVueState";
import {
useConnectionOfCurrentSQLEditorTab,
@@ -37,8 +36,10 @@ const AIPaneFallback = () => (
* the editor from being squeezed into an arbitrary top pane when
* the result pane wouldn't render anyway).
* 2. Inner horizontal split — `<EditorMain>` / `<AIChatToSQL>`.
- * The AI side pane mounts via `<VueMount>` so the Stage 22
- * AI-plugin port can stay deferred without blocking this stage.
+ * The AI side pane is now a React tree (Stage 22 port). `<AIContextProvider>`
+ * wraps the React `<AIChatToSQL>` to re-establish the per-tab AI
+ * state — the Vue `<VueMount component={AIChatToSQLBridgeHost}>`
+ * bridge is gone.
*
* State source: `useSQLEditorTabStore` for tab + disconnect state,
* `useConnectionOfCurrentSQLEditorTab` for the current instance,
@@ -103,10 +104,9 @@ export function StandardPanel() {
>
<div className="h-full overflow-hidden flex flex-col">
<Suspense fallback={<AIPaneFallback />}>
- <VueMount
- component={AIChatToSQLBridgeHost}
- className="h-full"
- />
+ <AIContextProvider>
+ <AIChatToSQL />
+ </AIContextProvider>
</Suspense>
</div>
</Panel>
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index f3462f9980..c7b680cc04 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -1658,14 +1658,32 @@
"ai": {
"actions": {
"explain-code": "Explain code",
- "find-problems": "Find problems"
+ "find-problems": "Find problems",
+ "insert-at-caret": "Insert at caret"
},
"ai-assistant": "AI Assistant",
+ "conversation": {
+ "delete": "Delete conversation",
+ "history-conversations": "History conversations",
+ "new-conversation": "Start new conversation",
+ "no-message": "No message in this conversation",
+ "rename": "Rename conversation",
+ "select-or-create": "Select or {create} a conversation to start.",
+ "tips": {
+ "no-more": "no more",
+ "suggest-prompt": "Suggesting prompts..."
+ },
+ "untitled": "Untitled conversation",
+ "view-history-conversations": "View history conversations"
+ },
+ "new-line": "New line",
"not-configured": {
"contact-admin-to-configure": "Please contact your org administrator.",
"go-to-configure": "Go to configure",
"self": "AI Assistant is not configured."
- }
+ },
+ "send": "Send",
+ "text-to-sql-placeholder": "Use natural language and Bytebase will convert it into SQL"
}
},
"policy": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index a25cbfdda3..c20be87f08 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -1650,14 +1650,32 @@
"ai": {
"actions": {
"explain-code": "Explicar el código",
- "find-problems": "encontrar problemas"
+ "find-problems": "encontrar problemas",
+ "insert-at-caret": "Insertar en el cursor"
},
"ai-assistant": "Asistente de IA",
+ "conversation": {
+ "delete": "Eliminar conversación",
+ "history-conversations": "Historial de conversaciones",
+ "new-conversation": "Comenzar nueva conversación",
+ "no-message": "No hay mensajes en esta conversación",
+ "rename": "Renombrar conversación",
+ "select-or-create": "Seleccione o {crear} una conversación para comenzar.",
+ "tips": {
+ "no-more": "No más",
+ "suggest-prompt": "Sugiriendo promts..."
+ },
+ "untitled": "Conversación sin título",
+ "view-history-conversations": "Ver historial de conversaciones"
+ },
+ "new-line": "Nueva linea",
"not-configured": {
"contact-admin-to-configure": "Comuníquese con el administrador de su organización.",
"go-to-configure": "Ir a configurar",
"self": "El Asistente AI no está configurado."
- }
+ },
+ "send": "Enviar",
+ "text-to-sql-placeholder": "Utilice lenguaje natural y Bytebase lo convertirá en SQL"
}
},
"policy": {
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 8dab59832d..40f4b78f24 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -1650,14 +1650,32 @@
"ai": {
"actions": {
"explain-code": "コードの説明",
- "find-problems": "問題を見つける"
+ "find-problems": "問題を見つける",
+ "insert-at-caret": "キャレットに挿入"
},
"ai-assistant": "AI アシスタント",
+ "conversation": {
+ "delete": "セッションの削除",
+ "history-conversations": "歴史対話",
+ "new-conversation": "新しい会話を開始する",
+ "no-message": "この会話にはメッセージはありません",
+ "rename": "セッション名の変更",
+ "select-or-create": "開始するセッションを選択または {create} します。",
+ "tips": {
+ "no-more": "何も残っていない",
+ "suggest-prompt": "プロンプト単語を生成..."
+ },
+ "untitled": "名前のないセッション",
+ "view-history-conversations": "過去の会話を表示する"
+ },
+ "new-line": "改行",
"not-configured": {
"contact-admin-to-configure": "組織の管理者に問い合わせてください。",
"go-to-configure": "設定に移動",
"self": "AI アシスタントが設定されていません。"
- }
+ },
+ "send": "送信",
+ "text-to-sql-placeholder": "ここに自然言語を入力すると、Bytebase はすぐにそれを SQL ステートメントに変換します。"
}
},
"policy": {
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 860ff260ea..9d773594e5 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -1650,14 +1650,32 @@
"ai": {
"actions": {
"explain-code": "Giải thích mã",
- "find-problems": "Tìm vấn đề"
+ "find-problems": "Tìm vấn đề",
+ "insert-at-caret": "Chèn vào con trỏ"
},
"ai-assistant": "Trợ lý AI",
+ "conversation": {
+ "delete": "Xóa cuộc trò chuyện",
+ "history-conversations": "Cuộc trò chuyện lịch sử",
+ "new-conversation": "Bắt đầu cuộc trò chuyện mới",
+ "no-message": "Không có tin nhắn trong cuộc trò chuyện này",
+ "rename": "Đổi tên cuộc trò chuyện",
+ "select-or-create": "Chọn hoặc {create} một cuộc trò chuyện để bắt đầu.",
+ "tips": {
+ "no-more": "không còn nữa",
+ "suggest-prompt": "Gợi ý nhắc nhở..."
+ },
+ "untitled": "Cuộc trò chuyện không có tiêu đề",
+ "view-history-conversations": "Xem cuộc trò chuyện lịch sử"
+ },
+ "new-line": "Dòng mới",
"not-configured": {
"contact-admin-to-configure": "Vui lòng liên hệ với quản trị viên tổ chức của bạn.",
"go-to-configure": "Đi tới cấu hình",
"self": "Trợ lý AI chưa được định cấu hình."
- }
+ },
+ "send": "Gửi",
+ "text-to-sql-placeholder": "Sử dụng ngôn ngữ tự nhiên và Bytebase sẽ chuyển đổi nó thành SQL"
}
},
"policy": {
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index e21443c604..26aa9417b2 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -1650,14 +1650,32 @@
"ai": {
"actions": {
"explain-code": "解释代码",
- "find-problems": "找出问题"
+ "find-problems": "找出问题",
+ "insert-at-caret": "在光标处插入"
},
"ai-assistant": "AI 助手",
+ "conversation": {
+ "delete": "删除会话",
+ "history-conversations": "历史对话",
+ "new-conversation": "开启新对话",
+ "no-message": "无消息",
+ "rename": "修改会话名称",
+ "select-or-create": "选择或{create}一个会话以开始。",
+ "tips": {
+ "no-more": "没有了",
+ "suggest-prompt": "生成提示词..."
+ },
+ "untitled": "未命名会话",
+ "view-history-conversations": "查看历史对话"
+ },
+ "new-line": "换行",
"not-configured": {
"contact-admin-to-configure": "请联系您的组织管理员。",
"go-to-configure": "前往配置",
"self": "AI 助手尚未配置。"
- }
+ },
+ "send": "发送",
+ "text-to-sql-placeholder": "在此输入自然语言后,Bytebase 会将其转换成 SQL 语句"
}
},
"policy": {
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
index a3e267ef2a..f3bd8fd72a 100644
--- a/frontend/tsconfig.app.json
+++ b/frontend/tsconfig.app.json
@@ -12,6 +12,8 @@
"src/**/*.test.ts",
"src/**/*.test.tsx",
"src/react/**/*.tsx",
+ "src/plugins/ai/react/**/*.ts",
+ "src/plugins/ai/react/**/*.tsx",
"src/react/components/MarkdownEditor/index.ts",
"src/react/components/task-run-log/index.ts",
"src/react/components/monaco/index.ts",
diff --git a/frontend/tsconfig.react.json b/frontend/tsconfig.react.json
index 9c32d2851b..9d1c0734b3 100644
--- a/frontend/tsconfig.react.json
+++ b/frontend/tsconfig.react.json
@@ -16,5 +16,11 @@
"@/*": ["./src/*"]
}
},
- "include": ["src/react/**/*.ts", "src/react/**/*.tsx", "src/react/react-env.d.ts"]
+ "include": [
+ "src/react/**/*.ts",
+ "src/react/**/*.tsx",
+ "src/react/react-env.d.ts",
+ "src/plugins/ai/react/**/*.ts",
+ "src/plugins/ai/react/**/*.tsx"
+ ]
}
diff --git a/frontend/tsconfig.vitest.json b/frontend/tsconfig.vitest.json
index ff689d6bb9..fe0cd8e922 100644
--- a/frontend/tsconfig.vitest.json
+++ b/frontend/tsconfig.vitest.json
@@ -9,6 +9,8 @@
],
"exclude": [
"src/react/**/*.tsx",
+ "src/plugins/ai/react/**/*.ts",
+ "src/plugins/ai/react/**/*.tsx",
"src/react/components/MarkdownEditor/index.ts",
"src/react/components/task-run-log/index.ts",
"src/react/components/monaco/index.ts",
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index cf4d38489a..2db9b675ec 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -30,7 +30,17 @@ export default defineConfig({
name: "react-tsx-transform",
enforce: "pre",
async transform(code, id) {
- if (!/\/src\/react\/.+\.tsx$/.test(id)) return undefined;
+ // Both the main React tree (`src/react/...`) and the AI plugin's
+ // co-located React subtree (`src/plugins/ai/react/...`) compile
+ // with React's automatic JSX runtime. The latter has to be
+ // listed explicitly — otherwise its `.tsx` files fall through
+ // to the `vueJsx()` plugin below and get compiled with Vue's
+ // JSX transform, which produces Vue VNodes and dies at runtime
+ // with "Cannot add property _ctx, object is not extensible"
+ // when Vue tries to attach `_ctx` to a frozen value.
+ if (!/\/(src\/react|src\/plugins\/ai\/react)\/.+\.tsx$/.test(id)) {
+ return undefined;
+ }
const result = await esbuildTransform(code, {
loader: "tsx",
jsx: "automatic",
@@ -45,7 +55,7 @@ export default defineConfig({
vue(),
vueJsx({
include: /\.tsx$/,
- exclude: /src\/react\//,
+ exclude: /src\/(react|plugins\/ai\/react)\//,
}),
// https://github.com/intlify/vite-plugin-vue-i18n
VueI18nPlugin({