Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(agent): handle duplicate Gemini tool call ids (#19979)
p0ny54b3cbef46d8
diff --git a/backend/api/v1/ai_service.go b/backend/api/v1/ai_service.goindex 22216f8fef..866576edc2 100644--- a/backend/api/v1/ai_service.go+++ b/backend/api/v1/ai_service.go@@ -10,6 +10,7 @@ import ("net/url""connectrpc.com/connect"+ "github.com/google/uuid""github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -532,6 +533,10 @@ type chatGeminiResponsePart struct {ThoughtSignature string `json:"thoughtSignature,omitempty"`}+func newGeminiToolCallID(name string) string {+ return fmt.Sprintf("call_%s_%s", name, uuid.NewString())+}+func (*AIService) chatGemini(ctx context.Context, aiSetting *storepb.AISetting, request *v1pb.AIChatRequest) (*connect.Response[v1pb.AIChatResponse], error) {payload := chatGeminiRequest{}@@ -654,7 +659,7 @@ func (*AIService) chatGemini(ctx context.Context, aiSetting *storepb.AISetting,return nil, errors.Errorf("failed to marshal function call args: %s", err)}tc := &v1pb.AIChatToolCall{- Id: fmt.Sprintf("call_%s", part.FunctionCall.Name),+ Id: newGeminiToolCallID(part.FunctionCall.Name),Name: part.FunctionCall.Name,Arguments: string(args),}diff --git a/backend/api/v1/ai_service_test.go b/backend/api/v1/ai_service_test.goindex 1e3b19a979..ba1854f4e2 100644--- a/backend/api/v1/ai_service_test.go+++ b/backend/api/v1/ai_service_test.go@@ -1,10 +1,16 @@package v1import (+ "context""encoding/json"+ "net/http"+ "net/http/httptest""testing""github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")func TestChatGeminiPartMarshalsThoughtSignatureOnPart(t *testing.T) {@@ -133,3 +139,36 @@ func TestGeminiThoughtSignatureFromMetadataSupportsLegacyFormats(t *testing.T) {require.Equal(t, "sig-native", geminiThoughtSignatureFromMetadata("sig-native"))})}++func TestChatGeminiGeneratesUniqueToolCallIDs(t *testing.T) {+ t.Parallel()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, err := w.Write([]byte(`{+ "candidates": [{+ "content": {+ "parts": [+ {"functionCall": {"name": "search_api", "args": {"service": "SQLService"}}},+ {"functionCall": {"name": "search_api", "args": {"operationId": "SQLService/Query"}}}+ ]+ }+ }]+ }`))+ require.NoError(t, err)+ }))+ defer server.Close()++ resp, err := (&AIService{}).chatGemini(+ context.Background(),+ &storepb.AISetting{+ Endpoint: server.URL,+ Model: "gemini-2.5-pro",+ ApiKey: "test-key",+ },+ &v1pb.AIChatRequest{},+ )+ require.NoError(t, err)+ require.Len(t, resp.Msg.ToolCalls, 2)+ require.NotEqual(t, resp.Msg.ToolCalls[0].Id, resp.Msg.ToolCalls[1].Id)+}diff --git a/frontend/src/react/plugins/agent/components/AgentChat.test.tsx b/frontend/src/react/plugins/agent/components/AgentChat.test.tsxindex c3d488097c..5f8f8823ed 100644--- a/frontend/src/react/plugins/agent/components/AgentChat.test.tsx+++ b/frontend/src/react/plugins/agent/components/AgentChat.test.tsx@@ -118,4 +118,87 @@ describe("AgentChat", () => {unmount();});++ test("renders duplicate tool call ids without React key warnings", () => {+ const consoleError = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);++ useAgentStore.getState().addMessage({+ role: "assistant",+ toolCalls: [+ {+ id: "call_search_api",+ name: "search_api",+ arguments: JSON.stringify({ service: "SQLService" }),+ },+ {+ id: "call_search_api",+ name: "search_api",+ arguments: JSON.stringify({ operationId: "SQLService/Query" }),+ },+ ],+ });++ const { container, render, unmount } = renderIntoContainer(<AgentChat />);++ render();++ expect(container.textContent).toContain("search_api");+ expect(container.querySelectorAll(".font-mono")).toHaveLength(2);+ expect(consoleError).not.toHaveBeenCalledWith(+ expect.stringContaining("Encountered two children with the same key")+ );++ consoleError.mockRestore();+ unmount();+ });++ test("matches duplicate tool call ids to results by occurrence order", () => {+ const assistantMessage = useAgentStore.getState().addMessage({+ role: "assistant",+ toolCalls: [+ {+ id: "call_search_api",+ name: "search_api",+ arguments: JSON.stringify({ service: "SQLService" }),+ },+ {+ id: "call_search_api",+ name: "search_api",+ arguments: JSON.stringify({ operationId: "SQLService/Query" }),+ },+ ],+ });++ useAgentStore.getState().addMessage({+ role: "tool",+ toolCallId: "call_search_api",+ content: "first-result",+ });+ useAgentStore.getState().addMessage({+ role: "tool",+ toolCallId: "call_search_api",+ content: "second-result",+ });++ const { container, render, unmount } = renderIntoContainer(<AgentChat />);++ render();++ const cardHeaders = container.querySelectorAll(".cursor-pointer");+ expect(cardHeaders).toHaveLength(2);++ act(() => {+ for (const header of cardHeaders) {+ header.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ }+ });++ expect(assistantMessage.toolCalls).toHaveLength(2);+ expect(container.textContent).toContain("first-result");+ expect(container.textContent).toContain("second-result");++ unmount();+ });});diff --git a/frontend/src/react/plugins/agent/components/AgentChat.tsx b/frontend/src/react/plugins/agent/components/AgentChat.tsxindex 33e889444a..87e2cb2756 100644--- a/frontend/src/react/plugins/agent/components/AgentChat.tsx+++ b/frontend/src/react/plugins/agent/components/AgentChat.tsx@@ -6,7 +6,7 @@ import { Button } from "@/react/components/ui/button";import { router } from "@/router";import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";import { hasWorkspacePermissionV2 } from "@/utils";-import type { AgentMessage } from "../logic/types";+import type { AgentMessage, ToolCall } from "../logic/types";import {selectCurrentChatRequiresAIConfiguration,selectError,@@ -47,17 +47,22 @@ export function AgentChat({ className }: AgentChatProps) {function getToolResult(messageId: string,- toolCallId: string+ toolCallId: string,+ duplicateIndex = 0): string | undefined {const fullIndex = allMessages.findIndex((message) => message.id === messageId);if (fullIndex < 0) return undefined;+ let matchingResultIndex = 0;for (let index = fullIndex + 1; index < allMessages.length; index++) {const message = allMessages[index];if (message.role === "tool" && message.toolCallId === toolCallId) {- return message.content;+ if (matchingResultIndex === duplicateIndex) {+ return message.content;+ }+ matchingResultIndex++;}if (message.role === "assistant" &&@@ -70,6 +75,20 @@ export function AgentChat({ className }: AgentChatProps) {return undefined;}+ function getToolCallDuplicateIndex(+ toolCalls: ToolCall[],+ currentToolCallIndex: number+ ): number {+ const currentToolCall = toolCalls[currentToolCallIndex];+ let duplicateIndex = 0;+ for (let index = 0; index < currentToolCallIndex; index++) {+ if (toolCalls[index]?.id === currentToolCall.id) {+ duplicateIndex++;+ }+ }+ return duplicateIndex;+ }+function goConfigure() {clearError(currentChatId);router.push({@@ -175,11 +194,15 @@ export function AgentChat({ className }: AgentChatProps) {</ReactMarkdown></div>)}- {msg.toolCalls?.map((toolCall) => (+ {msg.toolCalls?.map((toolCall, index, toolCalls) => (<ToolCallCard- key={toolCall.id}+ key={`${msg.id}:${toolCall.id}:${index}`}toolCall={toolCall}- result={getToolResult(msg.id, toolCall.id)}+ result={getToolResult(+ msg.id,+ toolCall.id,+ getToolCallDuplicateIndex(toolCalls, index)+ )}/>))}</div>