diff --git a/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/WebAIUtils.java b/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/WebAIUtils.java index 0b46fb5d7b2..55fa31e8c54 100644 --- a/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/WebAIUtils.java +++ b/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/WebAIUtils.java @@ -285,6 +285,12 @@ public static WebAISendChatMessageInfo submitPrompt( + "(schema, table and column names) to the AI assistant. Send the message again and allow it when asked.") .formatted(conversation.getDataSource() == null ? "" : conversation.getDataSource().getName())); } + if (StackblazeAI.isEnabled() + && StackblazeAI.billingConnection(webSession, conversation.getDataSource()) == null) { + // Refuse here, not in the background job: an error event that beats this + // mutation's reply leaves the chat spinner on (the reply sets it back on). + throw new DBWebException(StackblazeAI.NO_CONNECTION_MESSAGE); + } StackblazeAI.ensureDefaultProfile(); AIChatMessage promptMessage; AIChatMessage result; diff --git a/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/stackblaze/StackblazeAI.java b/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/stackblaze/StackblazeAI.java index 3c4a466ddd1..9be52f4e63b 100644 --- a/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/stackblaze/StackblazeAI.java +++ b/server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/stackblaze/StackblazeAI.java @@ -8,6 +8,8 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.cloudbeaver.DBWebException; +import io.cloudbeaver.WebSessionGlobalProjectImpl; +import io.cloudbeaver.model.WebConnectionInfo; import io.cloudbeaver.model.session.WebSession; import io.cloudbeaver.service.ai.WebAIFeatureProvider; import io.cloudbeaver.utils.ServletAppUtils; @@ -26,6 +28,8 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; +import java.util.HashSet; +import java.util.Set; /** * Stackblaze mode: on when {@code STACKBLAZE_LLM_URL} and {@code STACKBLAZE_LLM_SECRET} @@ -47,6 +51,11 @@ public final class StackblazeAI { public static final String PROFILE_ID = "stackblaze"; public static final String PROFILE_NAME = "Stackblaze"; + /** Shown when a turn has no connection to charge. */ + public static final String NO_CONNECTION_MESSAGE = + "Pick a database in the connection list above. AI usage is charged to the workspace that owns it."; + private static final String DUCKDB_NAME_SUFFIX = " \u00b7 SQL (DuckDB)"; + private static final int DEFAULT_CONTEXT_WINDOW = 128_000; private static final long CATALOG_RETRY_MS = 60_000L; @@ -120,8 +129,9 @@ public static AIConfigurationProfile turnProfile( @Nullable DBPDataSourceContainer dataSource, @NotNull String sessionId ) throws DBWebException { + dataSource = billingConnection(webSession, dataSource); if (dataSource == null) { - throw new DBWebException("Open the AI chat from a database connection."); + throw new DBWebException(NO_CONNECTION_MESSAGE); } String secret = secret(); if (secret == null) { @@ -147,6 +157,47 @@ public static AIConfigurationProfile turnProfile( return profile; } + /** + * The connection whose workspace pays for a turn: the chat's own connection, + * or, for a chat with "No connection", any shared connection the user can see + * when they all belong to one Stackblaze project ({@code //}). + * Null when there is nothing to charge or the choice would be a guess. + */ + @Nullable + public static DBPDataSourceContainer billingConnection( + @NotNull WebSession webSession, + @Nullable DBPDataSourceContainer chosen + ) { + if (chosen != null) { + return chosen; + } + WebSessionGlobalProjectImpl shared = webSession.getGlobalProject(); + if (shared == null) { + return null; + } + DBPDataSourceContainer first = null; + Set projects = new HashSet<>(); + for (WebConnectionInfo info : shared.getConnections()) { + DBPDataSourceContainer container = info.getDataSourceContainer(); + if (!shared.isDataSourceAccessible(container)) { + continue; + } + String name = container.getName() == null ? "" : container.getName(); + if (name.endsWith(DUCKDB_NAME_SUFFIX)) { + name = name.substring(0, name.length() - DUCKDB_NAME_SUFFIX.length()); + } + String[] parts = name.split("/", -1); + if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) { + continue; + } + projects.add(parts[0]); + if (first == null) { + first = container; + } + } + return projects.size() == 1 ? first : null; + } + @Nullable static String model(@Nullable String token) { String fromEnv = env("STACKBLAZE_LLM_MODEL"); diff --git a/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextManager.tsx b/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextManager.tsx index 59872be4980..f05407f125b 100644 --- a/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextManager.tsx +++ b/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextManager.tsx @@ -6,7 +6,7 @@ * you may not use this file except in compliance with the License. */ -import type { ReactElement } from 'react'; +import { useEffect, type ReactElement } from 'react'; import { observer } from 'mobx-react-lite'; import { isNotNullDefined } from '@dbeaver/js-helpers'; @@ -63,14 +63,38 @@ export const AIChatContextManager = observer(function AIChatContextManage const value = aiChatContextService.currentContext?.connectionKey.connectionId ?? NO_CONTEXT_ID; + // Stackblaze: with no SQL editor open the chat starts on "No connection" and its + // tools have no database to read. Use the user's only connected connection (or + // their only connection), unless they picked "No connection" themselves. + const connected = connections.filter(c => c.connected); + let onlyConnection = connected.length === 1 ? connected[0] : undefined; + + if (connected.length === 0 && connections.length === 1) { + onlyConnection = connections[0]; + } + + const canAutoPick = !aiChatContextService.currentContext && !aiChatContextService.isNoContextChosen; + const autoPickId = canAutoPick ? onlyConnection?.id : undefined; + + useEffect(() => { + if (!autoPickId) { + return; + } + const connection = connectionInfoResource.data.find(c => c?.id === autoPickId); + + if (connection) { + aiChatContextService.setContext({ connectionKey: createConnectionParam(connection) }); + } + }, [autoPickId, aiChatContextService, connectionInfoResource]); + function changeContext(contextId: string): void { if (contextId === NO_CONTEXT_ID) { - aiChatContextService.setContext(null); + aiChatContextService.chooseContext(null); } else { const connection = connectionInfoResource.data.find(c => c?.id === contextId); if (connection) { - aiChatContextService.setContext({ connectionKey: createConnectionParam(connection) }); + aiChatContextService.chooseContext({ connectionKey: createConnectionParam(connection) }); } } } diff --git a/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextService.ts b/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextService.ts index 344d2b9719a..f548b598129 100644 --- a/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextService.ts +++ b/webapp/packages/plugin-ai-chat/src/AIChat/AIChatContext/AIChatContextService.ts @@ -37,6 +37,8 @@ export class AIChatContextService extends Bootstrap { } private context: IAIChatContextInfo | null = null; + /** Stackblaze: the user picked "No connection" themselves; don't pick one for them. */ + private noContextChosen = false; private reactionDisposer: IReactionDisposer | null; constructor( @@ -50,6 +52,7 @@ export class AIChatContextService extends Bootstrap { this.reactionDisposer = null; userInfoResource.onUserChange.addHandler(() => { + this.noContextChosen = false; this.setContext(null); }); @@ -63,11 +66,22 @@ export class AIChatContextService extends Bootstrap { } }); - makeObservable(this, { + makeObservable(this, { context: observable, + noContextChosen: observable, }); } + get isNoContextChosen(): boolean { + return this.noContextChosen; + } + + /** A choice made in the chat's connection list ("No connection" is null). */ + chooseContext(context: IAIChatContextInfo | null): void { + this.noContextChosen = context === null; + this.setContext(context); + } + setContext(context: IAIChatContextInfo | null): void { this.context = context; this.onContextChange.execute(this.context);