From c8c1e7e6496cbb400f4aed4fbf94836c5f0b98a6 Mon Sep 17 00:00:00 2001 From: Weicheng Yu Date: Fri, 6 Nov 2026 20:47:09 +0800 Subject: [PATCH 01/15] fix(openai): strip retry-after from client-forwarded capacity shed errors and cover ws passthrough --- .../handler/openai_gateway_handler.go | 9 +- .../service/openai_capacity_shed_test.go | 35 ++++++-- .../service/openai_gateway_passthrough.go | 87 +++++++++++++++++-- .../openai_ws_v2_passthrough_adapter.go | 3 + ...openai_ws_v2_passthrough_lifecycle_test.go | 33 +++++++ 5 files changed, 148 insertions(+), 19 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 3566e86132..d17067a4c8 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -2737,7 +2737,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { var oauth429FailoverState service.OpenAIOAuth429FailoverState wsAttemptMessage := append([]byte(nil), firstMessage...) waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { - if account == nil || failoverErr == nil || failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero() { + if account == nil || failoverErr == nil { + return false + } + if (failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero()) && !failoverErr.RequestScopedTransient { return false } retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) @@ -3558,7 +3561,9 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted) return } - copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + if !failoverErr.IsOpenAICapacityShed() { + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + } if failoverErr.IsOpenAIRequestBodyTooLarge() { service.SetOpsUpstreamError(c, http.StatusRequestEntityTooLarge, service.OpenAIRequestBodyTooLargeClientMessage, "") h.handleStreamingAwareError( diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index 6737e42cbd..7e2826e232 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -511,10 +511,11 @@ func TestOpenAIStreamProcessingFailureAfterOutputIsRecorded(t *testing.T) { // 依赖其原码解析重试延时)必须原样保留。 func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) { cases := []struct { - name string - payload string - wantChanged bool - wantContain string + name string + payload string + wantChanged bool + wantContain string + wantNotContain []string }{ { name: "failed事件嵌套code改写", @@ -541,10 +542,25 @@ func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) { wantContain: `"code":"server_error"`, }, { - name: "rate_limit不改写", - payload: `{"type":"response.failed","response":{"error":{"code":"rate_limit_exceeded","message":"try again in 3s"}}}`, - wantChanged: false, - wantContain: `"code":"rate_limit_exceeded"`, + name: "剥离error帧headers中的retry-after并清理空headers", + payload: `{"type":"error","error":{"code":"server_is_overloaded","headers":{"retry-after":"326","retry-after-ms":"326000"},"message":"Our servers are currently overloaded. Please try again later.","type":"service_unavailable_error"},"sequence_number":3}`, + wantChanged: true, + wantContain: `"code":"server_error"`, + wantNotContain: []string{`"retry-after"`, `"retry-after-ms"`, `"headers"`}, + }, + { + name: "上游中转已改写为server_error时仍剥离retry-after与直接重试延时字段", + payload: `{"type":"error","error":{"code":"server_error","headers":{"retry-after":"326","retry-after-ms":"326000","x-request-id":"req_123"},"retry_after":326,"resets_in_seconds":326,"message":"Our servers are currently overloaded. Please try again later.","type":"service_unavailable_error"},"sequence_number":3}`, + wantChanged: true, + wantContain: `"x-request-id":"req_123"`, + wantNotContain: []string{`"retry-after"`, `"retry-after-ms"`, `"retry_after"`, `"resets_in_seconds"`}, + }, + { + name: "rate_limit保留原码与retry-after", + payload: `{"type":"response.failed","response":{"error":{"code":"rate_limit_exceeded","headers":{"retry-after":"30"},"resets_in_seconds":30,"message":"try again in 30s"}}}`, + wantChanged: false, + wantContain: `"retry-after":"30"`, + wantNotContain: nil, }, { name: "普通server_error不改写", @@ -568,6 +584,9 @@ func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) { require.NotContains(t, string(out), "server_is_overloaded") require.NotContains(t, string(out), "slow_down") } + for _, forbidden := range tc.wantNotContain { + require.NotContains(t, string(out), forbidden) + } }) } } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index af55cc0900..64aa8c5899 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1325,14 +1325,37 @@ func logOpenAICapacityFailoverSuppressed( // 客户端内置的退避重试。 const openAICapacityShedRetryableClientCode = "server_error" +// openAICapacityShedRetryDelayFieldNames 是容量降载事件转发给客户端前需要剥离的 +// 重试延时字段。OpenAI 上游在容量降载事件中常附带 error.headers.retry-after / +// retry-after-ms(例如 326s),客户端(如 Codex CLI)一旦解析到这些字段就会用上游 +// 给出的数分钟等待覆盖客户端内置的毫秒级指数退避,导致客户端长时间挂起在 +// Reconnecting 状态。rate_limit_exceeded 不经过本函数,其配额重置时间不受影响。 +var openAICapacityShedRetryDelayFieldNames = []string{ + "retry_after", + "retry_after_ms", + "resets_at", + "resets_in_seconds", +} + +func isOpenAICapacityShedRetryAfterHeaderKey(key string) bool { + switch strings.ToLower(strings.TrimSpace(key)) { + case "retry-after", "retry-after-ms", "retry_after", "retry_after_ms": + return true + default: + return false + } +} + // sanitizeOpenAICapacityShedErrorCodeForClient 把即将写给下游客户端的 -// error / response.failed 事件中的容量降载错误码改写为客户端可重试的错误码。 +// error / response.failed 事件中的容量降载错误码改写为客户端可重试的错误码, +// 并剥离上游附带的 retry-after 重试延时字段。 // 走到转发这一步说明网关侧 failover 已不可用(流中途)或已用尽;保留原始降载码 -// 只会让客户端就地终止会话。错误消息原样保留;监控与账号状态判定都基于改写前 +// 只会让客户端就地终止会话,而保留数分钟级的 retry-after 则会让客户端跳过内置的 +// 毫秒级退避、长时间卡在重连倒计时。错误消息原样保留;监控与账号状态判定都基于改写前 // 的原始 payload,不受影响。rate_limit 等其他错误码一律不动(客户端依赖 // rate_limit_exceeded 原码解析重试延时)。 func sanitizeOpenAICapacityShedErrorCodeForClient(payload []byte) ([]byte, bool) { - if len(payload) == 0 || !gjson.ValidBytes(payload) || !isOpenAIUpstreamCapacityShedEvent(payload) { + if len(payload) == 0 || !bytes.Contains(payload, []byte(`"error"`)) || !gjson.ValidBytes(payload) || !isOpenAIUpstreamCapacityShedEvent(payload) { return payload, false } updated := payload @@ -1343,15 +1366,61 @@ func sanitizeOpenAICapacityShedErrorCodeForClient(payload []byte) ([]byte, bool) continue } code := strings.ToLower(strings.TrimSpace(gjson.GetBytes(updated, path).String())) - if code != "" && code != "server_is_overloaded" && code != "slow_down" { + if code != "" && code != "server_is_overloaded" && code != "slow_down" && code != openAICapacityShedRetryableClientCode { continue } - next, err := sjson.SetBytes(updated, path, openAICapacityShedRetryableClientCode) - if err != nil { - return payload, false + if code != openAICapacityShedRetryableClientCode { + next, err := sjson.SetBytes(updated, path, openAICapacityShedRetryableClientCode) + if err != nil { + return payload, false + } + updated = next + changed = true + } + headersPath := parent + ".headers" + if headersResult := gjson.GetBytes(updated, headersPath); headersResult.IsObject() { + var removeKeys []string + remainingKeys := 0 + headersResult.ForEach(func(k, _ gjson.Result) bool { + key := k.String() + if isOpenAICapacityShedRetryAfterHeaderKey(key) { + removeKeys = append(removeKeys, key) + } else { + remainingKeys++ + } + return true + }) + if len(removeKeys) > 0 { + if remainingKeys == 0 { + next, err := sjson.DeleteBytes(updated, headersPath) + if err != nil { + return payload, false + } + updated = next + } else { + for _, key := range removeKeys { + next, err := sjson.DeleteBytes(updated, headersPath+"."+key) + if err != nil { + return payload, false + } + updated = next + } + } + changed = true + } + } + for _, field := range openAICapacityShedRetryDelayFieldNames { + fieldPath := parent + "." + field + if !gjson.GetBytes(updated, fieldPath).Exists() { + continue + } + next, err := sjson.DeleteBytes(updated, fieldPath) + if err != nil { + return payload, false + } + updated = next + changed = true } - updated = next - changed = true } return updated, changed } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index e7d0a0d09b..32cea1fe95 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -650,6 +650,9 @@ func (c *openAIWSClientFrameConn) WriteFrame(ctx context.Context, msgType coderw if c.restoreToolNames != nil { payload = c.restoreToolNames(payload) } + if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(payload); changed { + payload = rewritten + } } return c.conn.Write(ctx, msgType, payload) } diff --git a/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go b/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go index 24afbeda09..f849077018 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go +++ b/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go @@ -902,3 +902,36 @@ func TestPassthroughLifecycle_SecondTurnTimeoutIsNotFailoverSafe(t *testing.T) { t.Fatal("second turn first semantic output was left unbounded") } } + +func TestPassthroughLifecycle_CapacityShedSanitizesErrorCodeAndStripsRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + controlCtx, cancelControl := context.WithCancelCause(context.Background()) + defer cancelControl(context.Canceled) + upstream := newStagedPassthroughConn() + upstream.Send(`{"type":"response.created","response":{"id":"resp_overload","model":"gpt-5.1"}}`) + upstream.Send(`{"type":"error","error":{"code":"server_is_overloaded","headers":{"retry-after":"326","retry-after-ms":"326000"},"message":"Our servers are currently overloaded. Please try again later.","type":"service_unavailable_error"},"sequence_number":3}`) + upstream.Send(`{"type":"response.failed","response":{"id":"resp_overload","model":"gpt-5.1","status":"failed","error":{"code":"server_is_overloaded","headers":{"retry-after":"326","retry-after-ms":"326000"},"message":"Our servers are currently overloaded. Please try again later."}},"sequence_number":4}`) + server, _ := startPassthroughLifecycleServer(t, controlCtx, newPassthroughLifecycleService(passthroughLifecycleConfig(), upstream), passthroughLifecycleAccount()) + defer server.Close() + clientConn := dialPassthroughLifecycleClient(t, server) + defer func() { _ = clientConn.CloseNow() }() + + created, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "response.created", gjson.GetBytes(created, "type").String()) + + errFrame, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "error", gjson.GetBytes(errFrame, "type").String()) + require.Equal(t, "server_error", gjson.GetBytes(errFrame, "error.code").String()) + require.False(t, gjson.GetBytes(errFrame, "error.headers").Exists()) + require.NotContains(t, string(errFrame), "retry-after") + + failedFrame, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "response.failed", gjson.GetBytes(failedFrame, "type").String()) + require.Equal(t, "server_error", gjson.GetBytes(failedFrame, "response.error.code").String()) + require.False(t, gjson.GetBytes(failedFrame, "response.error.headers").Exists()) + require.NotContains(t, string(failedFrame), "retry-after") +} + From c85fd1c87314b20a93e87838a75a5968152b8384 Mon Sep 17 00:00:00 2001 From: Weicheng Yu Date: Sun, 8 Nov 2026 12:07:21 +0800 Subject: [PATCH 02/15] test: isolate service allocation assertions from background workers The full CI suite exposed the same process-wide allocation counter interference in signed thinking-history filtering. Reuse one subprocess helper for all six service allocation tests while retaining the original thresholds and assertions. Verify the named child test actually executed and propagate its failures. Validation: allocation tests passed twice; related precheck, model mapping, Gemini, compaction and tool schema tests passed; golangci-lint 2.14.0 reported 0 issues. A copying-parser negative control still fails the zero-allocation assertion. --- .../account_model_mapping_signature_test.go | 3 ++ .../service/allocation_isolation_test.go | 31 +++++++++++++++++++ .../gateway_thinking_filter_precheck_test.go | 3 ++ .../service/gemini_text_delta_test.go | 3 ++ .../openai_compact_body_signal_test.go | 3 ++ .../openai_responses_orphan_precheck_test.go | 15 +-------- .../openai_responses_tool_schema_test.go | 6 ++-- 7 files changed, 48 insertions(+), 16 deletions(-) create mode 100644 backend/internal/service/allocation_isolation_test.go diff --git a/backend/internal/service/account_model_mapping_signature_test.go b/backend/internal/service/account_model_mapping_signature_test.go index a83c05dc81..2444e37fe6 100644 --- a/backend/internal/service/account_model_mapping_signature_test.go +++ b/backend/internal/service/account_model_mapping_signature_test.go @@ -81,6 +81,9 @@ func TestModelMappingSignature_EmptyIsZero(t *testing.T) { } func TestModelMappingSignature_DoesNotAllocate(t *testing.T) { + if runAllocationTestInSubprocess(t) { + return + } mapping := map[string]any{ "claude-sonnet": "sonnet-a", "claude-opus": "opus-a", diff --git a/backend/internal/service/allocation_isolation_test.go b/backend/internal/service/allocation_isolation_test.go new file mode 100644 index 0000000000..2274487f43 --- /dev/null +++ b/backend/internal/service/allocation_isolation_test.go @@ -0,0 +1,31 @@ +package service + +import ( + "os" + "os/exec" + "regexp" + "testing" + + "github.com/stretchr/testify/require" +) + +// runAllocationTestInSubprocess isolates process-wide AllocsPerRun counters +// from background workers started by other service tests. The child runs the +// original assertions; the parent returns after checking the child's result. +func runAllocationTestInSubprocess(t *testing.T) bool { + t.Helper() + const isolatedEnv = "SUB2API_TEST_ISOLATED_ALLOCATION" + if os.Getenv(isolatedEnv) == t.Name() { + return false + } + binary, err := os.Executable() + require.NoError(t, err) + command := exec.CommandContext(t.Context(), binary, + "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", + "-test.count=1", "-test.timeout=30s", "-test.v") + command.Env = append(os.Environ(), isolatedEnv+"="+t.Name()) + output, err := command.CombinedOutput() + require.NoError(t, err, "%s", output) + require.Contains(t, string(output), "--- PASS: "+t.Name()+" ", "allocation test must execute in the child") + return true +} diff --git a/backend/internal/service/gateway_thinking_filter_precheck_test.go b/backend/internal/service/gateway_thinking_filter_precheck_test.go index b7cb36c4d9..ce28c77809 100644 --- a/backend/internal/service/gateway_thinking_filter_precheck_test.go +++ b/backend/internal/service/gateway_thinking_filter_precheck_test.go @@ -75,6 +75,9 @@ func signedThinkingHistoryBody() []byte { } func TestFilterThinkingBlocksSignedHistorySkipsDecode(t *testing.T) { + if runAllocationTestInSubprocess(t) { + return + } body := signedThinkingHistoryBody() allocs := testing.AllocsPerRun(5, func() { got := filterThinkingBlocksInternal(body, false) diff --git a/backend/internal/service/gemini_text_delta_test.go b/backend/internal/service/gemini_text_delta_test.go index d8a7bcf500..5240861cb7 100644 --- a/backend/internal/service/gemini_text_delta_test.go +++ b/backend/internal/service/gemini_text_delta_test.go @@ -49,6 +49,9 @@ func TestGeminiTextDeltaMatchesLegacy(t *testing.T) { } func TestGeminiTextDeltaIncrementalAllocationsStayLinear(t *testing.T) { + if runAllocationTestInSubprocess(t) { + return + } chunk := strings.Repeat("x", 100) const chunks = 2000 allocs := testing.AllocsPerRun(5, func() { diff --git a/backend/internal/service/openai_compact_body_signal_test.go b/backend/internal/service/openai_compact_body_signal_test.go index ef672ba16b..8656aa3434 100644 --- a/backend/internal/service/openai_compact_body_signal_test.go +++ b/backend/internal/service/openai_compact_body_signal_test.go @@ -119,6 +119,9 @@ func TestWebSocketCompatibilityNormalizesTriggerAfterPairedOutputCleanup(t *test } func TestNormalizeCompactionTriggerInputOrder_PrecheckKeepsContract(t *testing.T) { + if runAllocationTestInSubprocess(t) { + return + } plain := []byte(`{"model":"gpt-5","input":[{"type":"message","role":"user","content":"` + strings.Repeat("x", 4096) + `"}]}`) allocs := testing.AllocsPerRun(10, func() { got, changed, err := NormalizeCompactionTriggerInputOrder(plain) diff --git a/backend/internal/service/openai_responses_orphan_precheck_test.go b/backend/internal/service/openai_responses_orphan_precheck_test.go index f116db8eaf..51778a1958 100644 --- a/backend/internal/service/openai_responses_orphan_precheck_test.go +++ b/backend/internal/service/openai_responses_orphan_precheck_test.go @@ -1,8 +1,6 @@ package service import ( - "os" - "os/exec" "strings" "testing" @@ -128,18 +126,7 @@ func TestOpenAIResponsesOrphanPrecheckCompatibilityErrors(t *testing.T) { } func TestOpenAIResponsesOrphanPrecheckLargeEscapedContent(t *testing.T) { - // AllocsPerRun counts allocations across the whole process. Background - // workers started by other service tests must not pollute this measurement. - const isolatedEnv = "SUB2API_TEST_ORPHAN_PRECHECK_ALLOCS" - if os.Getenv(isolatedEnv) != "1" { - binary, err := os.Executable() - require.NoError(t, err) - command := exec.CommandContext(t.Context(), binary, - "-test.run=^TestOpenAIResponsesOrphanPrecheckLargeEscapedContent$", - "-test.count=1", "-test.timeout=30s") - command.Env = append(os.Environ(), isolatedEnv+"=1") - output, err := command.CombinedOutput() - require.NoError(t, err, "%s", output) + if runAllocationTestInSubprocess(t) { return } diff --git a/backend/internal/service/openai_responses_tool_schema_test.go b/backend/internal/service/openai_responses_tool_schema_test.go index 7b1714e30d..26bf2da82a 100644 --- a/backend/internal/service/openai_responses_tool_schema_test.go +++ b/backend/internal/service/openai_responses_tool_schema_test.go @@ -587,6 +587,9 @@ func buildToolSchemaNullTypeBody(t *testing.T, hits int) []byte { // 构造请求可以塞进百万级命中,会被放大成 TB 级 memcpy。这里用分配次数锁死该行为: // 命中数放大 500 倍,分配次数不得随之增长。 func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits(t *testing.T) { + if runAllocationTestInSubprocess(t) { + return + } small := buildToolSchemaNullTypeBody(t, 4) large := buildToolSchemaNullTypeBody(t, 2000) @@ -598,8 +601,7 @@ func TestSanitizeOpenAIResponsesToolParameterTypes_RewriteCountIndependentOfHits }) // 命中切片扩容是对数级,留出充裕余量;线性写法在这里会是 2000 量级。 - // 干净环境实测 large 约 17 allocs,200 是 10 倍余量,同时容忍 CI 慢 pod 上 - // 包内后台 goroutine(日志/ticker)对进程级 Mallocs 的噪声污染。 + // 干净环境实测 large 约 17 allocs,200 是 10 倍余量。 require.Less(t, largeAllocs, 200.0, "分配次数随命中数线性增长,说明退回了逐路径全量重写 (small=%v large=%v)", smallAllocs, largeAllocs) From 905893ca9ecdac6caa26ffa99513161794ce8b97 Mon Sep 17 00:00:00 2001 From: dzolv Date: Wed, 2 Dec 2026 16:23:39 +0800 Subject: [PATCH 03/15] fix(openai): ignore standalone named delegation in continuation checks and reset WS HTTP bridge on window rollover --- .../service/openai_responses_input_compat.go | 7 +- .../service/openai_tool_continuation.go | 33 +++- .../service/openai_tool_continuation_test.go | 38 ++++ .../service/openai_ws_forwarder_ingress.go | 117 +++++++++--- .../openai_ws_forwarder_ingress_test.go | 16 ++ .../service/openai_ws_forwarder_payload.go | 29 ++- .../openai_ws_http_bridge_resume_test.go | 169 ++++++++++++++++++ 7 files changed, 371 insertions(+), 38 deletions(-) diff --git a/backend/internal/service/openai_responses_input_compat.go b/backend/internal/service/openai_responses_input_compat.go index 29619bc4dd..f7d33fa87c 100644 --- a/backend/internal/service/openai_responses_input_compat.go +++ b/backend/internal/service/openai_responses_input_compat.go @@ -50,8 +50,11 @@ func sanitizeOpenAIResponsesOrphanToolOutputs(reqBody map[string]any, input []an // named function outputs without a preceding function call. Preserve // their native type, namespace and output instead of silently dropping // the request that started the turn. - if callID == "" && strings.TrimSpace(firstNonEmptyString(item["type"])) == "function_call_output" && - strings.TrimSpace(firstNonEmptyString(item["name"])) != "" { + if isStandaloneNamedFunctionCallOutput( + firstNonEmptyString(item["type"]), + callID, + firstNonEmptyString(item["name"]), + ) { normalized = append(normalized, rawItem) continue } diff --git a/backend/internal/service/openai_tool_continuation.go b/backend/internal/service/openai_tool_continuation.go index 3b2356c971..4e4f16baf6 100644 --- a/backend/internal/service/openai_tool_continuation.go +++ b/backend/internal/service/openai_tool_continuation.go @@ -50,6 +50,14 @@ func isCodexToolCallOutputItemType(typ string) bool { } } +// isStandaloneNamedFunctionCallOutput 判断是否为 Codex 注入的带名称、无 call_id 的独立输入(如任务派发 create_thread)。 +// 此类项属于客户端注入的独立上下文而非需要前置工具调用配对的工具结果。 +func isStandaloneNamedFunctionCallOutput(itemType, callID, name string) bool { + return strings.TrimSpace(callID) == "" && + strings.TrimSpace(itemType) == "function_call_output" && + strings.TrimSpace(name) != "" +} + // NeedsToolContinuation 判定请求是否需要工具调用续链处理。 // 满足以下任一信号即视为续链:previous_response_id、input 内包含工具输出/item_reference、 // 或显式声明 tools/tool_choice。 @@ -112,9 +120,13 @@ func AnalyzeToolContinuationSignals(reqBody map[string]any) ToolContinuationSign signals.HasToolCallContext = true } case isCodexToolCallOutputItemType(itemType): - signals.HasFunctionCallOutput = true callID, _ := itemMap["call_id"].(string) callID = strings.TrimSpace(callID) + name, _ := itemMap["name"].(string) + if isStandaloneNamedFunctionCallOutput(itemType, callID, name) { + continue + } + signals.HasFunctionCallOutput = true if callID == "" { signals.HasFunctionCallOutputMissingCallID = true continue @@ -175,8 +187,11 @@ func ValidateFunctionCallOutputContextBytes(body []byte) FunctionCallOutputValid itemType := item.Get("type").String() switch { case isCodexToolCallOutputItemType(itemType): - result.HasFunctionCallOutput = true callID := strings.TrimSpace(item.Get("call_id").String()) + if isStandaloneNamedFunctionCallOutput(itemType, callID, item.Get("name").String()) { + return true + } + result.HasFunctionCallOutput = true if callID == "" { result.HasFunctionCallOutputMissingCallID = true return true @@ -249,8 +264,11 @@ func AnalyzeToolCallOutputContextCoverageBytes(body []byte) ToolCallOutputContex itemType := item.Get("type").String() switch { case isCodexToolCallOutputItemType(itemType): - coverage.HasFunctionCallOutput = true callID := strings.TrimSpace(item.Get("call_id").String()) + if isStandaloneNamedFunctionCallOutput(itemType, callID, item.Get("name").String()) { + return + } + coverage.HasFunctionCallOutput = true if callID == "" { missingCallID = true return @@ -323,6 +341,11 @@ func ValidateFunctionCallOutputContext(reqBody map[string]any) FunctionCallOutpu itemType, _ := itemMap["type"].(string) switch { case isCodexToolCallOutputItemType(itemType): + callID, _ := itemMap["call_id"].(string) + name, _ := itemMap["name"].(string) + if isStandaloneNamedFunctionCallOutput(itemType, callID, name) { + continue + } result.HasFunctionCallOutput = true case isCodexToolCallContextItemType(itemType): callID, _ := itemMap["call_id"].(string) @@ -351,6 +374,10 @@ func ValidateFunctionCallOutputContext(reqBody map[string]any) FunctionCallOutpu case isCodexToolCallOutputItemType(itemType): callID, _ := itemMap["call_id"].(string) callID = strings.TrimSpace(callID) + name, _ := itemMap["name"].(string) + if isStandaloneNamedFunctionCallOutput(itemType, callID, name) { + continue + } if callID == "" { result.HasFunctionCallOutputMissingCallID = true continue diff --git a/backend/internal/service/openai_tool_continuation_test.go b/backend/internal/service/openai_tool_continuation_test.go index 460a659c2e..b8769894b6 100644 --- a/backend/internal/service/openai_tool_continuation_test.go +++ b/backend/internal/service/openai_tool_continuation_test.go @@ -51,6 +51,9 @@ func TestHasFunctionCallOutput(t *testing.T) { "input": []any{map[string]any{"type": typ}}, }), typ) } + require.False(t, HasFunctionCallOutput(map[string]any{ + "input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}, + })) require.False(t, HasFunctionCallOutput(map[string]any{ "input": "text", })) @@ -100,6 +103,9 @@ func TestHasFunctionCallOutputMissingCallID(t *testing.T) { require.True(t, HasFunctionCallOutputMissingCallID(map[string]any{ "input": []any{map[string]any{"type": "tool_search_output"}}, })) + require.False(t, HasFunctionCallOutputMissingCallID(map[string]any{ + "input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}, + })) require.False(t, HasFunctionCallOutputMissingCallID(map[string]any{ "input": []any{map[string]any{"type": "tool_search_output", "call_id": "call_1"}}, })) @@ -134,6 +140,10 @@ func TestValidateFunctionCallOutputContextBytesMatchesMapValidation(t *testing.T name: "missing_call_id", body: map[string]any{"input": []any{map[string]any{"type": "function_call_output"}}}, }, + { + name: "named_standalone_delegation_without_call_id", + body: map[string]any{"input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}}, + }, { name: "call_id_without_reference", body: map[string]any{"input": []any{map[string]any{"type": "function_call_output", "call_id": "call_1"}}}, @@ -263,6 +273,34 @@ func TestAnalyzeToolCallOutputContextCoverageBytes(t *testing.T) { hasOutput: true, coversAllIDs: false, }, + { + name: "standalone_named_delegation_only_does_not_require_replay", + body: map[string]any{"input": []any{ + map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}, + map[string]any{"type": "message", "role": "user", "content": "summary"}, + }}, + hasOutput: false, + coversAllIDs: false, + }, + { + name: "standalone_named_delegation_with_covered_output", + body: map[string]any{"input": []any{ + map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}, + map[string]any{"type": "function_call", "call_id": "call_a"}, + map[string]any{"type": "function_call_output", "call_id": "call_a"}, + }}, + hasOutput: true, + coversAllIDs: true, + }, + { + name: "standalone_named_delegation_with_unpaired_output_requires_replay", + body: map[string]any{"input": []any{ + map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}, + map[string]any{"type": "function_call_output", "call_id": "call_b"}, + }}, + hasOutput: true, + coversAllIDs: false, + }, { name: "mixed_context_and_reference_cover_all", body: map[string]any{"input": []any{ diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 81d4f24dd7..909100ccec 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -202,6 +202,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( requestedReasoningEffort *string } ingressSessionOriginalModel := "" + activeTurnMetadata := "" + initialHandshakeWindowID := "" + if c != nil { + activeTurnMetadata = strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader)) + initialHandshakeWindowID = strings.TrimSpace(c.GetHeader("x-codex-window-id")) + } applyPayloadMutation := func(current []byte, path string, value any) ([]byte, error) { next, err := sjson.SetBytes(current, path, value) @@ -318,8 +324,16 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( nil, ) } - if turnMetadata := strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader)); turnMetadata != "" { - next, setErr := applyPayloadMutation(normalized, "client_metadata."+openAIWSTurnMetadataHeader, turnMetadata) + frameTurnMetadata := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata."+openAIWSTurnMetadataHeader).String()) + frameWindowID := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata.x-codex-window-id").String()) + if frameTurnMetadata != "" { + activeTurnMetadata = frameTurnMetadata + } else if frameWindowID != "" { + if activeTurnMetadata != "" && strings.TrimSpace(gjson.Get(activeTurnMetadata, "window_id").String()) != frameWindowID { + activeTurnMetadata = "" + } + } else if activeTurnMetadata != "" { + next, setErr := applyPayloadMutation(normalized, "client_metadata."+openAIWSTurnMetadataHeader, activeTurnMetadata) if setErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", setErr) } @@ -594,6 +608,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } defer history.close() historyLost := false + lastBridgeWindowID := initialHandshakeWindowID var bridgeReplayInput []json.RawMessage bridgeReplayInputExists := false var bridgeAccountFailoverInput []json.RawMessage @@ -615,6 +630,40 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if c != nil && sessionHash != "" { c.Set(openAIWSIngressSessionHashContextKey, sessionHash) } + boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary( + currentBridgePayload.payloadRaw, + lastBridgeWindowID, + ) + if boundaryErr != nil { + return fmt.Errorf("normalize Codex websocket http bridge context-window boundary: %w", boundaryErr) + } + if contextWindowBoundary.Changed { + if contextWindowBoundary.PreviousResponseIDRemoved { + responsesLite := isOpenAIResponsesLiteWebSocketPayload(boundaryPayload) + if compatBody, compatChanged, compatErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, boundaryPayload, account, responsesLite); compatErr != nil { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatErr) + } else if compatChanged { + boundaryPayload = compatBody + } + } + currentBridgePayload.payloadRaw = boundaryPayload + currentBridgePayload.payloadBytes = len(boundaryPayload) + currentBridgePayload.previousResponseID = "" + historyLost = false + bridgeReplayInput = nil + bridgeReplayInputExists = false + bridgeAccountFailoverInput = nil + bridgeAccountFailoverInputExists = false + history.resize(0) + logOpenAIWSModeInfo( + "ingress_ws_http_bridge_context_window_changed account_id=%d turn=%d action=reset_bridge_replay_state previous_window_id=%s current_window_id=%s previous_response_id_removed=%v", + account.ID, + turn, + truncateOpenAIWSLogValue(lastBridgeWindowID, openAIWSIDValueMaxLen), + truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen), + contextWindowBoundary.PreviousResponseIDRemoved, + ) + } // 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。 // 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。 if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, sessionHash); len(invalidDigests) > 0 { @@ -813,6 +862,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // publishing it by session hash would leak it to independent bridges. turnState = bridgeTurnState } + if contextWindowBoundary.WindowID != "" { + lastBridgeWindowID = contextWindowBoundary.WindowID + } responseID := strings.TrimSpace(result.RequestID) if responseID != "" && stateStore != nil { ttl := s.openAIWSResponseStickyTTL() @@ -1444,7 +1496,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( turnPrevRecoveryTried := false lastTurnFinishedAt := time.Time{} lastTurnResponseID := "" - lastTurnWindowID := "" + lastTurnWindowID := initialHandshakeWindowID lastTurnPayload := []byte(nil) var lastTurnStrictState *openAIWSIngressPreviousTurnStrictState lastTurnReplayInput := []json.RawMessage(nil) @@ -1576,6 +1628,40 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } skipBeforeTurn = false + boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary( + currentPayload, + lastTurnWindowID, + ) + if boundaryErr != nil { + return fmt.Errorf("normalize Codex websocket context-window boundary: %w", boundaryErr) + } + if contextWindowBoundary.Changed { + if contextWindowBoundary.PreviousResponseIDRemoved { + responsesLite := isOpenAIResponsesLiteWebSocketPayload(boundaryPayload) + if compatBody, compatChanged, compatErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, boundaryPayload, account, responsesLite); compatErr != nil { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatErr) + } else if compatChanged { + boundaryPayload = compatBody + } + } + currentPayload = boundaryPayload + currentPayloadBytes = len(boundaryPayload) + lastTurnResponseID = "" + lastTurnPayload = nil + lastTurnStrictState = nil + lastTurnReplayInput = nil + lastTurnReplayInputExists = false + lastTurnReplayInputComplete = false + logOpenAIWSModeInfo( + "ingress_ws_context_window_changed account_id=%d turn=%d conn_id=%s action=break_previous_response_chain previous_window_id=%s current_window_id=%s previous_response_id_removed=%v", + account.ID, + turn, + truncateOpenAIWSLogValue(sessionConnID, openAIWSIDValueMaxLen), + truncateOpenAIWSLogValue(lastTurnWindowID, openAIWSIDValueMaxLen), + truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen), + contextWindowBoundary.PreviousResponseIDRemoved, + ) + } // 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。 // 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。 if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, sessionHash); len(invalidDigests) > 0 { @@ -1590,33 +1676,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( lastTurnReplayInput, _ = stripOpenAIInvalidEncryptedContentFromReplayItems(lastTurnReplayInput, invalidDigests) } } - boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary( - currentPayload, - lastTurnWindowID, - ) - if boundaryErr != nil { - return fmt.Errorf("normalize Codex websocket context-window boundary: %w", boundaryErr) - } - if contextWindowBoundary.Changed { - currentPayload = boundaryPayload - currentPayloadBytes = len(boundaryPayload) - logOpenAIWSModeInfo( - "ingress_ws_context_window_changed account_id=%d turn=%d conn_id=%s action=break_previous_response_chain previous_window_id=%s current_window_id=%s previous_response_id_removed=%v", - account.ID, - turn, - truncateOpenAIWSLogValue(sessionConnID, openAIWSIDValueMaxLen), - truncateOpenAIWSLogValue(lastTurnWindowID, openAIWSIDValueMaxLen), - truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen), - contextWindowBoundary.PreviousResponseIDRemoved, - ) - } currentPreviousResponseID := openAIWSPayloadStringFromRaw(currentPayload, "previous_response_id") expectedPrev := strings.TrimSpace(lastTurnResponseID) - if contextWindowBoundary.Changed { - // A context-window rollover is a new Responses root. Do not infer a - // continuation anchor from the response produced in the old window. - expectedPrev = "" - } toolSignals := ToolContinuationSignals{ HasFunctionCallOutput: openAIWSRawPayloadHasToolCallOutput(currentPayload), } diff --git a/backend/internal/service/openai_ws_forwarder_ingress_test.go b/backend/internal/service/openai_ws_forwarder_ingress_test.go index 915a4edf24..bca0fc3630 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_test.go @@ -1024,6 +1024,22 @@ func TestOpenAIWSRawPayloadHasToolCallOutput(t *testing.T) { payload := []byte(`{"input":[{"type":"input_text","text":"hello"}]}`) require.False(t, openAIWSRawPayloadHasToolCallOutput(payload)) }) + + t.Run("standalone_named_delegation_output_ignored", func(t *testing.T) { + t.Parallel() + payload := []byte(`{"input":[{"type":"function_call_output","name":"create_thread","output":"delegated"}]}`) + require.False(t, openAIWSRawPayloadHasToolCallOutput(payload)) + items := []json.RawMessage{ + json.RawMessage(`{"type":"function_call_output","name":"create_thread","output":"delegated"}`), + } + require.False(t, openAIWSRawItemsHasFunctionCallOutput(items)) + pairedItems := []json.RawMessage{ + json.RawMessage(`{"type":"function_call_output","name":"create_thread","output":"delegated"}`), + json.RawMessage(`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"}`), + json.RawMessage(`{"type":"function_call_output","call_id":"call_1","output":"ok"}`), + } + require.True(t, openAIWSRawItemsHaveToolCallContextForOutputs(pairedItems)) + }) } func TestSetOpenAIWSPayloadInputSequence(t *testing.T) { diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index fc50bc5515..21711a9f2e 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -645,9 +645,18 @@ func openAIWSRawItemsHasPrefix(items []json.RawMessage, prefix []json.RawMessage func openAIWSRawItemsHasFunctionCallOutput(items []json.RawMessage) bool { for _, item := range items { - if isCodexToolCallOutputItemType(gjson.GetBytes(item, "type").String()) { - return true + itemType := gjson.GetBytes(item, "type").String() + if !isCodexToolCallOutputItemType(itemType) { + continue } + if isStandaloneNamedFunctionCallOutput( + itemType, + gjson.GetBytes(item, "call_id").String(), + gjson.GetBytes(item, "name").String(), + ) { + continue + } + return true } return false } @@ -667,6 +676,9 @@ func openAIWSRawItemsHaveToolCallContextForOutputs(items []json.RawMessage) bool contextCallIDs[callID] = struct{}{} } case isCodexToolCallOutputItemType(itemType): + if isStandaloneNamedFunctionCallOutput(itemType, callID, gjson.GetBytes(item, "name").String()) { + continue + } if callID == "" { return false } @@ -729,14 +741,21 @@ func openAIWSRawPayloadHasToolCallOutput(payload []byte) bool { } if input.IsArray() { for _, item := range input.Array() { - if isCodexToolCallOutputItemType(item.Get("type").String()) { - return true + itemType := item.Get("type").String() + if !isCodexToolCallOutputItemType(itemType) { + continue } + if isStandaloneNamedFunctionCallOutput(itemType, item.Get("call_id").String(), item.Get("name").String()) { + continue + } + return true } return false } if input.Type == gjson.JSON { - return isCodexToolCallOutputItemType(input.Get("type").String()) + itemType := input.Get("type").String() + return isCodexToolCallOutputItemType(itemType) && + !isStandaloneNamedFunctionCallOutput(itemType, input.Get("call_id").String(), input.Get("name").String()) } return false } diff --git a/backend/internal/service/openai_ws_http_bridge_resume_test.go b/backend/internal/service/openai_ws_http_bridge_resume_test.go index b18ac294e4..22e550fce4 100644 --- a/backend/internal/service/openai_ws_http_bridge_resume_test.go +++ b/backend/internal/service/openai_ws_http_bridge_resume_test.go @@ -263,3 +263,172 @@ func TestOpenAIWSHTTPBridgeLaterTurn429RetriesCurrentTurnOnReplacementAccount(t require.Equal(t, scopeCodexAccountIdentityValue(&nextAccount, 0, "thread", "client-thread"), gjson.GetBytes(upstream.bodies[2], "client_metadata.thread_id").String()) require.Empty(t, upstream.requests[2].Header.Get(openAIWSTurnStateHeader)) } + +func TestOpenAIWSHTTPBridgeDelegatedSessionCompactionDoesNotReplayOldWindowHistory(t *testing.T) { + gin.SetMode(gin.TestMode) + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_first\",\"output\":[{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"first-ok\"}]},{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"inspect\",\"arguments\":\"{}\"}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n", + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_second\",\"output\":[{\"id\":\"msg_2\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"second-ok\"}]}],\"usage\":{\"input_tokens\":2,\"output_tokens\":1}}}\n\n", + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_third\",\"output\":[{\"id\":\"msg_3\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"third-ok\"}]}],\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n", + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fourth\",\"output\":[{\"id\":\"msg_4\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"fourth-ok\"}]}],\"usage\":{\"input_tokens\":4,\"output_tokens\":1}}}\n\n", + )), + }, + }} + svc := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: upstream, + cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), + } + account := &Account{ + ID: 131, Name: "bridge-compaction", Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, Concurrency: 1, + Extra: map[string]any{"openai_oauth_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge}, + Credentials: map[string]any{"chatgpt_account_id": "account-a", "chatgpt_user_id": "user-a"}, + } + + serverErrCh := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := websocket.Accept(w, r, nil) + if err != nil { + serverErrCh <- err + return + } + defer func() { _ = conn.CloseNow() }() + + rec := httptest.NewRecorder() + ginCtx, _ := gin.CreateTestContext(rec) + ginCtx.Request = r.Clone(r.Context()) + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, readErr := conn.Read(readCtx) + cancel() + if readErr != nil { + serverErrCh <- readErr + return + } + serverErrCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token-a", firstMessage, nil) + })) + defer wsServer.Close() + + dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + clientConn, _, err := websocket.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), &websocket.DialOptions{ + HTTPHeader: http.Header{ + openAIWSTurnMetadataHeader: []string{`{"window_id":"window-0"}`}, + }, + }) + cancel() + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + + // Turn 1: delegated session starts in window-0 with create_thread (no call_id). + writeCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","input":[{"type":"function_call_output","name":"create_thread","output":"delegated task"},{"role":"user","content":"first-window-msg"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _, completed1, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_first", gjson.GetBytes(completed1, "response.id").String()) + + // Turn 2: normal tool continuation in window-0. + writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","previous_response_id":"resp_first","input":[{"type":"function_call_output","call_id":"call_1","output":"tool-ok"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + _, completed2, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_second", gjson.GetBytes(completed2, "response.id").String()) + + // Turn 3: context compaction replaces history, omits previous_response_id, + // retains create_thread (without call_id), and rotates window_id to window-1. + writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","client_metadata":{"x-codex-turn-metadata":"{\"window_id\":\"window-1\"}"},"input":[{"type":"function_call_output","name":"create_thread","output":"delegated task"},{"role":"user","content":"compacted-summary"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + _, completed3, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_third", gjson.GetBytes(completed3, "response.id").String()) + + // Turn 4: follow-up turn in window-1 omitting client_metadata must stay in window-1 + // and stitch only from Turn 3's compacted root. + writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","previous_response_id":"resp_third","input":[{"role":"user","content":"after-compaction"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + _, completed4, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_fourth", gjson.GetBytes(completed4, "response.id").String()) + _ = clientConn.Close(websocket.StatusNormalClosure, "done") + + select { + case proxyErr := <-serverErrCh: + require.NoError(t, proxyErr) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for bridge completion") + } + + require.Len(t, upstream.bodies, 4) + // Turn 2 stitched Turn 1 history + call_1 + tool-ok. + require.Contains(t, string(upstream.bodies[1]), "first-window-msg") + require.Contains(t, string(upstream.bodies[1]), "call_1") + + // Turn 3 (compacted window-1) must NOT replay old window-0 history ("first-window-msg" or "call_1"), + // and must preserve frame-level window-1 instead of overwriting it with handshake window-0. + scopedWindow1 := scopeCodexAccountIdentityValue(account, 0, "window", "window-1") + require.NotContains(t, string(upstream.bodies[2]), "first-window-msg") + require.NotContains(t, string(upstream.bodies[2]), "call_1") + require.Contains(t, string(upstream.bodies[2]), "compacted-summary") + require.Equal(t, scopedWindow1, gjson.Get(gjson.GetBytes(upstream.bodies[2], "client_metadata.x-codex-turn-metadata").String(), "window_id").String()) + + // Turn 4 (continuation in window-1) stitches from Turn 3's compacted history and stays on window-1. + require.NotContains(t, string(upstream.bodies[3]), "first-window-msg") + require.NotContains(t, string(upstream.bodies[3]), "call_1") + require.Contains(t, string(upstream.bodies[3]), "compacted-summary") + require.Contains(t, string(upstream.bodies[3]), "after-compaction") + require.Equal(t, scopedWindow1, gjson.Get(gjson.GetBytes(upstream.bodies[3], "client_metadata.x-codex-turn-metadata").String(), "window_id").String()) +} From 57a990fafa327decc9df7ab87b508023d7fbd273 Mon Sep 17 00:00:00 2001 From: dzolv Date: Thu, 3 Dec 2026 11:05:52 +0800 Subject: [PATCH 04/15] fix(openai): keep HTTP handler missing-call-id validation and scope handshake window_id --- .../service/openai_tool_continuation.go | 14 +--------- .../service/openai_ws_forwarder_ingress.go | 20 +++++++++++--- .../service/openai_ws_forwarder_payload.go | 26 +++++++++++++++++++ 3 files changed, 43 insertions(+), 17 deletions(-) diff --git a/backend/internal/service/openai_tool_continuation.go b/backend/internal/service/openai_tool_continuation.go index 4e4f16baf6..c85e731947 100644 --- a/backend/internal/service/openai_tool_continuation.go +++ b/backend/internal/service/openai_tool_continuation.go @@ -187,11 +187,8 @@ func ValidateFunctionCallOutputContextBytes(body []byte) FunctionCallOutputValid itemType := item.Get("type").String() switch { case isCodexToolCallOutputItemType(itemType): - callID := strings.TrimSpace(item.Get("call_id").String()) - if isStandaloneNamedFunctionCallOutput(itemType, callID, item.Get("name").String()) { - return true - } result.HasFunctionCallOutput = true + callID := strings.TrimSpace(item.Get("call_id").String()) if callID == "" { result.HasFunctionCallOutputMissingCallID = true return true @@ -341,11 +338,6 @@ func ValidateFunctionCallOutputContext(reqBody map[string]any) FunctionCallOutpu itemType, _ := itemMap["type"].(string) switch { case isCodexToolCallOutputItemType(itemType): - callID, _ := itemMap["call_id"].(string) - name, _ := itemMap["name"].(string) - if isStandaloneNamedFunctionCallOutput(itemType, callID, name) { - continue - } result.HasFunctionCallOutput = true case isCodexToolCallContextItemType(itemType): callID, _ := itemMap["call_id"].(string) @@ -374,10 +366,6 @@ func ValidateFunctionCallOutputContext(reqBody map[string]any) FunctionCallOutpu case isCodexToolCallOutputItemType(itemType): callID, _ := itemMap["call_id"].(string) callID = strings.TrimSpace(callID) - name, _ := itemMap["name"].(string) - if isStandaloneNamedFunctionCallOutput(itemType, callID, name) { - continue - } if callID == "" { result.HasFunctionCallOutputMissingCallID = true continue diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 909100ccec..e6797ef2a8 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -203,10 +203,10 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } ingressSessionOriginalModel := "" activeTurnMetadata := "" - initialHandshakeWindowID := "" + activeWindowID := "" if c != nil { activeTurnMetadata = strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader)) - initialHandshakeWindowID = strings.TrimSpace(c.GetHeader("x-codex-window-id")) + activeWindowID = strings.TrimSpace(c.GetHeader("x-codex-window-id")) } applyPayloadMutation := func(current []byte, path string, value any) ([]byte, error) { @@ -225,6 +225,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( payload[path] = value case "client_metadata." + openAIWSTurnMetadataHeader: setOpenAIWSTurnMetadata(payload, fmt.Sprintf("%v", value)) + case "client_metadata.x-codex-window-id": + setOpenAIWSWindowIDMetadata(payload, fmt.Sprintf("%v", value)) default: return nil, err } @@ -328,7 +330,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( frameWindowID := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata.x-codex-window-id").String()) if frameTurnMetadata != "" { activeTurnMetadata = frameTurnMetadata + if w := strings.TrimSpace(gjson.Get(frameTurnMetadata, "window_id").String()); w != "" { + activeWindowID = w + } } else if frameWindowID != "" { + activeWindowID = frameWindowID if activeTurnMetadata != "" && strings.TrimSpace(gjson.Get(activeTurnMetadata, "window_id").String()) != frameWindowID { activeTurnMetadata = "" } @@ -338,6 +344,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", setErr) } normalized = next + } else if activeWindowID != "" { + next, setErr := applyPayloadMutation(normalized, "client_metadata.x-codex-window-id", activeWindowID) + if setErr != nil { + return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", setErr) + } + normalized = next } accountIdentitySourceRaw := append([]byte(nil), normalized...) accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(normalized, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) @@ -608,7 +620,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } defer history.close() historyLost := false - lastBridgeWindowID := initialHandshakeWindowID + lastBridgeWindowID := "" var bridgeReplayInput []json.RawMessage bridgeReplayInputExists := false var bridgeAccountFailoverInput []json.RawMessage @@ -1496,7 +1508,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( turnPrevRecoveryTried := false lastTurnFinishedAt := time.Time{} lastTurnResponseID := "" - lastTurnWindowID := initialHandshakeWindowID + lastTurnWindowID := "" lastTurnPayload := []byte(nil) var lastTurnStrictState *openAIWSIngressPreviousTurnStrictState lastTurnReplayInput := []json.RawMessage(nil) diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index 21711a9f2e..f563f86c77 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -247,6 +247,32 @@ func setOpenAIWSTurnMetadata(payload map[string]any, turnMetadata string) { } } +func setOpenAIWSWindowIDMetadata(payload map[string]any, windowID string) { + if len(payload) == 0 { + return + } + id := strings.TrimSpace(windowID) + if id == "" { + return + } + switch existing := payload["client_metadata"].(type) { + case map[string]any: + existing["x-codex-window-id"] = id + payload["client_metadata"] = existing + case map[string]string: + next := make(map[string]any, len(existing)+1) + for k, v := range existing { + next[k] = v + } + next["x-codex-window-id"] = id + payload["client_metadata"] = next + default: + payload["client_metadata"] = map[string]any{ + "x-codex-window-id": id, + } + } +} + func (s *OpenAIGatewayService) isOpenAIWSStoreRecoveryAllowed(account *Account) bool { if account != nil && account.IsOpenAIWSAllowStoreRecoveryEnabled() { return true From 08fdfa61d8155c13356c7e859a2b7b738d83a144 Mon Sep 17 00:00:00 2001 From: dzolv Date: Fri, 4 Dec 2026 10:44:00 +0800 Subject: [PATCH 05/15] fix(gemini): forward pageSize and pageToken on /v1beta/models --- .../handler/gemini_mixed_models_test.go | 129 +++++++++++++++++- .../internal/handler/gemini_v1beta_handler.go | 13 +- .../service/gemini_models_endpoints.go | 108 ++++++++++++++- .../service/gemini_models_endpoints_test.go | 106 ++++++++++++++ 4 files changed, 346 insertions(+), 10 deletions(-) diff --git a/backend/internal/handler/gemini_mixed_models_test.go b/backend/internal/handler/gemini_mixed_models_test.go index 3f5ed01401..70252639cd 100644 --- a/backend/internal/handler/gemini_mixed_models_test.go +++ b/backend/internal/handler/gemini_mixed_models_test.go @@ -87,11 +87,15 @@ func TestAppendUpstreamGeminiModelsPreservesMetadata(t *testing.T) { // Exercise the real handler's native-upstream branch, including scope fallback. type geminiMixedModelsUpstream struct { service.HTTPUpstream - status int - body string + status int + body string + lastReq *http.Request + calls int } -func (u *geminiMixedModelsUpstream) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) { +func (u *geminiMixedModelsUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + u.lastReq = req + u.calls++ return &http.Response{StatusCode: u.status, Header: http.Header{"Content-Type": {"application/json"}, "X-Request-Id": {"native-id"}}, Body: io.NopCloser(strings.NewReader(u.body))}, nil } func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) { @@ -240,3 +244,122 @@ func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) require.Equal(t, 2, f.upstream.calls) } + +func TestGeminiV1BetaListModels_PaginationQueryForwarding(t *testing.T) { + newHandler := func(upstream *geminiMixedModelsUpstream, allowlist service.GroupModelAllowlist, includeMixedAG bool) (*GatewayHandler, *service.APIKey) { + id := int64(48) + accounts := []service.Account{ + {ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Credentials: map[string]any{"api_key": "upstream-key"}}, + } + if includeMixedAG { + accounts = append(accounts, service.Account{ + ID: 2, + Platform: service.PlatformAntigravity, + Extra: map[string]any{"mixed_scheduling": true}, + Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}}, + }) + } + repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{id: accounts}}} + h := &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})} + key := &service.APIKey{GroupID: &id, Group: &service.Group{ID: id, Platform: service.PlatformGemini, ModelAllowlist: allowlist}} + return h, key + } + + t.Run("allowlists pageSize and pageToken and drops key and unknown params", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusOK, + body: `{"models":[{"name":"models/gemini-page-2"}]}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{}, true) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1000&pageToken=abc%2B%2F%3D%3D&key=sk-client-secret&alt=json&foo=bar", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.NotNil(t, upstream.lastReq) + gotQuery := upstream.lastReq.URL.Query() + require.Equal(t, "1000", gotQuery.Get("pageSize")) + require.Equal(t, "abc+/==", gotQuery.Get("pageToken")) + require.Empty(t, gotQuery.Get("key")) + require.Empty(t, gotQuery.Get("alt")) + require.Empty(t, gotQuery.Get("foo")) + require.Len(t, gotQuery, 2) + // 后续分页不重复附加混合分组的 Antigravity 模型。 + require.Contains(t, rec.Body.String(), "models/gemini-page-2") + require.NotContains(t, rec.Body.String(), "models/gemini-synced-custom") + }) + + t.Run("pageSize zero succeeds and omits pageSize upstream", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusOK, + body: `{"models":[{"name":"models/gemini-page-1"}],"nextPageToken":"tok-2"}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{}, true) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=0", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.NotNil(t, upstream.lastReq) + require.Empty(t, upstream.lastReq.URL.RawQuery) + // 首页仍附加混合分组的 Antigravity 模型并保留 nextPageToken。 + require.Contains(t, rec.Body.String(), "models/gemini-synced-custom") + require.Contains(t, rec.Body.String(), `"nextPageToken":"tok-2"`) + }) + + t.Run("invalid pagination params return 400 without hitting upstream", func(t *testing.T) { + for _, target := range []string{ + "/v1beta/models?pageSize=-1", + "/v1beta/models?pageSize=abc", + "/v1beta/models?pageToken=bad%0Atoken", + "/v1beta/models?pageToken=" + strings.Repeat("x", 4097), + } { + upstream := &geminiMixedModelsUpstream{status: http.StatusOK, body: `{"models":[]}`} + h, key := newHandler(upstream, service.GroupModelAllowlist{}, false) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, target, nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusBadRequest, rec.Code, target) + require.Zero(t, upstream.calls, target) + } + }) + + t.Run("allowlist dropping all models on a page keeps empty array and nextPageToken", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusOK, + body: `{"models":[{"name":"models/gemini-blocked"}],"nextPageToken":"tok-2"}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.JSONEq(t, `{"models":[],"nextPageToken":"tok-2"}`, rec.Body.String()) + }) + + t.Run("upstream error passes through untouched when allowlist is enabled", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusBadRequest, + body: `{"error":{"code":400,"message":"Invalid page token","status":"INVALID_ARGUMENT"}}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageToken=expired", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + require.JSONEq(t, upstream.body, rec.Body.String()) + }) +} diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index c30807fdfa..dc89567698 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -48,6 +48,12 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } + listQuery, err := service.ParseGeminiListModelsQuery(c.Query("pageSize"), c.Query("pageToken")) + if err != nil { + googleError(c, http.StatusBadRequest, err.Error()) + return + } + // 分组级模型白名单开启时过滤 models[].name(名字形如 models/xxx)。 filterGeminiModels := func(models []gemini.Model) []gemini.Model { if apiKey.Group == nil || !apiKey.Group.ModelAllowlistEnabled() { @@ -106,7 +112,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } - res, err := h.geminiCompatService.ForwardListModels(c.Request.Context(), account) + res, err := h.geminiCompatService.ForwardListModelsWithQuery(c.Request.Context(), account, listQuery) if err != nil { googleError(c, http.StatusBadGateway, err.Error()) return @@ -115,13 +121,14 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: filterGeminiModels(mergeGeminiModelLists(gemini.DefaultModels(), agModels))}) return } - if res.StatusCode == http.StatusOK && len(agModels) > 0 { + // 仅在首页附加混合分组内的 Antigravity 模型,避免后续分页重复追加。 + if res.StatusCode == http.StatusOK && len(agModels) > 0 && listQuery.PageToken == "" { if merged, ok := appendUpstreamGeminiModels(res.Body, agModels); ok { res.Body = merged } } - if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { + if res.StatusCode == http.StatusOK && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { if filtered, dropped, ok := filterUpstreamGeminiModelsBody(res.Body, apiKey.Group.ModelAllowlist); ok && dropped { // 只在确有条目被过滤时替换响应体;全命中或解析失败时保持原始响应, // 统一经 writeUpstreamResponse 写出(保留全部上游响应头)。 diff --git a/backend/internal/service/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go index 0364cd1f5a..1893808f2a 100644 --- a/backend/internal/service/gemini_models_endpoints.go +++ b/backend/internal/service/gemini_models_endpoints.go @@ -7,8 +7,10 @@ import ( "fmt" "io" "net/http" + "net/url" "slices" "sort" + "strconv" "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/gemini" @@ -24,6 +26,68 @@ import ( // errGeminiModelsUpstreamStatus 在 Vertex 分页读取遇到非 2xx 时中止分页,原始响应由调用方另行保存。 var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non-2xx status") +const maxGeminiListModelsPageTokenLen = 4096 + +// GeminiListModelsQuery 表示 GET /v1beta/models 允许透传到 AI Studio 兼容上游的分页查询参数。 +// 仅白名单放行 pageSize 与 pageToken,避免把客户端鉴权用的 ?key= 或其他任意参数透传给上游。 +type GeminiListModelsQuery struct { + PageSize int + PageToken string +} + +// ParseGeminiListModelsQuery 校验并解析客户端传入的 pageSize 与 pageToken 查询参数。 +// pageSize 允许为空或非负整数(0 表示沿用上游默认值);pageToken 作为不透明游标仅拒绝控制字符与超长输入。 +func ParseGeminiListModelsQuery(rawPageSize, rawPageToken string) (GeminiListModelsQuery, error) { + var q GeminiListModelsQuery + if rawPageSize != "" { + n, err := strconv.Atoi(rawPageSize) + if err != nil || n < 0 { + return GeminiListModelsQuery{}, errors.New("pageSize must be a non-negative integer") + } + q.PageSize = n + } + if rawPageToken != "" { + if !isSafeOpaquePageToken(rawPageToken) { + return GeminiListModelsQuery{}, errors.New("invalid pageToken") + } + q.PageToken = rawPageToken + } + return q, nil +} + +func isSafeOpaquePageToken(token string) bool { + if len(token) > maxGeminiListModelsPageTokenLen { + return false + } + for i := 0; i < len(token); i++ { + b := token[i] + if b < 0x20 || b == 0x7f { + return false + } + } + return true +} + +func (q GeminiListModelsQuery) toURLValues() (url.Values, error) { + if q.PageSize < 0 { + return nil, errors.New("pageSize must be a non-negative integer") + } + if q.PageToken != "" && !isSafeOpaquePageToken(q.PageToken) { + return nil, errors.New("invalid pageToken") + } + if q.PageSize == 0 && q.PageToken == "" { + return nil, nil + } + values := url.Values{} + if q.PageSize > 0 { + values.Set("pageSize", strconv.Itoa(q.PageSize)) + } + if q.PageToken != "" { + values.Set("pageToken", q.PageToken) + } + return values, nil +} + // DeclaredModelIDs 在分组内每个可调度 Gemini 账号都有生效的 model_mapping(含 Google One 的默认映射)时, // 返回这些映射键的并集(去重排序,通配符键原样保留)。有账号未配置映射时该账号接受任意模型,返回空, // 模型接口由选中账号的上游应答。 @@ -163,11 +227,21 @@ func modelsEndpointAccountRank(a *Account) int { // AI Studio 兼容账号原样返回上游响应;Vertex 服务账号读取 Google 发布方模型列表后转换格式, // 上游非 2xx 时原样返回该响应;Vertex API Key 账号返回内置列表。 func (s *GeminiMessagesCompatService) ForwardListModels(ctx context.Context, account *Account) (*UpstreamHTTPResult, error) { + return s.ForwardListModelsWithQuery(ctx, account, GeminiListModelsQuery{}) +} + +// ForwardListModelsWithQuery 读取账号上游的模型列表,并将白名单分页查询参数(pageSize、pageToken) +// 透传给 AI Studio 兼容上游;Vertex 账号仍返回聚合后的完整列表或内置列表。 +func (s *GeminiMessagesCompatService) ForwardListModelsWithQuery(ctx context.Context, account *Account, query GeminiListModelsQuery) (*UpstreamHTTPResult, error) { if account == nil { return nil, errors.New("account is nil") } if !account.IsVertexServiceAccount() { - return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models") + queryValues, err := query.toURLValues() + if err != nil { + return nil, err + } + return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models", queryValues) } if account.IsVertexAPIKey() { return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModelsList()) @@ -195,7 +269,7 @@ func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, accou return nil, errors.New("account is nil") } if !account.IsVertexServiceAccount() { - return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models/"+model) + return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models/"+model, nil) } if account.IsVertexAPIKey() { return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model)) @@ -226,7 +300,8 @@ func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, accou // forwardGeminiModelsGET 向 AI Studio 兼容上游转发模型接口的 GET 请求。 // path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验,见 upstream_path_guard.go。 -func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context, account *Account, path string) (*UpstreamHTTPResult, error) { +// query 仅接受白名单过滤后的查询参数,通过结构化 URL 合并写入,避免直接拼接原始查询串。 +func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context, account *Account, path string, query url.Values) (*UpstreamHTTPResult, error) { sanitizedPath, ok := sanitizedUpstreamPathSuffix(path) if !ok || sanitizedPath == "" { return nil, errors.New("invalid path") @@ -237,7 +312,10 @@ func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context if err != nil { return nil, err } - fullURL := strings.TrimRight(normalizedBaseURL, "/") + sanitizedPath + fullURL, err := buildGeminiModelsEndpointURL(normalizedBaseURL, sanitizedPath, query) + if err != nil { + return nil, err + } req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) if err != nil { @@ -267,6 +345,28 @@ func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context return s.doGeminiModelsGET(req, account) } +func buildGeminiModelsEndpointURL(normalizedBaseURL, sanitizedPath string, query url.Values) (string, error) { + u, err := url.Parse(normalizedBaseURL) + if err != nil { + return "", fmt.Errorf("invalid base_url: %w", err) + } + u.Fragment = "" + u.ForceQuery = false + u.Path = strings.TrimRight(u.Path, "/") + sanitizedPath + u.RawPath = "" + if len(query) > 0 { + q := u.Query() + for k, vals := range query { + if len(vals) == 0 { + continue + } + q.Set(k, vals[0]) + } + u.RawQuery = q.Encode() + } + return u.String(), nil +} + // listVertexGeminiModels 读取 Vertex 服务账号在指定区域可用的 Gemini 模型。 // 上游返回非 2xx 时 failure 为该页的原始响应,modelIDs 与 err 均为空。 func (s *GeminiMessagesCompatService) listVertexGeminiModels(ctx context.Context, account *Account, location string) (modelIDs []string, failure *UpstreamHTTPResult, err error) { diff --git a/backend/internal/service/gemini_models_endpoints_test.go b/backend/internal/service/gemini_models_endpoints_test.go index 962f642779..1a511ef9c2 100644 --- a/backend/internal/service/gemini_models_endpoints_test.go +++ b/backend/internal/service/gemini_models_endpoints_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "net/http" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/config" @@ -229,3 +230,108 @@ func TestForwardModels_VertexMultiRegionAccountReadsGlobalList(t *testing.T) { require.Equal(t, http.StatusOK, res.StatusCode) require.Equal(t, globalList, upstream.lastReq.URL.String()) } + +func TestParseGeminiListModelsQuery(t *testing.T) { + q, err := ParseGeminiListModelsQuery("", "") + require.NoError(t, err) + require.Equal(t, GeminiListModelsQuery{}, q) + + q, err = ParseGeminiListModelsQuery("0", "") + require.NoError(t, err) + require.Equal(t, GeminiListModelsQuery{PageSize: 0}, q) + + q, err = ParseGeminiListModelsQuery("1000", "Chttb2RlbHMvZ2VtaW5p+abc/def==") + require.NoError(t, err) + require.Equal(t, GeminiListModelsQuery{PageSize: 1000, PageToken: "Chttb2RlbHMvZ2VtaW5p+abc/def=="}, q) + + q, err = ParseGeminiListModelsQuery("", strings.Repeat("a", maxGeminiListModelsPageTokenLen)) + require.NoError(t, err) + require.Len(t, q.PageToken, maxGeminiListModelsPageTokenLen) + + for _, badSize := range []string{"-1", "abc", "1.5", "10\n", " 10"} { + _, err = ParseGeminiListModelsQuery(badSize, "") + require.Error(t, err, "pageSize=%q", badSize) + } + for _, badToken := range []string{ + "tok\r\n", + "tok\x00", + "tok\x7f", + strings.Repeat("a", maxGeminiListModelsPageTokenLen+1), + } { + _, err = ParseGeminiListModelsQuery("", badToken) + require.Error(t, err, "pageToken len=%d", len(badToken)) + } +} + +func TestForwardListModelsWithQuery_ForwardsPaginationParams(t *testing.T) { + t.Run("forwards pageSize and base64 pageToken with proper encoding", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[{"name":"models/gemini-2.5-pro"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 261, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com/proxy/", + }} + + res, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{ + PageSize: 1000, + PageToken: "abc+/def==", + }) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://relay.example.com/proxy/v1beta/models?pageSize=1000&pageToken=abc%2B%2Fdef%3D%3D", upstream.lastReq.URL.String()) + require.Equal(t, "sk-pool", upstream.lastReq.Header.Get("x-goog-api-key")) + }) + + t.Run("merges with existing base_url query params and strips fragment", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 262, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com/gateway?tenant=alpha#frag", + }} + + res, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageSize: 50}) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://relay.example.com/gateway/v1beta/models?pageSize=50&tenant=alpha", upstream.lastReq.URL.String()) + }) + + t.Run("pageSize zero omits pageSize and leaves URL clean", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 263, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com", + }} + + res, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageSize: 0}) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://relay.example.com/v1beta/models", upstream.lastReq.URL.String()) + }) + + t.Run("rejects invalid direct query before hitting upstream", func(t *testing.T) { + upstream := &httpUpstreamRecorder{} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 264, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-pool"}} + + _, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageSize: -1}) + require.Error(t, err) + _, err = svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageToken: "bad\n"}) + require.Error(t, err) + require.Empty(t, upstream.requests) + }) + + t.Run("vertex service account ignores AI Studio pagination query", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-2.5-flash"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardListModelsWithQuery(context.Background(), vertexModelSyncTestAccount(nil), GeminiListModelsQuery{ + PageSize: 10, + PageToken: "client-token", + }) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.lastReq.URL.String()) + }) +} From 6be2403d7a9ee22e3c8c424f2e3de6e28e24e4ab Mon Sep 17 00:00:00 2001 From: Sjeary <1286860778@qq.com> Date: Thu, 3 Dec 2026 20:18:44 -0800 Subject: [PATCH 06/15] fix: prevent overflow in mobile user management --- frontend/src/components/common/DataTable.vue | 2 +- .../user/PlatformUsageBreakdown.vue | 24 +++++++++----- .../user/UserAttributesConfigModal.vue | 4 +-- .../__tests__/PlatformUsageBreakdown.spec.ts | 31 +++++++++++++++++++ frontend/src/views/admin/UsersView.vue | 16 +++++----- 5 files changed, 58 insertions(+), 19 deletions(-) create mode 100644 frontend/src/components/user/__tests__/PlatformUsageBreakdown.spec.ts diff --git a/frontend/src/components/common/DataTable.vue b/frontend/src/components/common/DataTable.vue index 72c0716b9e..2e910c09ac 100644 --- a/frontend/src/components/common/DataTable.vue +++ b/frontend/src/components/common/DataTable.vue @@ -76,7 +76,7 @@ {{ column.label }} -
+
{{ column.formatter ? column.formatter(row[column.key], row) : row[column.key] }} diff --git a/frontend/src/components/user/PlatformUsageBreakdown.vue b/frontend/src/components/user/PlatformUsageBreakdown.vue index 481c5a8bb1..77c98f5932 100644 --- a/frontend/src/components/user/PlatformUsageBreakdown.vue +++ b/frontend/src/components/user/PlatformUsageBreakdown.vue @@ -1,23 +1,30 @@