The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Gemini Enterprise Agent Platform: FE changes (#79558)
applebyfb3f08713df1
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.tsindex 9ae32a02f84..8b167e200ed 100644--- a/frontend/src/metabase-types/api/metabot.ts+++ b/frontend/src/metabase-types/api/metabot.ts@@ -196,6 +196,7 @@ export type MetabotProvider =| "anthropic"| "azure"| "bedrock"+ | "google"| "mistral"| "moonshot"| "openai"@@ -214,10 +215,15 @@ export interface AzureCredentials {"base-url"?: string | null;}-/** One permissive map mirroring the backend's request schema: Bedrock sends AWS key- * material, Azure sends an API key and base URL. */+export interface GoogleCredentials {+ "service-account-key"?: string | null;+ "oauth-access-token"?: string | null;+ "project-id"?: string | null;+ location?: string | null;+}+export interface MetabotCredentials- extends BedrockCredentials, AzureCredentials {}+ extends BedrockCredentials, AzureCredentials, GoogleCredentials {}export interface MetabotSettingsResponse {value: string | null;diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 4914baa28ef..fcf998582e4 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -542,6 +542,10 @@ interface SettingsManagerSettings {"llm-moonshot-api-key"?: string | null;"llm-azure-api-key"?: string | null;"llm-azure-api-base-url"?: string | null;+ "llm-google-service-account-key"?: string | null;+ "llm-google-oauth-access-token"?: string | null;+ "llm-google-project-id"?: string | null;+ "llm-google-location"?: string | null;"llm-bedrock-access-key-id"?: string | null;"llm-bedrock-secret-access-key"?: string | null;"llm-bedrock-region"?: string | null;diff --git a/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx b/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsxindex aab7f58e559..f9bb12684d5 100644--- a/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/AIProviderSettingsSection.unit.spec.tsx@@ -20,6 +20,7 @@ import { Route } from "metabase/router";import { defer } from "metabase/utils/promise";import type {BedrockCredentials,+ GoogleCredentials,MetabotCredentials,MetabotProvider,MetabotSettingsResponse,@@ -74,6 +75,11 @@ const DEFAULT_RESPONSES: Record<MetabotProvider, MetabotSettingsResponse> = {value: "azure/anthropic/claude-sonnet-4-5",models: [],},+ google: {+ // Google has no model dropdown. Model IDs are free text, validated at connect time.+ value: "google/google/gemini-3.5-flash",+ models: [],+ },bedrock: {value: "bedrock/anthropic.claude-haiku-4-5",models: [@@ -134,11 +140,18 @@ type MetabotSettingsApiResponse =| MetabotSettingsResponse| (() => Promise<MetabotSettingsResponse>);+type GoogleSettingKey =+ | "llm-google-service-account-key"+ | "llm-google-oauth-access-token"+ | "llm-google-project-id"+ | "llm-google-location";+type MetabotSettingKey =| "llm-metabot-provider"| "llm-anthropic-api-key"| "llm-azure-api-key"| "llm-azure-api-base-url"+ | GoogleSettingKey| "llm-mistral-api-key"| "llm-moonshot-api-key"| "llm-openai-api-key"@@ -190,6 +203,11 @@ type SetupOptions = {deferPurchaseCloudAddOnResponse?: boolean;removeCloudAddOnResponse?: number | { status: number; body: unknown };apiKeyValues?: Partial<Record<MetabotProvider, string | null>>;+ googleProjectIdValue?: string | null;+ googleServiceAccountValue?: string | null;+ googleOauthTokenValue?: string | null;+ googleLocationValue?: string | null;+ googleEnvSettings?: Partial<Record<GoogleSettingKey, string>>;pauseUpdateResponse?: boolean;deferMetabotSettingsUpdateResponse?: boolean;settingUpdateResponse?: number | { status: number; body?: unknown };@@ -200,6 +218,53 @@ type SetupOptions = {onClose?: jest.Mock;};+type GoogleSettingValues = Pick<+ SetupOptions,+ | "googleProjectIdValue"+ | "googleServiceAccountValue"+ | "googleOauthTokenValue"+ | "googleLocationValue"+ | "googleEnvSettings"+>;++function createGoogleSettingDefinitions({+ googleProjectIdValue = "my-project",+ googleServiceAccountValue = null,+ googleOauthTokenValue = null,+ googleLocationValue = null,+ googleEnvSettings = {},+}: GoogleSettingValues): Record<GoogleSettingKey, MetabotSettingDefinition> {+ const createGoogleSetting = (key: GoogleSettingKey, value: string | null) => {+ const envName = googleEnvSettings[key];+ return createMockSettingDefinition({+ key,+ value: value ?? undefined,+ is_env_setting: Boolean(envName),+ env_name: envName,+ });+ };++ return {+ "llm-google-service-account-key": createGoogleSetting(+ "llm-google-service-account-key",+ googleServiceAccountValue,+ ),+ "llm-google-oauth-access-token": createGoogleSetting(+ "llm-google-oauth-access-token",+ googleOauthTokenValue,+ ),+ // The project ID is saved with an OAuth token. A service account key includes its own.+ "llm-google-project-id": createGoogleSetting(+ "llm-google-project-id",+ googleOauthTokenValue ? (googleProjectIdValue ?? null) : null,+ ),+ "llm-google-location": createGoogleSetting(+ "llm-google-location",+ googleLocationValue,+ ),+ };+}+async function setup({isHosted = false,hasDeprecatedMetabaseAiProvider,@@ -221,6 +286,11 @@ async function setup({deferPurchaseCloudAddOnResponse = false,removeCloudAddOnResponse = 200,apiKeyValues,+ googleProjectIdValue,+ googleServiceAccountValue,+ googleOauthTokenValue,+ googleLocationValue,+ googleEnvSettings,pauseUpdateResponse = false,deferMetabotSettingsUpdateResponse = false,settingUpdateResponse = 204,@@ -305,6 +375,13 @@ async function setup({? "https://my-resource.services.ai.azure.com/anthropic": undefined,}),+ ...createGoogleSettingDefinitions({+ googleProjectIdValue,+ googleServiceAccountValue,+ googleOauthTokenValue,+ googleLocationValue,+ googleEnvSettings,+ }),"llm-mistral-api-key": createMockSettingDefinition({key: "llm-mistral-api-key",value: mergedApiKeyValues.mistral ?? undefined,@@ -468,6 +545,43 @@ async function setup({updateBedrockSetting("llm-bedrock-session-token", "session-token");}+ if (body.provider === "google" && "credentials" in body) {+ const mask = (value: string | null | undefined) =>+ value ? `**********${String(value).slice(-2)}` : undefined;++ // Same rules as Bedrock. `credentials: null` clears everything. In the map, an absent+ // field keeps the saved value, and a null field clears it.+ const requestCredentials = body.credentials ?? null;+ const updateGoogleSetting = (+ settingKey: GoogleSettingKey,+ field: keyof GoogleCredentials,+ masked: boolean,+ ) => {+ if (requestCredentials !== null && !(field in requestCredentials)) {+ return;+ }+ const nextValue = requestCredentials?.[field];+ settingsDefinitions[settingKey] = createMockSettingDefinition({+ ...settingsDefinitions[settingKey],+ key: settingKey,+ value: masked ? mask(nextValue) : (nextValue ?? undefined),+ });+ };++ updateGoogleSetting(+ "llm-google-service-account-key",+ "service-account-key",+ true,+ );+ updateGoogleSetting(+ "llm-google-oauth-access-token",+ "oauth-access-token",+ true,+ );+ updateGoogleSetting("llm-google-project-id", "project-id", false);+ updateGoogleSetting("llm-google-location", "location", false);+ }+if ("model" in body) {sessionProperties["llm-metabot-provider"] = updateResponse.value;sessionProperties["llm-metabot-configured?"] = true;@@ -648,6 +762,7 @@ describe("AIProviderSettingsSection", () => {/Z\.AI/,/Microsoft Azure/,/Amazon Bedrock/,+ /Gemini Enterprise Agent Platform/,]) {const option = await screen.findByRole("option", { name });expect(option).toBeInTheDocument();@@ -2282,6 +2397,541 @@ describe("AIProviderSettingsSection", () => {});});+ describe("Gemini Enterprise Agent Platform", () => {+ // The "OAuth token" label on the auth toggle is the same as the label on the OAuth token+ // input. Thus the queries for credential inputs also give the element type.+ const CREDENTIAL_INPUT = { selector: "input[type='password']" };++ it("shows the project ID, location, model, and auth type toggle with the service account key picker when selected", async () => {+ await setup({ savedProviderValue: null, isConfigured: false });++ await selectProvider("Gemini Enterprise Agent Platform");++ expect(await screen.findByLabelText("Project ID")).toBeInTheDocument();+ expect(screen.getByLabelText("Location")).toBeInTheDocument();+ expect(screen.getByLabelText("Model")).toBeInTheDocument();+ expect(+ screen.getByLabelText("Authentication method"),+ ).toBeInTheDocument();+ expect(screen.getByText("Service account key file")).toBeInTheDocument();+ // Only the credential input for the selected auth type is shown.+ expect(+ screen.queryByLabelText("OAuth token", CREDENTIAL_INPUT),+ ).not.toBeInTheDocument();+ });++ it("explains that model availability varies by location and links to the location docs", async () => {+ await setup({ savedProviderValue: null, isConfigured: false });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Model");++ expect(+ screen.getByText(/Model availability varies by location/),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", {+ name: "See which Gemini models are available in each location.",+ }),+ ).toHaveAttribute(+ "href",+ "https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations#google-models",+ );+ });++ const typeModel = async (model: string) => {+ await setup({ savedProviderValue: null, isConfigured: false });+ await selectProvider("Gemini Enterprise Agent Platform");+ await userEvent.type(await screen.findByLabelText("Model"), model);+ };++ const MODEL_WARNING =+ "Metabot works best with these models: gemini-3.5-flash, gemini-3.6-flash, gemini-3.7-flash. Other models may not work as expected.";++ it.each(["gemini-3.5-flash", "gemini-3.6-flash", "gemini-3.7-flash"])(+ "shows no advisory warning for %s",+ async (model) => {+ await typeModel(model);++ expect(screen.queryByText(MODEL_WARNING)).not.toBeInTheDocument();+ },+ );++ it("shows no advisory warning for a recommended model entered with the google publisher prefix", async () => {+ await typeModel("google/gemini-3.5-flash");++ expect(screen.queryByText(MODEL_WARNING)).not.toBeInTheDocument();+ });++ it("lists the recommended models when the model is another Gemini model", async () => {+ await typeModel("gemini-2.5-flash");++ expect(screen.getByText(MODEL_WARNING)).toBeInTheDocument();+ });++ it("lists the recommended models when the model is not a Gemini model", async () => {+ await typeModel("claude-sonnet-4-6");++ expect(screen.getByText(MODEL_WARNING)).toBeInTheDocument();+ });++ it("shows no advisory warning while the model is still blank", async () => {+ await setup({ savedProviderValue: null, isConfigured: false });+ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Model");++ expect(screen.queryByText(MODEL_WARNING)).not.toBeInTheDocument();+ });++ it("advisory warnings do not block connect", async () => {+ await setup({+ savedProviderValue: null,+ isConfigured: false,+ updateResponse: {+ value: "google/google/gemini-2.5-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.test-token",+ );+ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ await userEvent.type(screen.getByLabelText("Model"), "gemini-2.5-flash");++ expect(screen.getByText(MODEL_WARNING)).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();++ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-2.5-flash",+ credentials: {+ "oauth-access-token": "ya29.test-token",+ "project-id": "my-project",+ },+ },+ ]);+ });+ });++ it("shows a single credential input matching the selected auth type", async () => {+ await setup({ savedProviderValue: null, isConfigured: false });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.click(screen.getByText("OAuth token"));+ expect(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Service account key file"),+ ).not.toBeInTheDocument();++ await userEvent.click(screen.getByText("Service account key"));+ expect(screen.getByText("Service account key file")).toBeInTheDocument();+ expect(screen.getByText("Click to select a file")).toBeInTheDocument();+ expect(+ screen.getByLabelText("Service account key file input"),+ ).toBeInTheDocument();+ expect(+ screen.queryByLabelText("OAuth token", CREDENTIAL_INPUT),+ ).not.toBeInTheDocument();+ });++ it("keeps Connect disabled until the OAuth token, project ID, and model are filled in", async () => {+ await setup({ savedProviderValue: null, isConfigured: false });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.test-token",+ );+ expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();++ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();++ await userEvent.type(screen.getByLabelText("Model"), "gemini-3.5-flash");+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();+ });++ it("connects with a service account key file alone and sends its contents as credentials", async () => {+ await setup({+ savedProviderValue: null,+ isConfigured: false,+ updateResponse: {+ value: "google/google/gemini-3.5-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ await selectProvider("Gemini Enterprise Agent Platform");++ expect(+ await screen.findByRole("button", { name: "Connect" }),+ ).toBeDisabled();+ await userEvent.type(screen.getByLabelText("Model"), "gemini-3.5-flash");+ await userEvent.upload(+ screen.getByLabelText("Service account key file input"),+ new File(['{"type": "service_account"}'], "service-account.json", {+ type: "application/json",+ }),+ );+ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();+ });++ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-3.5-flash",+ credentials: {+ "service-account-key": '{"type": "service_account"}',+ },+ },+ ]);+ });+ });++ it("clears a selected service account file with the clear button", async () => {+ await setup({ savedProviderValue: null, isConfigured: false });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.type(screen.getByLabelText("Model"), "gemini-3.5-flash");+ await userEvent.upload(+ screen.getByLabelText("Service account key file input"),+ new File(['{"type": "service_account"}'], "service-account.json", {+ type: "application/json",+ }),+ );+ expect(+ await screen.findByText("service-account.json"),+ ).toBeInTheDocument();+ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();+ });++ await userEvent.click(+ screen.getByRole("button", { name: "Clear the selected file" }),+ );+ expect(+ screen.queryByText("service-account.json"),+ ).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();+ });++ it("connects by sending the qualified model and the credentials object in one request", async () => {+ await setup({+ savedProviderValue: null,+ isConfigured: false,+ updateResponse: {+ value: "google/google/gemini-3.5-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.test-token",+ );+ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ // A bare Gemini model ID gets the `google/` publisher prefix.+ await userEvent.type(screen.getByLabelText("Model"), "gemini-3.5-flash");+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ // The location field did not change, thus it is not sent. Only changed fields are sent.+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-3.5-flash",+ credentials: {+ "oauth-access-token": "ya29.test-token",+ "project-id": "my-project",+ },+ },+ ]);+ });+ });++ it("keeps an explicitly publisher-qualified model ID unchanged", async () => {+ await setup({+ savedProviderValue: null,+ isConfigured: false,+ updateResponse: {+ value: "google/google/gemini-3.6-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.test-token",+ );+ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ await userEvent.type(+ screen.getByLabelText("Model"),+ "google/gemini-3.6-flash",+ );+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-3.6-flash",+ credentials: {+ "oauth-access-token": "ya29.test-token",+ "project-id": "my-project",+ },+ },+ ]);+ });+ });++ it("indicates a saved service account key without echoing it and shows the saved model", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleServiceAccountValue: "**********\n}",+ });++ // The auth toggle defaults to the saved credential type.+ expect(+ await screen.findByText("Service account key file"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("A service account key is saved."),+ ).toBeInTheDocument();+ expect(+ screen.queryByLabelText("OAuth token", CREDENTIAL_INPUT),+ ).not.toBeInTheDocument();+ // The saved model is shown as the bare Gemini ID, without the `google/` publisher prefix.+ expect(await screen.findByLabelText("Model")).toHaveValue(+ "gemini-3.5-flash",+ );+ });++ it("clears a saved service account key when connecting with an OAuth token instead", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleServiceAccountValue: "**********\n}",+ updateResponse: {+ value: "google/google/gemini-3.5-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ // The toggle starts on the saved service account. Change to the OAuth token auth type.+ await screen.findByText("Service account key file");+ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.new-token",+ );+ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ // The service account field goes as null. The backend prefers the service account key to+ // the OAuth token, thus the old key must not stay active.+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-3.5-flash",+ credentials: {+ "oauth-access-token": "ya29.new-token",+ "project-id": "my-project",+ "service-account-key": null,+ },+ },+ ]);+ });+ });++ it("opens on the service account key when both credentials are saved, matching the backend's precedence", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleServiceAccountValue: "**********\n}",+ googleOauthTokenValue: "**********en",+ });++ expect(+ await screen.findByText("Service account key file"),+ ).toBeInTheDocument();+ expect(+ screen.queryByLabelText("OAuth token", CREDENTIAL_INPUT),+ ).not.toBeInTheDocument();+ });++ it("leaves an env-backed service account key alone when connecting with an OAuth token", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleServiceAccountValue: "**********\n}",+ googleEnvSettings: {+ "llm-google-service-account-key": "MB_LLM_GOOGLE_SERVICE_ACCOUNT_KEY",+ },+ updateResponse: {+ value: "google/google/gemini-3.5-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ await screen.findByLabelText("Project ID");+ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.new-token",+ );+ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ // An env-set key cannot be cleared, so the request leaves it out.+ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-3.5-flash",+ credentials: {+ "oauth-access-token": "ya29.new-token",+ "project-id": "my-project",+ },+ },+ ]);+ });+ });++ it("shows the saved credentials and model for a connected provider", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleOauthTokenValue: "**********en",+ });++ expect(+ await screen.findByLabelText("OAuth token", CREDENTIAL_INPUT),+ ).toHaveValue("**********en");+ expect(screen.getByLabelText("Project ID")).toHaveValue("my-project");+ expect(screen.getByLabelText("Model")).toHaveValue("gemini-3.5-flash");+ expect(+ screen.getByRole("button", { name: "Disconnect" }),+ ).toBeInTheDocument();+ });++ it("shows Connect instead of Disconnect when the connected model is edited", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleOauthTokenValue: "**********en",+ updateResponse: {+ value: "google/google/gemini-3.6-flash",+ models: DEFAULT_RESPONSES.google.models,+ },+ });++ expect(await screen.findByLabelText("Model")).toHaveValue(+ "gemini-3.5-flash",+ );+ expect(+ screen.getByRole("button", { name: "Disconnect" }),+ ).toBeInTheDocument();++ await userEvent.clear(screen.getByLabelText("Model"));+ await userEvent.type(screen.getByLabelText("Model"), "gemini-3.6-flash");++ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ await waitFor(async () => {+ expect(await findMetabotSettingsUpdates()).toEqual([+ {+ provider: "google",+ model: "google/gemini-3.6-flash",+ credentials: {},+ },+ ]);+ });+ });++ it("shows the connect error when validating the model fails", async () => {+ await setup({+ savedProviderValue: null,+ isConfigured: false,+ metabotSettingsUpdateResponse: {+ status: 400,+ body: {+ message:+ "Google API endpoint is unavailable or the model was not found.",+ },+ },+ });++ await selectProvider("Gemini Enterprise Agent Platform");+ await screen.findByLabelText("Project ID");++ await userEvent.click(screen.getByText("OAuth token"));+ await userEvent.type(+ screen.getByLabelText("OAuth token", CREDENTIAL_INPUT),+ "ya29.test-token",+ );+ await userEvent.type(screen.getByLabelText("Project ID"), "my-project");+ await userEvent.type(screen.getByLabelText("Model"), "gemini-9000");+ await userEvent.click(screen.getByRole("button", { name: "Connect" }));++ expect(+ await screen.findByText(+ "Google API endpoint is unavailable or the model was not found.",+ ),+ ).toBeInTheDocument();+ });++ it("disconnects by clearing the credentials before the provider setting", async () => {+ await setup({+ savedProviderValue: "google/google/gemini-3.5-flash",+ googleOauthTokenValue: "**********en",+ });++ await screen.findByLabelText("Project ID");+ await confirmDisconnectProvider();++ // The credentials must be cleared before the provider setting.+ await waitFor(async () => {+ expect(await findPutRequests()).toEqual([+ {+ path: METABOT_SETTINGS_PATH,+ body: { provider: "google", credentials: null },+ },+ {+ path: SETTING_PATH,+ body: { "llm-metabot-provider": null },+ },+ ]);+ });+ });+ });+describe("Amazon Bedrock", () => {it("shows the AWS credential fields when Amazon Bedrock is selected", async () => {await setup({ savedProviderValue: null, isConfigured: false });diff --git a/frontend/src/metabase/metabot/api.ts b/frontend/src/metabase/metabot/api.tsindex 35251475dc3..fad92398976 100644--- a/frontend/src/metabase/metabot/api.ts+++ b/frontend/src/metabase/metabot/api.ts@@ -26,6 +26,9 @@ import type {import type { MetabotConversationDetail } from "./utils/normalize-fetched-chat-messages";+const touchesCredentials = (body: UpdateMetabotSettingsRequest) =>+ "credentials" in body || "api-key" in body;+export const metabotApi = Api.injectEndpoints({endpoints: (builder) => ({listMetabots: builder.query<{ items: MetabotInfo[] }, void>({@@ -94,8 +97,13 @@ export const metabotApi = Api.injectEndpoints({url: "/api/metabot/settings",body,}),- invalidatesTags: (_, error) =>- invalidateTags(error, ["session-properties"]),+ invalidatesTags: (_, error, body) =>+ invalidateTags(error, [+ "session-properties",+ // A credential write can change which models the provider serves, e.g. a different Bedrock+ // region, Google location, or Azure resource.+ ...(touchesCredentials(body) ? [listTag("llm-models")] : []),+ ]),}),updateMetabot: builder.mutation<MetabotInfo,diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsxindex a8fd08ff271..ff69e977982 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/AIProviderConfigurationForm.tsx@@ -33,6 +33,7 @@ import { AIProviderConfigurationContext } from "./AIProviderConfigurationContextimport { ApiKeyProviderFields } from "./ApiKeyProviderFields";import { AzureProviderFields } from "./AzureProviderFields";import { BedrockProviderFields } from "./BedrockProviderFields";+import { GoogleProviderFields } from "./GoogleProviderFields";import {API_KEY_SETTING_BY_PROVIDER,getProviderOptions,@@ -149,7 +150,8 @@ function AIProviderConfigurationFormBody({if (connectedProvider !== "metabase" &&connectedProvider !== "bedrock" &&- connectedProvider !== "azure"+ connectedProvider !== "azure" &&+ connectedProvider !== "google") {const apiKeySettingKey = API_KEY_SETTING_BY_PROVIDER[connectedProvider];const apiKeySetting = providerApiKeyDetails[apiKeySettingKey];@@ -160,8 +162,12 @@ function AIProviderConfigurationFormBody({}try {- if (connectedProvider === "bedrock" || connectedProvider === "azure") {- // Bedrock and Azure key material spans several settings; an explicit+ if (+ connectedProvider === "bedrock" ||+ connectedProvider === "azure" ||+ connectedProvider === "google"+ ) {+ // Bedrock, Azure, and Google key material spans several settings; an explicit// `credentials: null` clears them all in one call. It runs before the provider// is deselected so a failure can't leave saved keys behind.await updateMetabotSettings({@@ -324,6 +330,13 @@ function AIProviderConfigurationFormBody({isEnvSetting={isEnvSetting}/>))+ .with("google", () => (+ <GoogleProviderFields+ connectedModel={connectedModel}+ isCurrentConfigured={isCurrentConfigured}+ isEnvSetting={isEnvSetting}+ />+ )).with("anthropic","mistral",diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/GoogleProviderFields.tsx b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/GoogleProviderFields.tsxnew file mode 100644index 00000000000..dba9e366f65--- /dev/null+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/GoogleProviderFields.tsx@@ -0,0 +1,376 @@+import { type FormikHelpers, useFormikContext } from "formik";+import { useMemo, useState } from "react";+import { jt, t } from "ttag";++import { ExternalLink } from "metabase/common/components/ExternalLink";+import { SetByEnvVar } from "metabase/common/components/SetByEnvVar";+import {+ FormErrorMessage,+ FormFileInput,+ FormProvider,+ FormTextInput,+} from "metabase/forms";+import { useAdminSettings } from "metabase/settings";+import { Alert, Box, Code, Icon, SegmentedControl, Text } from "metabase/ui";+import type {+ GoogleCredentials,+ SettingDefinitionMap,+} from "metabase-types/api";++import { useUpdateMetabotSettingsMutation } from "../../api";++import { useAIProviderConfigurationContext } from "./AIProviderConfigurationContext";+import { hasConfiguredSettingValue } from "./utils";++const GOOGLE_SETTING_KEYS = [+ "llm-google-service-account-key",+ "llm-google-oauth-access-token",+ "llm-google-project-id",+ "llm-google-location",+] as const;++const GOOGLE_MODEL_LOCATIONS_URL =+ "https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations#google-models";++// The models Metabot is known to work well with. Which of them a project can actually reach depends+// on its location, thus the input still accepts any model ID and only warns about the rest.+// The first entry in this list is used as the placeholder for the model form input below.+const RECOMMENDED_MODELS = [+ "gemini-3.5-flash",+ "gemini-3.6-flash",+ "gemini-3.7-flash",+] as const;++type GoogleSettingDetails = SettingDefinitionMap<+ (typeof GOOGLE_SETTING_KEYS)[number]+>;++type GoogleCredentialValues = {+ serviceAccountFile: File | null;+ oauthToken: string;+ projectId: string;+ location: string;+ model: string;+};++type GoogleAuthType = "service-account" | "oauth-token";++const isGoogleAuthType = (value: string): value is GoogleAuthType =>+ value === "service-account" || value === "oauth-token";++// The setting keeps publisher-qualified model IDs, e.g. `google/gemini-3.5-flash`. The input shows+// and accepts the bare Gemini ID. Thus we remove the default `google` publisher for the display and+// add it again on submit.+const stripGooglePublisher = (model: string | undefined) =>+ model?.replace(/^google\//, "") ?? "";++const qualifyGoogleModel = (model: string) =>+ model.includes("/") ? model : `google/${model}`;++const isRecommendedModel = (model: string) =>+ RECOMMENDED_MODELS.some(+ (recommended) =>+ recommended === stripGooglePublisher(model.trim().toLowerCase()),+ );++// Advisory only — a model outside the list still connects, it just may not work well with Metabot.+const getModelWarning = (model: string): string | null => {+ if (!model.trim() || isRecommendedModel(model)) {+ return null;+ }+ const recommendedModels = RECOMMENDED_MODELS.join(", ");+ return t`Metabot works best with these models: ${recommendedModels}. Other models may not work as expected.`;+};++const readFileText = (file: File) =>+ new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(String(reader.result));+ reader.onerror = () => reject(new Error(t`Could not read the file`));+ reader.readAsText(file);+ });++export const GoogleProviderFields = ({+ connectedModel,+ isCurrentConfigured,+ isEnvSetting,+}: {+ connectedModel: string | undefined;+ isCurrentConfigured: boolean;+ isEnvSetting: boolean;+}) => {+ const [updateMetabotSettings] = useUpdateMetabotSettingsMutation();+ const { details } = useAdminSettings(GOOGLE_SETTING_KEYS);++ const initialValues = useMemo<GoogleCredentialValues>(+ () => ({+ // The saved key JSON never goes back into the form. The file picker starts empty, and an+ // empty picker means "keep the saved key". See the placeholder of the picker.+ serviceAccountFile: null,+ oauthToken: String(details["llm-google-oauth-access-token"]?.value ?? ""),+ projectId: String(details["llm-google-project-id"]?.value ?? ""),+ location: String(details["llm-google-location"]?.value ?? ""),+ model: stripGooglePublisher(+ isCurrentConfigured ? connectedModel : undefined,+ ),+ }),+ [connectedModel, details, isCurrentConfigured],+ );++ const handleSubmit = async (+ values: GoogleCredentialValues,+ { resetForm }: FormikHelpers<GoogleCredentialValues>,+ ) => {+ // Send only the fields that changed. The backend keeps the saved value for a field that is+ // absent. A field that the user made blank goes as null, which clears the saved value.+ const credentials: GoogleCredentials = {};+ const setIfChanged = (+ apiField: keyof GoogleCredentials,+ field: "oauthToken" | "projectId" | "location",+ ) => {+ if (values[field] !== initialValues[field]) {+ credentials[apiField] = values[field] || null;+ }+ };++ setIfChanged("oauth-access-token", "oauthToken");+ setIfChanged("project-id", "projectId");+ setIfChanged("location", "location");++ if (values.serviceAccountFile) {+ credentials["service-account-key"] = await readFileText(+ values.serviceAccountFile,+ );+ }++ // A connection with one credential type clears the other. An env-backed credential is left alone: the env var+ // supplies it on every read, so clearing it would do nothing.+ const clearOtherCredential = (+ apiField: "service-account-key" | "oauth-access-token",+ settingKey:+ | "llm-google-service-account-key"+ | "llm-google-oauth-access-token",+ ) => {+ const setting = details[settingKey];+ const isClearable =+ hasConfiguredSettingValue(setting) && !setting?.is_env_setting;+ if (isClearable && !(apiField in credentials)) {+ credentials[apiField] = null;+ }+ };++ if (credentials["service-account-key"]) {+ clearOtherCredential(+ "oauth-access-token",+ "llm-google-oauth-access-token",+ );+ } else if (credentials["oauth-access-token"]) {+ clearOtherCredential(+ "service-account-key",+ "llm-google-service-account-key",+ );+ }++ await updateMetabotSettings({+ provider: "google",+ model: qualifyGoogleModel(values.model.trim()),+ credentials,+ }).unwrap();++ // Remove the key material after the save. The picker shows its placeholder again.+ resetForm({ values: { ...values, serviceAccountFile: null } });+ };++ return (+ <FormProvider+ initialValues={initialValues}+ onSubmit={handleSubmit}+ enableReinitialize+ >+ <GoogleCredentialFields+ details={details}+ isCurrentConfigured={isCurrentConfigured}+ isEnvSetting={isEnvSetting}+ />+ </FormProvider>+ );+};++const GoogleCredentialFields = ({+ details,+ isCurrentConfigured,+ isEnvSetting,+}: {+ details: GoogleSettingDetails;+ isCurrentConfigured: boolean;+ isEnvSetting: boolean;+}) => {+ const { dirty, submitForm, values, setFieldValue, initialValues } =+ useFormikContext<GoogleCredentialValues>();++ const serviceAccountSetting = details["llm-google-service-account-key"];+ const oauthTokenSetting = details["llm-google-oauth-access-token"];+ const projectIdSetting = details["llm-google-project-id"];+ const locationSetting = details["llm-google-location"];++ const hasSavedServiceAccount = hasConfiguredSettingValue(+ serviceAccountSetting,+ );++ // Ensure auth toggle selects correct option based on current settings.+ const [authTypeOverride, setAuthTypeOverride] =+ useState<GoogleAuthType | null>(null);+ const savedAuthType: GoogleAuthType =+ !hasSavedServiceAccount && hasConfiguredSettingValue(oauthTokenSetting)+ ? "oauth-token"+ : "service-account";+ const authType = authTypeOverride ?? savedAuthType;++ const hasCompleteCredential =+ authType === "service-account"+ ? !!values.serviceAccountFile || hasSavedServiceAccount+ : !!values.oauthToken.trim() && !!values.projectId.trim();+ // The file picker never shows a saved key, thus an empty picker is still complete if a key is saved.+ const isComplete = hasCompleteCredential && !!values.model.trim();+ const modelWarning = getModelWarning(values.model);+ const connectHandler =+ isComplete && (!isCurrentConfigured || dirty) ? submitForm : null;+ const { isMutating } = useAIProviderConfigurationContext(connectHandler);++ const handleAuthTypeChange = (value: string) => {+ if (!isGoogleAuthType(value)) {+ return;+ }+ setAuthTypeOverride(value);+ // Only the credential that is visible can go in the request. Reset what the admin entered for+ // the other auth type.+ if (value === "service-account") {+ setFieldValue("oauthToken", initialValues.oauthToken);+ } else {+ setFieldValue("serviceAccountFile", null);+ }+ };++ const serviceAccountEnvName = serviceAccountSetting?.is_env_setting+ ? serviceAccountSetting.env_name+ : undefined;+ const oauthTokenEnvName = oauthTokenSetting?.is_env_setting+ ? oauthTokenSetting.env_name+ : undefined;+ const projectIdEnvName = projectIdSetting?.is_env_setting+ ? projectIdSetting.env_name+ : undefined;+ const locationEnvName = locationSetting?.is_env_setting+ ? locationSetting.env_name+ : undefined;++ return (+ <>+ <FormTextInput+ name="projectId"+ label={t`Project ID`}+ description={t`The Google Cloud project to use. Optional if the service account key provides it.`}+ placeholder={t`Enter your Google Cloud project ID`}+ disabled={isMutating || isEnvSetting || !!projectIdEnvName}+ w="100%"+ />+ {projectIdEnvName && <SetByEnvVar varName={projectIdEnvName} />}++ <FormTextInput+ name="location"+ label={t`Location`}+ description={t`Optional. Defaults to global.`}+ placeholder="global"+ disabled={isMutating || isEnvSetting || !!locationEnvName}+ w="100%"+ />+ {locationEnvName && <SetByEnvVar varName={locationEnvName} />}++ <FormTextInput+ name="model"+ label={t`Model`}+ description={jt`Model availability varies by location. ${(+ <ExternalLink key="model-locations" href={GOOGLE_MODEL_LOCATIONS_URL}>+ {t`See which Gemini models are available in each location.`}+ </ExternalLink>+ )}`}+ placeholder={RECOMMENDED_MODELS[0]}+ disabled={isMutating || isEnvSetting}+ w="100%"+ />+ {modelWarning && (+ <Alert size="compact" color="warning" icon={<Icon name="warning" />}>+ {modelWarning}+ </Alert>+ )}++ <Box>+ <Text fw="bold">{t`Authentication method`}</Text>+ <Text size="sm" c="text-secondary">+ {t`Authenticate with a service account key or an OAuth access token.`}+ </Text>+ </Box>++ <SegmentedControl+ value={authType}+ onChange={handleAuthTypeChange}+ disabled={isMutating || isEnvSetting}+ data={[+ { value: "service-account", label: t`Service account key` },+ { value: "oauth-token", label: t`OAuth token` },+ ]}+ aria-label={t`Authentication method`}+ fullWidth+ />++ {authType === "service-account" && (+ <>+ <FormFileInput+ name="serviceAccountFile"+ label={t`Service account key file`}+ description={+ hasSavedServiceAccount ? (+ <>+ <strong>{t`A service account key is saved.`}</strong>{" "}+ {t`Choose a new file to replace it.`}+ </>+ ) : (+ t`Upload a service account key file to authenticate with.`+ )+ }+ placeholder={t`Click to select a file`}+ leftSection={<Icon name="upload" />}+ accept="application/json"+ clearable+ clearButtonProps={{ "aria-label": t`Clear the selected file` }}+ disabled={isMutating || isEnvSetting || !!serviceAccountEnvName}+ fileInputProps={{ "aria-label": t`Service account key file input` }}+ w="100%"+ />+ {serviceAccountEnvName && (+ <SetByEnvVar varName={serviceAccountEnvName} />+ )}+ </>+ )}++ {authType === "oauth-token" && (+ <>+ <FormTextInput+ name="oauthToken"+ label={t`OAuth token`}+ type="password"+ description={jt`Paste a short-lived OAuth access token, e.g. the output of ${(+ <Code key="gcloud">{"gcloud auth print-access-token"}</Code>+ )}. Useful for testing.`}+ placeholder="ya29..."+ disabled={isMutating || isEnvSetting || !!oauthTokenEnvName}+ w="100%"+ />+ {oauthTokenEnvName && <SetByEnvVar varName={oauthTokenEnvName} />}+ </>+ )}++ <FormErrorMessage />+ </>+ );+};diff --git a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.tsindex a4255117b98..f9e6be9b00e 100644--- a/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts+++ b/frontend/src/metabase/metabot/components/AIProviderConfigurationForm/utils.ts@@ -2,7 +2,7 @@ import { t } from "ttag";import type { MetabotProvider, SettingDefinition } from "metabase-types/api";-type ApiKeylessProviders = "metabase";+type ApiKeylessProviders = "metabase" | "google";type ApiKeyProviders = Exclude<MetabotProvider, ApiKeylessProviders>;type MetabotApiKeylessProviderOption = {@@ -25,7 +25,8 @@ export type MetabotProviderOption =export function getProviderOptions(hasMetabaseProviderAccess: boolean,-): Partial<Record<ApiKeylessProviders, MetabotApiKeylessProviderOption>> &+): Partial<Record<"metabase", MetabotApiKeylessProviderOption>> &+ Record<"google", MetabotApiKeylessProviderOption> &Record<ApiKeyProviders, MetabotApiKeyProviderOption> {return {...(hasMetabaseProviderAccess && {@@ -61,6 +62,10 @@ export function getProviderOptions("https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html",},},+ google: {+ value: "google",+ label: "Gemini Enterprise Agent Platform",+ },mistral: {value: "mistral",label: "Mistral",@@ -108,7 +113,7 @@ export function getProviderOptions(export type MetabotApiKeyProvider = Exclude<MetabotProvider,- "metabase" | "azure" | "bedrock"+ "metabase" | "azure" | "bedrock" | "google">;export function isMetabotProvider(@@ -122,6 +127,7 @@ export function isAvailableProvider(provider: MetabotProvider): boolean {provider === "anthropic" ||provider === "azure" ||provider === "bedrock" ||+ provider === "google" ||provider === "metabase" ||provider === "mistral" ||provider === "moonshot" ||diff --git a/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.config.tsx b/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.config.tsxindex 2d8e22eb4e0..4ca2537d5b9 100644--- a/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.config.tsx+++ b/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.config.tsx@@ -1,5 +1,6 @@import { FileInput } from "@mantine/core";+import Styles from "./FileInput.module.css";import { FileInputValue } from "./FileInputValue";export const fileInputOverrides = {@@ -8,5 +9,9 @@ export const fileInputOverrides = {size: "md",valueComponent: FileInputValue,},+ classNames: {+ placeholder: Styles.FileInputPlaceholder,+ section: Styles.FileInputSection,+ },}),};diff --git a/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.module.css b/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.module.cssindex beed9cee926..4d4e400c307 100644--- a/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.module.css+++ b/frontend/src/metabase/ui/components/inputs/FileInput/FileInput.module.css@@ -3,3 +3,17 @@text-overflow: ellipsis;white-space: nowrap;}++/* The theme resolves --mantine-color-placeholder to transparent, because the native+ ::placeholder has its own style. That would hide the span placeholder that FileInput+ renders. Give it the color that native input placeholders get. */+.FileInputPlaceholder {+ color: var(--mb-color-text-disabled);+}++/* The clear button rendered by `clearable` is a CloseButton, which takes its color+ from the gray palette that the theme resolves to transparent. Without this it is+ present and clickable but invisible. */+.FileInputSection button {+ color: var(--mb-color-text-primary);+}