From 151e41ef1abeebebcea37f2cc2e6251e115a87fa Mon Sep 17 00:00:00 2001 From: PylotLight <7006124+PylotLight@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:14:46 +1100 Subject: [PATCH 1/2] feat: add configurable AI MongoDB query generation --- .gitignore | 1 + docs/architecture.md | 2 + docs/database-client.md | 10 + src/main/ai-query.js | 356 +++++++++++++ src/main/ipc.ts | 22 + src/preload/index.ts | 16 + src/renderer/src/App.tsx | 10 + src/renderer/src/components/ai-query.css | 504 ++++++++++++++++++ src/renderer/src/views/AiQuerySettings.jsx | 280 ++++++++++ src/renderer/src/views/Settings.tsx | 30 +- .../src/views/workspace/DatabaseWorkspace.tsx | 49 ++ .../components/MongoAiQueryDialog.jsx | 325 +++++++++++ src/shared/ai-query.js | 165 ++++++ src/shared/ai-query.test.js | 104 ++++ src/shared/database.ts | 30 ++ 15 files changed, 1897 insertions(+), 7 deletions(-) create mode 100644 src/main/ai-query.js create mode 100644 src/renderer/src/components/ai-query.css create mode 100644 src/renderer/src/views/AiQuerySettings.jsx create mode 100644 src/renderer/src/views/workspace/components/MongoAiQueryDialog.jsx create mode 100644 src/shared/ai-query.js create mode 100644 src/shared/ai-query.test.js diff --git a/.gitignore b/.gitignore index f6e0d55..c47bac6 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json # caches .eslintcache .cache +__pycache__/ *.tsbuildinfo # IntelliJ based IDEs diff --git a/docs/architecture.md b/docs/architecture.md index 9b27103..f7b88a2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -15,6 +15,7 @@ React renderer → preload bridge → Electron IPC → connection manager → No - `src/main/alembic-graph.js` reads Alembic revision files without importing project Python code, then compares the revision graph with live `alembic_version` rows. - `src/main/alembic-model-compare.js` invokes the selected project Python interpreter for SQLAlchemy/Alembic autogenerate comparison. Its helper returns operation summaries and offline-rendered SQL for review; it does not apply upgrades or execute the preview. - `src/main/saved-connections.ts` stores profile metadata in the app's user-data directory and protects passwords with Electron `safeStorage` backed by the operating system credential store. +- `src/main/ai-query.js` keeps the OpenAI-compatible provider key encrypted with Electron `safeStorage`, sends user-approved prompts from the main process, and validates generated MongoDB filters and pipelines before returning them. - `src/shared/` contains database types, validation helpers and app configuration. ## Query path @@ -33,3 +34,4 @@ SQLite connections point to absolute local file paths. `DatabaseSync` stays in t 2. The main process validates database inputs before starting driver work. 3. Driver work and result normalization stay off the Electron main thread. 4. Renderer capabilities are limited to methods exposed through `src/preload/index.ts`. +5. AI provider credentials and HTTP requests stay in the main process. AI generation is opt-in; each request requires a renderer consent check, sends field/index metadata but no document values, and returns a query draft that is never executed automatically. diff --git a/docs/database-client.md b/docs/database-client.md index 860dceb..dda00ab 100644 --- a/docs/database-client.md +++ b/docs/database-client.md @@ -113,6 +113,16 @@ For the included demo collection, enter `orders` as the collection and use: The MongoDB driver returns matching documents, including each document's `_id` field. Insert, update, delete, index and collection operations are available through the collection toolbar; updates use MongoDB update operators such as `$set` or `$inc`. +#### Generate a query with AI + +Choose **AI query** beside the MongoDB editor controls. The first time, open **Settings → AI query**, enter an OpenAI-compatible chat-completions endpoint and model, and add an API key if the provider requires one. AI query generation is off until you enable it. Rowfish stores the key using Electron `safeStorage` and sends provider requests from the Electron main process; it is never exposed to the renderer. HTTPS is required for remote endpoints; plain HTTP is accepted only for loopback providers such as `localhost`. + +Before every generation request, Rowfish shows what will be sent and asks for your consent. The request includes your prompt, database and collection names, field paths, and index definitions. It does not include document contents, sampled field values, database credentials, or the MongoDB URI. The prompt and schema metadata go directly to your configured provider, which may apply its own retention, privacy, and billing policies. + +The separate **Save & test** action in Settings also sends a short provider-check request when you choose it. + +The returned filter or aggregation pipeline is parsed and checked against Rowfish's blocked operators before it can be inserted. **Use** only places the draft in the editor; it does not run automatically. Review the generated query and run it yourself when ready. + ## Results, search and cancellation Results arrive in batches and are shown in a virtualized grid. Choose a row limit from `500`, `1,000`, `5,000` or `10,000`; the default is `1,000`. The renderer retains no more than 10,000 rows and the normalized result payload is capped at **16 MB**. Individual cells are truncated at 8,192 characters, and the grid displays at most 100 columns. diff --git a/src/main/ai-query.js b/src/main/ai-query.js new file mode 100644 index 0000000..9f9a34d --- /dev/null +++ b/src/main/ai-query.js @@ -0,0 +1,356 @@ +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, writeFile, unlink } from "node:fs/promises"; +import path from "node:path"; +import { app, safeStorage } from "electron"; +import { + buildMongoQueryMessages, + DEFAULT_AI_QUERY_SETTINGS, + isLocalAiEndpoint, + normalizeAiEndpoint, + parseGeneratedMongoQuery, +} from "../shared/ai-query.js"; +import { isPlainRecord, validateText } from "./database/validation"; +import { getOwnedConnection } from "./database"; +import { getMongoCollectionDetails } from "./database/mongo"; +import { assertAllowedSender } from "./database/worker-bridge"; + +const FILE_NAME = "ai-query-settings.json"; +const MAX_PROMPT_LENGTH = 3_000; +const REQUEST_TIMEOUT_MS = 45_000; +const MAX_PROVIDER_RESPONSE_BYTES = 256 * 1_024; + +function validatePrompt(value) { + if (typeof value !== "string") throw new Error("Prompt must be text."); + const prompt = value.trim(); + if ( + !prompt || + prompt.length > MAX_PROMPT_LENGTH || + /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(prompt) + ) { + throw new Error("Prompt is required and must be under 3,000 characters."); + } + return prompt; +} + +function storagePath() { + return path.join(app.getPath("userData"), FILE_NAME); +} + +async function hasSecureStorage() { + if (!(await safeStorage.isAsyncEncryptionAvailable())) return false; + if (process.platform !== "linux") return true; + return ["gnome_libsecret", "kwallet", "kwallet5", "kwallet6"].includes( + safeStorage.getSelectedStorageBackend(), + ); +} + +async function readStoredSettings() { + try { + const value = JSON.parse(await readFile(storagePath(), "utf8")); + if ( + value?.version !== 1 || + typeof value.endpoint !== "string" || + typeof value.model !== "string" || + typeof value.enabled !== "boolean" || + (value.encryptedApiKey !== null && + typeof value.encryptedApiKey !== "string") + ) { + throw new Error("Stored AI query settings have an unsupported format."); + } + return value; + } catch (error) { + if (error?.code === "ENOENT") { + return { + version: 1, + ...DEFAULT_AI_QUERY_SETTINGS, + encryptedApiKey: null, + }; + } + throw error instanceof Error + ? error + : new Error("Could not read AI query settings."); + } +} + +async function writeStoredSettings(value) { + const file = storagePath(); + const directory = path.dirname(file); + await mkdir(directory, { recursive: true, mode: 0o700 }); + const temporaryFile = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(temporaryFile, JSON.stringify(value, null, 2), { + encoding: "utf8", + mode: 0o600, + }); + await rename(temporaryFile, file); + } catch { + await unlink(temporaryFile).catch(() => undefined); + throw new Error("Could not save AI query settings on this device."); + } +} + +function publicSettings(value) { + const endpoint = normalizeAiEndpoint(value.endpoint); + const model = validateText(value.model, "Model", 160, true); + const hasApiKey = Boolean(value.encryptedApiKey); + const needsKey = !isLocalAiEndpoint(endpoint); + return { + endpoint, + model, + enabled: value.enabled, + hasApiKey, + configured: value.enabled && (!needsKey || hasApiKey), + }; +} + +export async function getAiQuerySettings(event) { + assertAllowedSender(event.sender); + return publicSettings(await readStoredSettings()); +} + +export async function saveAiQuerySettings(event, rawValue) { + assertAllowedSender(event.sender); + if (!isPlainRecord(rawValue)) throw new Error("Invalid AI query settings."); + const current = await readStoredSettings(); + const endpoint = normalizeAiEndpoint(rawValue.endpoint); + const model = validateText(rawValue.model, "Model", 160, true); + if (typeof rawValue.enabled !== "boolean") + throw new Error("Choose whether AI query generation is enabled."); + if ( + rawValue.clearApiKey !== undefined && + typeof rawValue.clearApiKey !== "boolean" + ) + throw new Error("API key removal selection is invalid."); + let encryptedApiKey = rawValue.clearApiKey ? null : current.encryptedApiKey; + if (rawValue.apiKey !== undefined) { + if ( + typeof rawValue.apiKey !== "string" || + rawValue.apiKey.length > 4_096 || + /[\0\r\n]/.test(rawValue.apiKey) + ) { + throw new Error("API key is invalid or too long."); + } + if (rawValue.apiKey) { + if (!(await hasSecureStorage())) { + throw new Error( + "Secure credential storage is unavailable. Rowfish did not save the API key.", + ); + } + try { + encryptedApiKey = ( + await safeStorage.encryptStringAsync(rawValue.apiKey) + ).toString("base64"); + } catch { + throw new Error( + "Rowfish could not encrypt the API key with the operating-system credential store.", + ); + } + } + } + const next = { + version: 1, + endpoint, + model, + enabled: rawValue.enabled, + encryptedApiKey, + }; + await writeStoredSettings(next); + return publicSettings(next); +} + +async function readApiKey(value) { + if (!value.encryptedApiKey) return ""; + if (!(await hasSecureStorage())) { + throw new Error( + "The operating-system credential store is unavailable, so Rowfish cannot read the saved AI API key.", + ); + } + try { + const result = await safeStorage.decryptStringAsync( + Buffer.from(value.encryptedApiKey, "base64"), + ); + return result.result; + } catch { + throw new Error( + "Rowfish could not decrypt the saved AI API key. Remove it and enter it again in Settings.", + ); + } +} + +function providerError(status) { + if (status === 401 || status === 403) + return "The AI provider rejected the API key. Check the key in Settings."; + if (status === 404) + return "The AI endpoint or model was not found. Check the endpoint and model in Settings."; + if (status === 429) + return "The AI provider is rate-limiting this request. Try again later."; + return `The AI provider returned HTTP ${status}. Check its endpoint and try again.`; +} + +async function readProviderPayload(response) { + const contentLength = response.headers.get("content-length"); + if ( + contentLength && + Number.isFinite(Number(contentLength)) && + Number(contentLength) > MAX_PROVIDER_RESPONSE_BYTES + ) { + throw new Error("The AI provider response exceeds the 256 KB limit."); + } + const reader = response.body?.getReader(); + if (!reader) + throw new Error("The AI provider returned an unreadable response."); + const chunks = []; + let totalBytes = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + totalBytes += value.byteLength; + if (totalBytes > MAX_PROVIDER_RESPONSE_BYTES) { + await reader.cancel().catch(() => undefined); + throw new Error("The AI provider response exceeds the 256 KB limit."); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const bytes = Buffer.allocUnsafe(totalBytes); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + return JSON.parse(bytes.toString("utf8")); + } catch { + throw new Error("The AI provider returned an unreadable response."); + } +} + +async function requestCompletion(settings, messages, maxTokens = 2_048) { + const endpoint = normalizeAiEndpoint(settings.endpoint); + const apiKey = await readApiKey(settings); + if (!apiKey && !isLocalAiEndpoint(endpoint)) { + throw new Error( + "Add an API key for this remote provider in Settings before generating a query.", + ); + } + let response; + try { + response = await fetch(`${endpoint}/chat/completions`, { + method: "POST", + redirect: "error", + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + headers: { + "content-type": "application/json", + ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}), + }, + body: JSON.stringify({ + model: settings.model, + messages, + max_tokens: maxTokens, + }), + }); + } catch (error) { + if (error?.name === "TimeoutError" || error?.name === "AbortError") { + throw new Error("The AI provider did not respond within 45 seconds."); + } + throw new Error( + "Could not reach the configured AI provider. Check the endpoint and your network connection.", + ); + } + if (!response.ok) throw new Error(providerError(response.status)); + let payload; + try { + payload = await readProviderPayload(response); + } catch (error) { + if (error?.message === "The AI provider response exceeds the 256 KB limit.") + throw error; + throw new Error("The AI provider returned an unreadable response."); + } + const content = payload?.choices?.[0]?.message?.content; + if (typeof content !== "string" || !content.trim()) { + throw new Error( + "The AI provider returned no query content. Check that the selected model supports chat completions.", + ); + } + return content; +} + +export async function testAiQueryProvider(event) { + assertAllowedSender(event.sender); + const settings = await readStoredSettings(); + normalizeAiEndpoint(settings.endpoint); + validateText(settings.model, "Model", 160, true); + const content = await requestCompletion( + settings, + [ + { role: "system", content: "Reply with the single word OK." }, + { role: "user", content: "Test the provider connection." }, + ], + 8, + ); + if (!content.trim()) + throw new Error("The AI provider returned an empty test response."); + return { message: "The provider responded successfully." }; +} + +export async function generateMongoQueryWithAi(event, rawValue) { + assertAllowedSender(event.sender); + if (!isPlainRecord(rawValue)) throw new Error("Invalid AI query request."); + const connectionId = validateText( + rawValue.connectionId, + "Connection id", + 80, + true, + ); + const database = validateText( + rawValue.database, + "MongoDB database", + 128, + true, + ); + const collection = validateText( + rawValue.collection, + "MongoDB collection", + 128, + true, + ); + const prompt = validatePrompt(rawValue.prompt); + const mode = rawValue.mode; + if (mode !== "find" && mode !== "aggregate") + throw new Error("Choose Find or Aggregate mode."); + + const settings = await readStoredSettings(); + if (!settings.enabled) + throw new Error( + "AI query generation is disabled. Enable it in Settings first.", + ); + const connection = getOwnedConnection(event, connectionId); + if (connection.config.kind !== "mongodb") + throw new Error("Choose a MongoDB connection to generate a MongoDB query."); + const details = await getMongoCollectionDetails( + event, + connectionId, + database, + collection, + ); + const fields = (details.fields ?? []) + .filter((field) => typeof field === "string" && field.length <= 240) + .slice(0, 200); + const indexes = (details.indexes ?? []).slice(0, 40).map((index) => ({ + keys: typeof index.keys === "string" ? index.keys.slice(0, 2_000) : "{}", + unique: Boolean(index.unique), + })); + const messages = buildMongoQueryMessages({ + prompt, + mode, + database, + collection, + fields, + indexes, + }); + const content = await requestCompletion(settings, messages); + return parseGeneratedMongoQuery(content, mode); +} diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 703aebb..caf702b 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -1,5 +1,11 @@ import { app, dialog, ipcMain } from "electron"; import { getMainWindow } from "./window"; +import { + generateMongoQueryWithAi, + getAiQuerySettings, + saveAiQuerySettings, + testAiQueryProvider, +} from "./ai-query.js"; import { cancelDatabaseQuery, connectDatabase, @@ -42,6 +48,22 @@ export function registerIpc(): void { "Application controls are available only to the Rowfish window.", ); }; + ipcMain.handle("ai-query:get-settings", (event) => { + assertAppSender(event); + return getAiQuerySettings(event); + }); + ipcMain.handle("ai-query:save-settings", (event, input: unknown) => { + assertAppSender(event); + return saveAiQuerySettings(event, input); + }); + ipcMain.handle("ai-query:test-provider", (event) => { + assertAppSender(event); + return testAiQueryProvider(event); + }); + ipcMain.handle("ai-query:generate-mongo", (event, request: unknown) => { + assertAppSender(event); + return generateMongoQueryWithAi(event, request); + }); ipcMain.handle("app:quit", (event) => { assertAppSender(event); app.quit(); diff --git a/src/preload/index.ts b/src/preload/index.ts index 1382781..c49d6df 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,5 +1,7 @@ import { contextBridge, ipcRenderer } from "electron"; import type { + AiQuerySettings, + AiQuerySettingsInput, DatabaseBrowserDatabase, DatabaseBrowserTable, DatabaseConnectionInput, @@ -11,6 +13,8 @@ import type { DatabaseQueryRequest, MongoBrowserCollection, MongoBrowserDatabase, + MongoAiQueryRequest, + MongoAiQueryResult, MongoMutationRequest, MongoMutationResult, PostgresServerInfo, @@ -35,6 +39,18 @@ const api = { choosePythonInterpreter: (): Promise => ipcRenderer.invoke("app:choose-python-interpreter"), }, + aiQuery: { + getSettings: (): Promise => + ipcRenderer.invoke("ai-query:get-settings"), + saveSettings: (input: AiQuerySettingsInput): Promise => + ipcRenderer.invoke("ai-query:save-settings", input), + testProvider: (): Promise<{ message: string }> => + ipcRenderer.invoke("ai-query:test-provider"), + generateMongoQuery: ( + request: MongoAiQueryRequest, + ): Promise => + ipcRenderer.invoke("ai-query:generate-mongo", request), + }, database: { connect: ( input: DatabaseConnectionInput, diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 8b3d2cc..fe0595a 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -11,9 +11,12 @@ import { } from "./lib/ui-preferences"; export default function App(): React.JSX.Element { + type SettingsSection = "appearance" | "editor" | "ai"; const [search, setSearch] = useState(""); const [prefs, setPrefs] = useState(loadUiPreferences); const [settingsOpen, setSettingsOpen] = useState(false); + const [settingsSection, setSettingsSection] = + useState("appearance"); const [saveError, setSaveError] = useState(false); const triggerRef = useRef(null); useEffect(() => { @@ -26,6 +29,10 @@ export default function App(): React.JSX.Element { setSettingsOpen(false); requestAnimationFrame(() => triggerRef.current?.focus()); }; + const openSettings = (section?: SettingsSection) => { + if (section) setSettingsSection(section); + setSettingsOpen(true); + }; useEffect(() => { if (settingsOpen) document.querySelector(".settings-back")?.focus(); @@ -106,12 +113,15 @@ export default function App(): React.JSX.Element { search={search} preferences={prefs} sidebarActions={actions} + onOpenSettings={openSettings} settingsView={ settingsOpen ? ( ) : undefined } diff --git a/src/renderer/src/components/ai-query.css b/src/renderer/src/components/ai-query.css new file mode 100644 index 0000000..c22c005 --- /dev/null +++ b/src/renderer/src/components/ai-query.css @@ -0,0 +1,504 @@ +.ai-settings-heading { + display: flex; + align-items: flex-start; + gap: 12px; +} +.ai-settings-heading .settings-description { + margin-bottom: 0; +} +.ai-feature-icon { + display: inline-grid; + width: 34px; + height: 34px; + flex: 0 0 34px; + place-items: center; + border: 1px solid color-mix(in srgb, var(--mint) 32%, var(--border)); + border-radius: 11px; + background: color-mix(in srgb, var(--mint) 11%, transparent); + color: var(--mint); +} +.ai-privacy-note { + display: flex; + align-items: flex-start; + gap: 10px; + margin: 20px 0 7px; + padding: 12px 13px; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--surface-subtle, rgba(255, 255, 255, 0.04)); + color: var(--muted); +} +.ai-privacy-note > svg { + flex: 0 0 auto; + margin-top: 2px; + color: var(--mint); +} +.ai-privacy-note p { + margin: 0; + font-size: 11px; + line-height: 1.55; +} +.ai-enable-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 17px 0; + border-top: 1px solid var(--border); + border-bottom: 1px solid var(--border); +} +.ai-enable-row strong, +.ai-enable-row small { + display: block; +} +.ai-enable-row strong { + font-size: 12px; + font-weight: 650; +} +.ai-enable-row small, +.ai-settings-label small { + margin-top: 4px; + color: var(--muted); + font-size: 10px; + line-height: 1.45; +} +.ai-enable-row input, +.ai-consent-row input { + accent-color: var(--mint); +} +.ai-settings-fields { + display: grid; + gap: 15px; + padding: 18px 0; +} +.ai-settings-label { + display: grid; + gap: 6px; + color: var(--text); + font-size: 11px; + font-weight: 650; +} +.ai-settings-label input { + width: 100%; + min-width: 0; + padding: 10px 11px; + border: 1px solid var(--border); + border-radius: 9px; + outline: none; + background: var(--surface-subtle, rgba(255, 255, 255, 0.045)); + color: var(--text); + font: inherit; + font-weight: 450; +} +.ai-settings-label input:focus, +.ai-query-dialog textarea:focus { + border-color: var(--mint); + box-shadow: 0 0 0 2px var(--mint-dim); +} +.ai-settings-label small { + font-weight: 400; +} +.ai-optional { + color: var(--muted); + font-size: 10px; + font-weight: 400; +} +.ai-settings-status { + display: flex; + align-items: center; + gap: 8px; + color: var(--muted); + font-size: 11px; +} +.ai-status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #8b9098; +} +.ai-status-dot.ready { + background: var(--mint); + box-shadow: 0 0 8px color-mix(in srgb, var(--mint) 60%, transparent); +} +.ai-settings-message { + display: flex; + align-items: center; + gap: 6px; + margin: 11px 0 0; + font-size: 11px; + line-height: 1.45; +} +.ai-settings-message.error { + color: #ef8e91; +} +.ai-settings-message.success { + color: var(--mint); +} +.ai-settings-actions, +.ai-dialog-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 8px; +} +.ai-settings-actions { + margin-top: 18px; + padding-top: 15px; + border-top: 1px solid var(--border); +} +.ai-primary-button, +.ai-secondary-button, +.ai-danger-button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + min-height: 34px; + padding: 8px 12px; + border: 1px solid var(--border); + border-radius: 9px; + background: var(--surface-subtle, rgba(255, 255, 255, 0.05)); + color: var(--text); + font: inherit; + font-size: 11px; + font-weight: 600; + cursor: pointer; +} +.ai-primary-button { + border-color: color-mix(in srgb, var(--mint) 48%, var(--border)); + background: color-mix(in srgb, var(--mint) 17%, transparent); + color: var(--mint); +} +.ai-danger-button { + color: #ef8e91; +} +.ai-primary-button:hover:not(:disabled), +.ai-secondary-button:hover:not(:disabled) { + background: color-mix(in srgb, var(--mint) 22%, transparent); +} +.ai-danger-button:hover:not(:disabled) { + background: rgba(239, 142, 145, 0.1); +} +.ai-primary-button:disabled, +.ai-secondary-button:disabled, +.ai-danger-button:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.ai-spinner { + animation: ai-spin 1s linear infinite; +} +@keyframes ai-spin { + to { + transform: rotate(360deg); + } +} + +.ai-dialog-scrim { + position: fixed; + z-index: 1200; + inset: 0; + display: grid; + place-items: center; + padding: 24px; + background: rgba(5, 8, 12, 0.5); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); +} +.ai-query-dialog { + display: flex; + flex-direction: column; + width: min(680px, 100%); + max-height: min(790px, calc(100vh - 48px)); + overflow: hidden; + border: 1px solid var(--border); + border-radius: 19px; + background: var(--surface-raised, rgba(20, 25, 31, 0.96)); + box-shadow: + 0 28px 100px rgba(0, 0, 0, 0.45), + inset 0 1px rgba(255, 255, 255, 0.06); + color: var(--text); +} +.ai-query-dialog-header { + display: flex; + align-items: center; + gap: 11px; + padding: 17px 20px; + border-bottom: 1px solid var(--border); +} +.ai-query-dialog-header h2 { + margin: 0; + font-size: 15px; + letter-spacing: -0.02em; +} +.ai-query-dialog-header p { + margin: 4px 0 0; + color: var(--muted); + font-size: 10px; + overflow-wrap: anywhere; +} +.ai-dialog-close { + display: grid; + width: 32px; + height: 32px; + margin-left: auto; + place-items: center; + border: 1px solid transparent; + border-radius: 8px; + background: transparent; + color: var(--muted); + cursor: pointer; +} +.ai-dialog-close:hover { + border-color: var(--border); + background: rgba(255, 255, 255, 0.06); + color: var(--text); +} +.ai-dialog-body, +.ai-query-preview { + overflow: auto; + padding: 19px 20px 20px; +} +.ai-mode-label, +.ai-prompt-label { + display: grid; + gap: 8px; + font-size: 11px; + font-weight: 650; +} +.ai-mode-choice { + display: flex; + width: fit-content; + padding: 3px; + gap: 3px; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface-subtle, rgba(255, 255, 255, 0.035)); +} +.ai-mode-choice button { + padding: 7px 10px; + border: 0; + border-radius: 7px; + background: transparent; + color: var(--muted); + font: inherit; + font-size: 10px; + cursor: pointer; +} +.ai-mode-choice button.selected { + background: color-mix(in srgb, var(--mint) 18%, transparent); + color: var(--mint); +} +.ai-prompt-label { + margin-top: 16px; +} +.ai-query-dialog textarea { + width: 100%; + min-height: 86px; + max-height: 180px; + resize: vertical; + margin-top: 8px; + padding: 11px 12px; + border: 1px solid var(--border); + border-radius: 10px; + outline: none; + background: var(--surface-subtle, rgba(255, 255, 255, 0.04)); + color: var(--text); + font: inherit; + font-size: 12px; + line-height: 1.5; +} +.ai-prompt-count { + margin-top: 4px; + color: var(--muted); + font-size: 9px; + text-align: right; +} +.ai-data-disclosure { + margin-top: 14px; + padding: 11px 12px; + border: 1px solid var(--border); + border-radius: 11px; + background: rgba(255, 255, 255, 0.025); +} +.ai-disclosure-title { + display: flex; + align-items: center; + gap: 7px; + color: var(--text); + font-size: 10px; + font-weight: 650; + overflow-wrap: anywhere; +} +.ai-key-glyph { + display: inline-block; + width: 8px; + height: 8px; + flex: 0 0 8px; + border-radius: 50%; + background: var(--mint); + box-shadow: 0 0 0 3px var(--mint-dim); +} +.ai-data-disclosure > p { + margin: 7px 0 0; + color: var(--muted); + font-size: 10px; + line-height: 1.5; +} +.ai-consent-row { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 10px; + padding-top: 9px; + border-top: 1px solid var(--border); + color: var(--text); + font-size: 10px; + line-height: 1.45; + cursor: pointer; +} +.ai-consent-row input { + margin: 1px 0 0; + flex: 0 0 auto; +} +.ai-dialog-actions { + margin-top: 18px; + padding-top: 13px; + border-top: 1px solid var(--border); +} +.ai-dialog-loading { + display: flex; + align-items: center; + gap: 10px; + min-height: 160px; + padding: 24px; + color: var(--muted); + font-size: 12px; +} +.ai-not-configured { + padding: 8px 0 3px; +} +.ai-not-configured .ai-feature-icon { + margin-bottom: 11px; +} +.ai-not-configured h3 { + margin: 0; + font-size: 14px; +} +.ai-not-configured p { + max-width: 470px; + margin: 8px 0 0; + color: var(--muted); + font-size: 11px; + line-height: 1.55; +} +.ai-preview-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.ai-preview-eyebrow { + color: var(--mint); + font-size: 9px; + font-weight: 750; + letter-spacing: 0.1em; +} +.ai-preview-heading h3 { + margin: 4px 0 0; + font-size: 14px; +} +.ai-preview-check { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 5px 8px; + border: 1px solid color-mix(in srgb, var(--mint) 32%, var(--border)); + border-radius: 99px; + color: var(--mint); + font-size: 9px; +} +.ai-preview-explanation { + margin: 14px 0 9px; + color: var(--muted); + font-size: 11px; + line-height: 1.5; +} +.ai-query-code { + max-height: 410px; + overflow: auto; + margin: 12px 0 0; + padding: 14px; + border: 1px solid var(--border); + border-radius: 11px; + background: rgba(0, 0, 0, 0.15); + color: var(--text); + font: + 11px/1.55 ui-monospace, + SFMono-Regular, + Menlo, + monospace; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.ai-preview-warning { + display: flex; + align-items: flex-start; + gap: 7px; + margin: 11px 0 0; + color: #dcbf78; + font-size: 10px; + line-height: 1.45; +} +.ai-preview-warning svg { + flex: 0 0 auto; +} + +@media (max-width: 640px) { + .ai-dialog-scrim { + padding: 10px; + } + .ai-query-dialog { + max-height: calc(100vh - 20px); + border-radius: 15px; + } + .ai-query-dialog-header { + padding: 14px; + } + .ai-dialog-body, + .ai-query-preview { + padding: 15px; + } + .ai-settings-actions { + justify-content: flex-start; + } + .ai-settings-actions > button { + flex: 1 1 auto; + } +} + +.db-ai-query-button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 31px; + padding: 6px 9px; + border: 1px solid color-mix(in srgb, var(--mint) 35%, var(--border)); + border-radius: 8px; + background: color-mix(in srgb, var(--mint) 9%, transparent); + color: var(--mint); + font: inherit; + font-size: 10px; + font-weight: 650; + white-space: nowrap; + cursor: pointer; +} +.db-ai-query-button:hover:not(:disabled) { + background: color-mix(in srgb, var(--mint) 17%, transparent); +} +.db-ai-query-button:disabled { + opacity: 0.5; + cursor: not-allowed; +} diff --git a/src/renderer/src/views/AiQuerySettings.jsx b/src/renderer/src/views/AiQuerySettings.jsx new file mode 100644 index 0000000..b9138b8 --- /dev/null +++ b/src/renderer/src/views/AiQuerySettings.jsx @@ -0,0 +1,280 @@ +import { useEffect, useState } from "react"; +import { Check, KeyRound, LoaderCircle, Sparkles, Trash2 } from "lucide-react"; +import "../components/ai-query.css"; + +const DEFAULT_SETTINGS = { + endpoint: "https://api.openai.com/v1", + model: "gpt-4.1-mini", + enabled: false, + hasApiKey: false, + configured: false, +}; + +export default function AiQuerySettings() { + const [settings, setSettings] = useState(DEFAULT_SETTINGS); + const [apiKey, setApiKey] = useState(""); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(""); + const [error, setError] = useState(""); + const [notice, setNotice] = useState(""); + + useEffect(() => { + let active = true; + window.api.aiQuery + .getSettings() + .then((value) => { + if (active) setSettings(value); + }) + .catch((reason) => { + if (active) + setError( + reason instanceof Error + ? reason.message + : "Could not load AI settings.", + ); + }) + .finally(() => { + if (active) setLoading(false); + }); + return () => { + active = false; + }; + }, []); + + const save = async (shouldTest = false) => { + setBusy(shouldTest ? "test" : "save"); + setError(""); + setNotice(""); + try { + const saved = await window.api.aiQuery.saveSettings({ + endpoint: settings.endpoint, + model: settings.model, + enabled: settings.enabled, + apiKey, + }); + setSettings(saved); + setApiKey(""); + if (shouldTest) { + const result = await window.api.aiQuery.testProvider(); + setNotice(result.message); + } else { + setNotice("AI query settings saved on this device."); + } + } catch (reason) { + setError( + reason instanceof Error + ? reason.message + : "Could not save AI settings.", + ); + } finally { + setBusy(""); + } + }; + + const removeKey = async () => { + setBusy("remove"); + setError(""); + setNotice(""); + try { + const saved = await window.api.aiQuery.saveSettings({ + endpoint: settings.endpoint, + model: settings.model, + enabled: settings.enabled, + clearApiKey: true, + }); + setSettings(saved); + setApiKey(""); + setNotice("Saved API key removed."); + } catch (reason) { + setError( + reason instanceof Error + ? reason.message + : "Could not remove the saved API key.", + ); + } finally { + setBusy(""); + } + }; + + if (loading) { + return ( +
+

AI query generation

+

Loading provider settings…

+
+ ); + } + + return ( +
+
+ +
+

AI query generation

+

+ Connect an OpenAI-compatible model to draft MongoDB filters and + aggregation pipelines. +

+
+
+ +
+
+ + + +
+ + + +
+ +
+
+ + {error && ( +

+ {error} +

+ )} + {notice && ( +

+ {notice} +

+ )} + +
+ + + {settings.hasApiKey && ( + + )} +
+
+ ); +} diff --git a/src/renderer/src/views/Settings.tsx b/src/renderer/src/views/Settings.tsx index 3afa16e..00d25b5 100644 --- a/src/renderer/src/views/Settings.tsx +++ b/src/renderer/src/views/Settings.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import AiQuerySettings from "./AiQuerySettings"; import { ACCENTS, DEFAULT_UI_PREFERENCES, @@ -7,19 +8,25 @@ import { } from "../lib/ui-preferences"; import "../components/settings.css"; +type Section = "appearance" | "editor" | "ai"; type Props = { prefs: UiPreferences; onChange: (prefs: UiPreferences) => void; onBack: () => void; + initialSection?: Section; + onSectionChange?: (section: Section) => void; }; -type Section = "appearance" | "editor"; export default function Settings({ prefs, onChange, onBack, + initialSection, + onSectionChange, }: Props): React.JSX.Element { - const [section, setSection] = useState
("appearance"); + const [section, setSection] = useState
( + initialSection ?? "appearance", + ); const set = (patch: Partial) => onChange({ ...prefs, ...patch }); const radio = ( @@ -95,18 +102,25 @@ export default function Settings({
- ) : ( + ) : section === "editor" ? (

Editor

@@ -414,6 +428,8 @@ export default function Settings({

+ ) : ( + )} diff --git a/src/renderer/src/views/workspace/DatabaseWorkspace.tsx b/src/renderer/src/views/workspace/DatabaseWorkspace.tsx index 62db376..73cb129 100644 --- a/src/renderer/src/views/workspace/DatabaseWorkspace.tsx +++ b/src/renderer/src/views/workspace/DatabaseWorkspace.tsx @@ -12,6 +12,7 @@ import { CircleHelp, List, Braces, + Sparkles, } from "lucide-react"; import type { ReactNode } from "react"; import "../../components/query-connection.css"; @@ -47,6 +48,7 @@ import MongoCollectionBar from "./components/MongoCollectionBar"; import MongoOperationDialog, { type MongoOperationFields, } from "./components/MongoOperationDialog"; +import MongoAiQueryDialog from "./components/MongoAiQueryDialog"; import QueryConnectionDialog from "./components/QueryConnectionDialog"; import ResultsTable from "./components/ResultsTable"; import SaveQueryDialog from "./components/SaveQueryDialog"; @@ -102,6 +104,7 @@ import type { DatabaseRow, MongoBrowserCollection, MongoBrowserDatabase, + MongoAiQueryResult, MongoMutationRequest, SavedConnectionProfile, } from "../../../../shared/database"; @@ -153,13 +156,16 @@ export default function DatabaseWorkspace({ preferences, sidebarActions, settingsView, + onOpenSettings, }: { search: string; preferences: UiPreferences; sidebarActions: ReactNode; settingsView?: ReactNode; + onOpenSettings: (section?: "appearance" | "editor" | "ai") => void; }): React.JSX.Element { const [showConnect, setShowConnect] = useState(false); + const [showMongoAiGenerator, setShowMongoAiGenerator] = useState(false); const [showQueryConnection, setShowQueryConnection] = useState(false); const queryConnectionTabId = useRef(null); const [queryConnectionBusy, setQueryConnectionBusy] = useState(false); @@ -2226,6 +2232,18 @@ export default function DatabaseWorkspace({ /> ))} + {activeTab?.kind === "mongodb" && + activeConnection?.kind === "mongodb" && ( + + )}