From b0d60a8c867b54919bccdb6dca8eb86dde2644b5 Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:30:23 +0800 Subject: [PATCH 1/4] fix(gemini): separate same-name parallel tool calls in streams --- .../gemini_chat_completions_compat_service.go | 4 +- .../service/gemini_messages_compat_service.go | 4 +- .../service/gemini_parallel_tools_test.go | 169 ++++++++++++++++++ .../service/gemini_tool_call_boundary.go | 25 +++ 4 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 backend/internal/service/gemini_parallel_tools_test.go create mode 100644 backend/internal/service/gemini_tool_call_boundary.go diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index f0716e003c..fc33c52d1b 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -600,6 +600,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom var seenThought geminiTextDelta openToolIndex := -1 openToolName := "" + openToolUpstreamID := "" var seenToolJSON geminiTextDelta closeOpenBlock := func() bool { @@ -735,7 +736,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom if closeOpenBlock() { return streamResult(), nil } - if openToolIndex >= 0 && openToolName != name { + if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { if closeOpenTool() { return streamResult(), nil } @@ -745,6 +746,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom nextBlockIndex++ openToolIndex = idx openToolName = name + openToolUpstreamID, _ = fc["id"].(string) sawToolUse = true if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_start", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 9d2ad1ae45..c1f10a793a 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2215,6 +2215,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex := -1 openToolID := "" openToolName := "" + openToolUpstreamID := "" var seenToolJSON geminiTextDelta reader := newBoundedSSELineReader(resp.Body, s.cfg) @@ -2394,7 +2395,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } // If we receive streamed tool args in pieces, keep a single tool block open and emit deltas. - if openToolIndex >= 0 && openToolName != name { + if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { writeSSE(c.Writer, "content_block_stop", map[string]any{ "type": "content_block_stop", "index": openToolIndex, @@ -2408,6 +2409,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolID = "toolu_" + randomHex(8) openToolIndex = nextBlockIndex openToolName = name + openToolUpstreamID, _ = fc["id"].(string) nextBlockIndex++ sawToolUse = true diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go new file mode 100644 index 0000000000..192887c579 --- /dev/null +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -0,0 +1,169 @@ +package service + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGeminiParallelToolStreams(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + frames [][]string + want []string + }{ + {"same_name_distinct_ids_one_event", [][]string{{`{"id":"a","name":"read_file","args":{"path":"a"}}`, `{"id":"b","name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_distinct_ids_separate_events", [][]string{{`{"id":"a","name":"read_file","args":{"path":"a"}}`}, {`{"id":"b","name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_identical_arguments_distinct_ids", [][]string{{`{"id":"a","name":"read_file","args":{}}`, `{"id":"b","name":"read_file","args":{}}`}}, []string{`{}`, `{}`}}, + {"same_name_no_ids_one_event", [][]string{{`{"name":"read_file","args":{"path":"a"}}`, `{"name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_no_ids_identical_separate_events", [][]string{{`{"name":"read_file","args":{}}`}, {`{"name":"read_file","args":{}}`}}, []string{`{}`, `{}`}}, + {"same_id_incremental_strings", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"no_id_incremental_strings", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"same_id_cumulative_and_duplicate", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, + } + for _, tt := range tests { + for _, protocol := range []string{"chat", "messages"} { + t.Run(tt.name+"/"+protocol, func(t *testing.T) { + var upstream strings.Builder + for _, frame := range tt.frames { + parts := []any{} + for _, fc := range frame { + var call map[string]any + require.NoError(t, json.Unmarshal([]byte(fc), &call)) + parts = append(parts, map[string]any{"functionCall": call}) + } + b, err := json.Marshal(map[string]any{"candidates": []any{map[string]any{"content": map[string]any{"parts": parts}}}}) + require.NoError(t, err) + upstream.WriteString("data: " + string(b) + "\n\n") + } + upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + svc := &GeminiMessagesCompatService{} + resp := &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(upstream.String()))} + var result *geminiStreamResult + var err error + if protocol == "chat" { + result, err = svc.handleChatCompletionsStreamingResponseFromGemini(c, resp, time.Now(), "gemini-test", false, true) + } else { + result, err = svc.handleStreamingResponse(c, resp, time.Now(), "gemini-test") + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.CacheReadInputTokens) + calls, terminal, open := collectParallelToolCalls(t, rec.Body.String(), protocol) + require.True(t, terminal) + require.Equal(t, -1, open) + require.Len(t, calls, len(tt.want)) + ids := map[string]bool{} + for i, want := range tt.want { + a := calls[i] + require.NotNil(t, a) + require.NotEmpty(t, a.id) + require.NotEmpty(t, a.name) + require.False(t, ids[a.id]) + ids[a.id] = true + require.JSONEq(t, want, a.args) + } + }) + } + } +} + +// collectParallelToolCalls checks the public SSE representation, including +// per-call metadata and the Anthropic content block lifecycle. +func collectParallelToolCalls(t *testing.T, body, protocol string) (map[int]*parallelToolCall, bool, int) { + t.Helper() + calls := map[int]*parallelToolCall{} + terminal, open := false, -1 + for _, line := range strings.Split(body, "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + raw := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if raw == "[DONE]" { + continue + } + var e struct { + Type string `json:"type"` + Index int `json:"index"` + ContentBlock struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + } `json:"content_block"` + Delta struct { + Type string `json:"type"` + PartialJSON string `json:"partial_json"` + StopReason string `json:"stop_reason"` + } `json:"delta"` + Choices []struct { + FinishReason string `json:"finish_reason"` + Delta struct { + ToolCalls []struct { + Index *int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + } + require.NoError(t, json.Unmarshal([]byte(raw), &e)) + if protocol == "chat" { + for _, choice := range e.Choices { + if choice.FinishReason == "tool_calls" { + terminal = true + } + for _, tc := range choice.Delta.ToolCalls { + require.NotNil(t, tc.Index) + idx := *tc.Index + a := calls[idx] + if a == nil { + require.NotEmpty(t, tc.ID, "first delta must identify its call") + require.NotEmpty(t, tc.Function.Name, "first delta must name its function") + a = ¶llelToolCall{} + calls[idx] = a + } + a.id += tc.ID + a.name += tc.Function.Name + a.args += tc.Function.Arguments + } + } + continue + } + switch e.Type { + case "content_block_start": + require.Equal(t, -1, open, "previous block must close before the next starts") + require.Equal(t, "tool_use", e.ContentBlock.Type) + open = e.Index + _, exists := calls[e.Index] + require.False(t, exists, "tool block indexes must be unique") + calls[e.Index] = ¶llelToolCall{id: e.ContentBlock.ID, name: e.ContentBlock.Name} + case "content_block_delta": + require.Equal(t, open, e.Index) + require.Equal(t, "input_json_delta", e.Delta.Type) + require.NotNil(t, calls[e.Index]) + calls[e.Index].args += e.Delta.PartialJSON + case "content_block_stop": + require.Equal(t, open, e.Index) + open = -1 + case "message_delta": + terminal = e.Delta.StopReason == "tool_use" + } + } + return calls, terminal, open +} + +type parallelToolCall struct{ id, name, args string } diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go new file mode 100644 index 0000000000..22f9914cdf --- /dev/null +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -0,0 +1,25 @@ +package service + +import ( + "encoding/json" + "strings" +) + +// geminiToolCallStartsNewBlock distinguishes call identity from function name. +// Calls with explicit IDs may contain incremental or cumulative arguments. +// Without IDs on both parts, a complete argument document marks the boundary +// before the next call, even when its name and arguments are identical. +func geminiToolCallStartsNewBlock(openID, openName, seenJSON string, fc map[string]any) bool { + name, _ := fc["name"].(string) + if strings.TrimSpace(name) == "" { + name = "tool" + } + if name != openName { + return true + } + id, _ := fc["id"].(string) + if id != "" && openID != "" { + return id != openID + } + return json.Valid([]byte(seenJSON)) +} From 27a61be4c9e72857fcde5b0d6085d31bdb73d10b Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:52:06 +0800 Subject: [PATCH 2/4] fix(gemini): preserve final snapshots of fragmented tool calls --- .../gemini_chat_completions_compat_service.go | 20 ++----- .../service/gemini_messages_compat_service.go | 25 +++----- .../service/gemini_parallel_tools_test.go | 13 +++- .../service/gemini_tool_call_boundary.go | 59 ++++++++++++++++--- 4 files changed, 74 insertions(+), 43 deletions(-) diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index fc33c52d1b..e89587866d 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -600,7 +600,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom var seenThought geminiTextDelta openToolIndex := -1 openToolName := "" - openToolUpstreamID := "" + var toolBoundary geminiToolCallBoundary var seenToolJSON geminiTextDelta closeOpenBlock := func() bool { @@ -620,6 +620,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} return disconnected } @@ -736,7 +737,8 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom if closeOpenBlock() { return streamResult(), nil } - if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { + argsJSONText := geminiToolCallArgsJSON(fc["args"]) + if openToolIndex >= 0 && toolBoundary.startsNewBlock(openToolName, seenToolJSON.seen.String(), argsJSONText, fc) { if closeOpenTool() { return streamResult(), nil } @@ -746,7 +748,6 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom nextBlockIndex++ openToolIndex = idx openToolName = name - openToolUpstreamID, _ = fc["id"].(string) sawToolUse = true if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_start", @@ -762,19 +763,8 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom } } - argsJSONText := "{}" - switch v := fc["args"].(type) { - case nil: - case string: - if strings.TrimSpace(v) != "" { - argsJSONText = v - } - default: - if b, err := json.Marshal(v); err == nil && len(b) > 0 { - argsJSONText = string(b) - } - } delta := seenToolJSON.next(argsJSONText) + toolBoundary.observe(fc, seenToolJSON.seen.String()) if delta != "" { if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_delta", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index c1f10a793a..b0e6b308cd 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2215,7 +2215,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex := -1 openToolID := "" openToolName := "" - openToolUpstreamID := "" + var toolBoundary geminiToolCallBoundary var seenToolJSON geminiTextDelta reader := newBoundedSSELineReader(resp.Body, s.cfg) @@ -2283,6 +2283,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } if openBlockType != "thinking" { if openBlockIndex >= 0 { @@ -2334,6 +2335,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } delta := seenText.next(text) @@ -2379,7 +2381,6 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re if fc, ok := part["functionCall"].(map[string]any); ok && fc != nil { name, _ := fc["name"].(string) - args := fc["args"] if strings.TrimSpace(name) == "" { name = "tool" } @@ -2395,7 +2396,8 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } // If we receive streamed tool args in pieces, keep a single tool block open and emit deltas. - if openToolIndex >= 0 && geminiToolCallStartsNewBlock(openToolUpstreamID, openToolName, seenToolJSON.seen.String(), fc) { + argsJSONText := geminiToolCallArgsJSON(fc["args"]) + if openToolIndex >= 0 && toolBoundary.startsNewBlock(openToolName, seenToolJSON.seen.String(), argsJSONText, fc) { writeSSE(c.Writer, "content_block_stop", map[string]any{ "type": "content_block_stop", "index": openToolIndex, @@ -2403,13 +2405,13 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } if openToolIndex < 0 { openToolID = "toolu_" + randomHex(8) openToolIndex = nextBlockIndex openToolName = name - openToolUpstreamID, _ = fc["id"].(string) nextBlockIndex++ sawToolUse = true @@ -2425,21 +2427,8 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re }) } - argsJSONText := "{}" - switch v := args.(type) { - case nil: - // keep default "{}" - case string: - if strings.TrimSpace(v) != "" { - argsJSONText = v - } - default: - if b, err := json.Marshal(args); err == nil && len(b) > 0 { - argsJSONText = string(b) - } - } - delta := seenToolJSON.next(argsJSONText) + toolBoundary.observe(fc, seenToolJSON.seen.String()) if delta != "" { writeSSE(c.Writer, "content_block_delta", map[string]any{ "type": "content_block_delta", diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go index 192887c579..66babba3b2 100644 --- a/backend/internal/service/gemini_parallel_tools_test.go +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -28,6 +28,15 @@ func TestGeminiParallelToolStreams(t *testing.T) { {"same_id_incremental_strings", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, {"no_id_incremental_strings", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, {"same_id_cumulative_and_duplicate", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"anonymous_incremental_then_final_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"id_first_chunk_only_then_final_snapshot", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"id_learned_on_second_chunk_then_duplicate", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"same_name_no_ids_identical_one_event", [][]string{{`{"name":"read_file","args":{"path":"a"}}`, `{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_fragments_snapshot_then_identical_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_fragments_then_distinct_complete_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"late_id_then_distinct_same_arguments_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_cumulative_final_string_then_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"explicit_id_change_overrides_fragment_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":","id":"a"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, } for _, tt := range tests { @@ -43,9 +52,9 @@ func TestGeminiParallelToolStreams(t *testing.T) { } b, err := json.Marshal(map[string]any{"candidates": []any{map[string]any{"content": map[string]any{"parts": parts}}}}) require.NoError(t, err) - upstream.WriteString("data: " + string(b) + "\n\n") + _, _ = upstream.WriteString("data: " + string(b) + "\n\n") } - upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") + _, _ = upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) svc := &GeminiMessagesCompatService{} diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go index 22f9914cdf..9b2edd9a6e 100644 --- a/backend/internal/service/gemini_tool_call_boundary.go +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -5,11 +5,18 @@ import ( "strings" ) -// geminiToolCallStartsNewBlock distinguishes call identity from function name. -// Calls with explicit IDs may contain incremental or cumulative arguments. -// Without IDs on both parts, a complete argument document marks the boundary -// before the next call, even when its name and arguments are identical. -func geminiToolCallStartsNewBlock(openID, openName, seenJSON string, fc map[string]any) bool { +// geminiToolCallBoundary tracks identity separately from the function name. +// Native object-valued args without IDs represent independent calls, including +// identical calls. String-valued fragments may end with a cumulative snapshot; +// preserve that snapshot's identity until its object-valued args arrive. +// Without IDs, a terminal snapshot and a new identical call immediately after +// fragments are indistinguishable; prefer the snapshot in that specific case. +type geminiToolCallBoundary struct { + upstreamID string + fragmented bool +} + +func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON string, fc map[string]any) bool { name, _ := fc["name"].(string) if strings.TrimSpace(name) == "" { name = "tool" @@ -18,8 +25,44 @@ func geminiToolCallStartsNewBlock(openID, openName, seenJSON string, fc map[stri return true } id, _ := fc["id"].(string) - if id != "" && openID != "" { - return id != openID + if id != "" && b.upstreamID != "" { + return id != b.upstreamID } - return json.Valid([]byte(seenJSON)) + if !json.Valid([]byte(seenJSON)) { + return false + } + // Keep the existing delta accumulator's duplicate/rewind behavior for a + // fragmented call. Do not deduplicate separate complete native calls. + if b.fragmented && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { + return false + } + return true +} + +func (b *geminiToolCallBoundary) observe(fc map[string]any, seenJSON string) { + if b.upstreamID == "" { + b.upstreamID, _ = fc["id"].(string) + } + if _, isString := fc["args"].(string); isString { + b.fragmented = b.fragmented || !json.Valid([]byte(seenJSON)) + } else { + // The terminal object snapshot has been consumed. A following + // anonymous complete object can now be another identical call. + b.fragmented = false + } +} + +func geminiToolCallArgsJSON(args any) string { + switch v := args.(type) { + case nil: + case string: + if strings.TrimSpace(v) != "" { + return v + } + default: + if b, err := json.Marshal(args); err == nil && len(b) > 0 { + return string(b) + } + } + return "{}" } From ddb7eac6330af796c92e940f0112d34c36a24811 Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:13:53 +0800 Subject: [PATCH 3/4] chore(go): upgrade to 1.27.4 to resolve security check --- .github/workflows/backend-ci.yml | 4 ++-- .github/workflows/release.yml | 2 +- .github/workflows/security-scan.yml | 2 +- DEV_GUIDE.md | 2 +- Dockerfile | 2 +- backend/Dockerfile | 2 +- backend/go.mod | 2 +- deploy/Dockerfile | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index d1b420aa94..751f1fb0fd 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -35,7 +35,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Unit tests working-directory: backend run: make test-unit @@ -75,7 +75,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: golangci-lint uses: golangci/golangci-lint-action@v9 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9f2ef5dd7d..b5780a6be5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -137,7 +137,7 @@ jobs: check-latest: false cache: false - name: Verify Go version - run: go version | grep -q 'go1.27.3' + run: go version | grep -q 'go1.27.4' - name: Restore target-specific Go cache id: go-cache uses: actions/cache/restore@v6 diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 703e10354a..19893aae97 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -23,7 +23,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Run govulncheck working-directory: backend run: | diff --git a/DEV_GUIDE.md b/DEV_GUIDE.md index 2f440d0f62..f01d59e48c 100644 --- a/DEV_GUIDE.md +++ b/DEV_GUIDE.md @@ -53,7 +53,7 @@ npm install -g pnpm ### CI 要求 -- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 +- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 - 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml` ### 本地测试命令 diff --git a/Dockerfile b/Dockerfile index 0242d6f13e..0c9e438850 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.3-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.21 ARG POSTGRES_IMAGE=postgres:18-alpine ARG GOPROXY=https://goproxy.cn,direct diff --git a/backend/Dockerfile b/backend/Dockerfile index 40e228cd37..52bcb43dcc 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.2-alpine +FROM golang:1.27.4-alpine WORKDIR /app diff --git a/backend/go.mod b/backend/go.mod index 91db5d03b4..8163fbea14 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/Wei-Shaw/sub2api -go 1.27.3 +go 1.27.4 require ( entgo.io/ent v0.14.5 diff --git a/deploy/Dockerfile b/deploy/Dockerfile index d5c580b466..e0e8fbf030 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -7,7 +7,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.2-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.20 ARG GOPROXY=https://goproxy.cn,direct ARG GOSUMDB=sum.golang.google.cn From ce026a2cbf1e1d366ddd64fe098e8a0334949a7b Mon Sep 17 00:00:00 2001 From: green_bean <62200636+little-greenbean@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:52:12 +0800 Subject: [PATCH 4/4] fix(gemini): retain complete string argument snapshots --- .../gemini_chat_completions_compat_service.go | 2 +- .../service/gemini_messages_compat_service.go | 2 +- .../service/gemini_parallel_tools_test.go | 8 ++++++ .../service/gemini_tool_call_boundary.go | 27 +++++++++---------- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index e89587866d..4626131b2e 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -764,7 +764,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom } delta := seenToolJSON.next(argsJSONText) - toolBoundary.observe(fc, seenToolJSON.seen.String()) + toolBoundary.observe(fc) if delta != "" { if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_delta", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index b0e6b308cd..4aee3e384d 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2428,7 +2428,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } delta := seenToolJSON.next(argsJSONText) - toolBoundary.observe(fc, seenToolJSON.seen.String()) + toolBoundary.observe(fc) if delta != "" { writeSSE(c.Writer, "content_block_delta", map[string]any{ "type": "content_block_delta", diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go index 66babba3b2..30145de0d3 100644 --- a/backend/internal/service/gemini_parallel_tools_test.go +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -37,6 +37,14 @@ func TestGeminiParallelToolStreams(t *testing.T) { {"late_id_then_distinct_same_arguments_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, {"anonymous_cumulative_final_string_then_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, {"explicit_id_change_overrides_fragment_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":","id":"a"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_duplicate_no_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_duplicate_first_id_only", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_duplicate_final_object_same_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"a"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_final_object_no_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"complete_strings_stable_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"a"}`}}, []string{`{"path":"a"}`}}, + {"complete_strings_distinct_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_snapshot_then_identical_native_call", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_late_id_then_new_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, } for _, tt := range tests { diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go index 9b2edd9a6e..5388e27e09 100644 --- a/backend/internal/service/gemini_tool_call_boundary.go +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -7,13 +7,13 @@ import ( // geminiToolCallBoundary tracks identity separately from the function name. // Native object-valued args without IDs represent independent calls, including -// identical calls. String-valued fragments may end with a cumulative snapshot; -// preserve that snapshot's identity until its object-valued args arrive. -// Without IDs, a terminal snapshot and a new identical call immediately after -// fragments are indistinguishable; prefer the snapshot in that specific case. +// identical calls. String-valued arguments use stream mode even when the first +// chunk is already complete JSON; retain duplicate strings and the terminal +// object snapshot in that call. Without IDs, a terminal snapshot and a new +// identical call after strings are indistinguishable; prefer the snapshot. type geminiToolCallBoundary struct { upstreamID string - fragmented bool + stringArgs bool } func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON string, fc map[string]any) bool { @@ -32,24 +32,21 @@ func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON str return false } // Keep the existing delta accumulator's duplicate/rewind behavior for a - // fragmented call. Do not deduplicate separate complete native calls. - if b.fragmented && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { + // string-argument call. Do not deduplicate separate complete native calls. + if b.stringArgs && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { return false } return true } -func (b *geminiToolCallBoundary) observe(fc map[string]any, seenJSON string) { +func (b *geminiToolCallBoundary) observe(fc map[string]any) { if b.upstreamID == "" { b.upstreamID, _ = fc["id"].(string) } - if _, isString := fc["args"].(string); isString { - b.fragmented = b.fragmented || !json.Valid([]byte(seenJSON)) - } else { - // The terminal object snapshot has been consumed. A following - // anonymous complete object can now be another identical call. - b.fragmented = false - } + // The representation determines the mode, not whether the first string + // happens to contain complete JSON. An object consumes the final snapshot, + // allowing the next anonymous native object to be an independent call. + _, b.stringArgs = fc["args"].(string) } func geminiToolCallArgsJSON(args any) string {