From eb4ccd173e35b459661fff4a4f079f6f96fccc56 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Fri, 16 Oct 2026 20:32:00 +0800 Subject: [PATCH 01/33] fix(openai): apply reasoning mappings to synthesized effort --- .../internal/handler/composite_platform.go | 7 ---- .../handler/composite_platform_test.go | 36 ++++++++++++++----- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 6e613aa3e4..764a6a7f9d 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -163,13 +163,6 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s return } bindRequestedReasoningEffort(c, body, strings.TrimSpace(gjson.GetBytes(body, "model").String())) - // The Messages bridge synthesizes a default OpenAI effort when - // output_config.effort is omitted. Bind the group policy only for an - // explicit client value so the ceiling does not alter that default. - effort := gjson.GetBytes(body, "output_config.effort") - if !effort.Exists() || effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" { - return - } maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey) if !ok { return diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 7704a129a0..4dc504e6c3 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -133,14 +133,34 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) { require.True(t, changed) require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(bound)) - omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) - omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil) - omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI)) - bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, apiKey, []byte(`{"model":"gpt-5"}`)) - omitted, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), body) - require.NoError(t, err) - require.False(t, changed) - require.Equal(t, body, omitted) + synthesizedGroup := &service.Group{ + Platform: service.PlatformComposite, + ReasoningEffortMappings: []service.ReasoningEffortMapping{ + {From: "medium", To: "low"}, + {From: "none", To: "low"}, + }, + } + synthesizedAPIKey := &service.APIKey{Group: synthesizedGroup} + for _, tc := range []struct { + name string + request string + response string + want string + }{ + {name: "default medium", request: `{"model":"gpt-5"}`, response: `{"reasoning":{"effort":"medium"}}`, want: "low"}, + {name: "disabled thinking none", request: `{"model":"gpt-5","thinking":{"type":"disabled"}}`, response: `{"reasoning":{"effort":"none"}}`, want: "low"}, + } { + t.Run(tc.name, func(t *testing.T) { + omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil) + omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI)) + bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, synthesizedAPIKey, []byte(tc.request)) + got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), []byte(tc.response)) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, tc.want, gjson.GetBytes(got, "reasoning.effort").String()) + }) + } denyGroup := *group denyGroup.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny From 6f2faba2935c4e592c78c2f629a3d16f2a7ea09a Mon Sep 17 00:00:00 2001 From: wucm667 Date: Sat, 24 Oct 2026 11:28:25 +0800 Subject: [PATCH 02/33] fix(openai): validate synthesized effort after policy mapping --- .../internal/handler/composite_platform.go | 2 +- .../handler/composite_platform_test.go | 4 +- .../handler/messages_effort_policy_test.go | 50 ++++++ .../anthropic_effort_validation_test.go | 35 ++++ .../pkg/apicompat/anthropic_to_responses.go | 22 ++- backend/internal/service/apicompat_config.go | 4 - .../service/openai_gateway_messages.go | 12 +- .../openai_gateway_messages_chat_fallback.go | 6 +- .../service/openai_gateway_request_body.go | 13 +- .../openai_messages_effort_policy_test.go | 156 ++++++++++++++++++ .../service/openai_reasoning_effort_policy.go | 16 ++ 11 files changed, 303 insertions(+), 17 deletions(-) create mode 100644 backend/internal/handler/messages_effort_policy_test.go create mode 100644 backend/internal/pkg/apicompat/anthropic_effort_validation_test.go create mode 100644 backend/internal/service/openai_messages_effort_policy_test.go diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 764a6a7f9d..d1ce35fefb 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -167,5 +167,5 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s if !ok { return } - c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit)) + c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicyForMessages(c.Request.Context(), body, maxEffort, mappings, overLimit)) } diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 4dc504e6c3..ee3d4ad859 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -147,7 +147,7 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) { response string want string }{ - {name: "default medium", request: `{"model":"gpt-5"}`, response: `{"reasoning":{"effort":"medium"}}`, want: "low"}, + {name: "default medium", request: `{"model":"gpt-5"}`, response: `{"reasoning":{"effort":"medium"}}`, want: "medium"}, {name: "disabled thinking none", request: `{"model":"gpt-5","thinking":{"type":"disabled"}}`, response: `{"reasoning":{"effort":"none"}}`, want: "low"}, } { t.Run(tc.name, func(t *testing.T) { @@ -157,7 +157,7 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) { bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, synthesizedAPIKey, []byte(tc.request)) got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), []byte(tc.response)) require.NoError(t, err) - require.True(t, changed) + require.Equal(t, tc.want != "medium", changed) require.Equal(t, tc.want, gjson.GetBytes(got, "reasoning.effort").String()) }) } diff --git a/backend/internal/handler/messages_effort_policy_test.go b/backend/internal/handler/messages_effort_policy_test.go new file mode 100644 index 0000000000..63734b7e04 --- /dev/null +++ b/backend/internal/handler/messages_effort_policy_test.go @@ -0,0 +1,50 @@ +package handler + +import ( + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestMessagesEffortPolicyBinding(t *testing.T) { + for _, platform := range []string{service.PlatformOpenAI, service.PlatformComposite} { + for _, test := range []struct { + name string + preference string + effort string + mappings []service.ReasoningEffortMapping + ceiling string + want string + }{ + {name: "omitted unchanged", effort: "medium", want: "medium"}, + {name: "omitted ignores medium mapping", effort: "medium", mappings: []service.ReasoningEffortMapping{{From: "medium", To: "low"}}, want: "medium"}, + {name: "omitted ignores ceiling", effort: "medium", ceiling: "low", want: "medium"}, + {name: "omitted none mapping does not cap medium default", effort: "medium", ceiling: "low", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}}, want: "medium"}, + {name: "disabled omitted applies none only once", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}, {From: "low", To: "high"}}, want: "low"}, + {name: "disabled explicit applies none", preference: `,"output_config":{"effort":"max"},"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}}, want: "low"}, + {name: "explicit adaptive retains policy", preference: `,"output_config":{"effort":"high"},"thinking":{"type":"adaptive"}`, effort: "high", ceiling: "medium", want: "medium"}, + {name: "omitted retains model scope", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6-sol", MatchType: "exact"}}, want: "none"}, + } { + t.Run(platform+"/"+test.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", "/v1/messages", nil) + apiKey := &service.APIKey{Group: &service.Group{Platform: platform, MaxReasoningEffort: test.ceiling, ReasoningEffortMappings: test.mappings}} + body := []byte(`{"model":"gpt-6.1-sol"` + test.preference + `}`) + ensureCompositeTargetPlatform(c, apiKey, "gpt-6.1-sol") + bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body) + converted := []byte(`{"model":"gpt-6.1-sol","reasoning":{"effort":"` + test.effort + `"}}`) + got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), converted) + require.NoError(t, err) + require.Equal(t, test.want, gjson.GetBytes(got, "reasoning.effort").String()) + require.Equal(t, test.effort != test.want, changed) + if !changed { + require.Equal(t, converted, got) + } + }) + } + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_effort_validation_test.go b/backend/internal/pkg/apicompat/anthropic_effort_validation_test.go new file mode 100644 index 0000000000..d72ce9e907 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_effort_validation_test.go @@ -0,0 +1,35 @@ +package apicompat + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAnthropicToResponsesDeferredEffortValidation(t *testing.T) { + for _, effort := range []string{"", "low", "high", "max"} { + t.Run(effort, func(t *testing.T) { + req := &AnthropicRequest{ + Model: "gpt-6.1-sol", + MaxTokens: 1, + Thinking: &AnthropicThinking{Type: "disabled"}, + OutputConfig: &AnthropicOutputConfig{Effort: effort}, + } + _, err := AnthropicToResponses(req) + require.Error(t, err) + _, err = AnthropicToResponsesWithMinOutputTokens(req, 32) + require.Error(t, err) + converted, err := AnthropicToResponsesWithOptions(req, AnthropicToResponsesOptions{ + MinOutputTokens: 32, + DeferReasoningEffortValidation: true, + }) + require.NoError(t, err) + require.Equal(t, "gpt-6.1-sol", converted.Model) + require.Equal(t, "none", converted.Reasoning.Effort) + require.Empty(t, converted.Reasoning.Summary) + require.Equal(t, 32, *converted.MaxOutputTokens) + require.Equal(t, "disabled", req.Thinking.Type) + require.Equal(t, effort, req.OutputConfig.Effort) + }) + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go index a54ca94133..aabeacf37f 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go @@ -19,8 +19,22 @@ func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) { // AnthropicToResponsesWithMinOutputTokens converts an Anthropic request using // the supplied max_output_tokens floor. func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ResponsesRequest, error) { - if err := openai.ValidateGPT61SolReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil { - return nil, err + return AnthropicToResponsesWithOptions(req, AnthropicToResponsesOptions{MinOutputTokens: minOutputTokens}) +} + +// AnthropicToResponsesOptions controls conversion and optional deferred effort +// validation. Callers deferring validation must validate raw selections before +// conversion and the final effort after applying their policy. +type AnthropicToResponsesOptions struct { + MinOutputTokens int + DeferReasoningEffortValidation bool +} + +func AnthropicToResponsesWithOptions(req *AnthropicRequest, options AnthropicToResponsesOptions) (*ResponsesRequest, error) { + if !options.DeferReasoningEffortValidation { + if err := openai.ValidateGPT61SolReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil { + return nil, err + } } input, err := convertAnthropicToResponsesInput(req.System, req.Messages) if err != nil { @@ -56,8 +70,8 @@ func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTok if req.MaxTokens > 0 { v := req.MaxTokens - if v < minOutputTokens { - v = minOutputTokens + if v < options.MinOutputTokens { + v = options.MinOutputTokens } out.MaxOutputTokens = &v } diff --git a/backend/internal/service/apicompat_config.go b/backend/internal/service/apicompat_config.go index e9605e0a5c..8d7680594c 100644 --- a/backend/internal/service/apicompat_config.go +++ b/backend/internal/service/apicompat_config.go @@ -16,10 +16,6 @@ func chatCompletionsToResponses(cfg *config.Config, req *apicompat.ChatCompletio return apicompat.ChatCompletionsToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg)) } -func anthropicToResponses(cfg *config.Config, req *apicompat.AnthropicRequest) (*apicompat.ResponsesRequest, error) { - return apicompat.AnthropicToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg)) -} - func settingServiceConfig(settingService *SettingService) *config.Config { if settingService == nil { return nil diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 45f890a370..76c125fc0e 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -98,7 +98,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 2. Model mapping billingModel := resolveOpenAIForwardModel(account, normalizedModel, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) - if err := validateGPT61SolCompatRequest(body, upstreamModel); err != nil { + if err := validateGPT61SolRawEffort(body, upstreamModel); err != nil { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } @@ -154,7 +154,10 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 3. Convert Anthropic → Responses after compatibility-only replay guard. anthropicReq.Model = upstreamModel - responsesReq, err := anthropicToResponses(s.cfg, &anthropicReq) + responsesReq, err := apicompat.AnthropicToResponsesWithOptions(&anthropicReq, apicompat.AnthropicToResponsesOptions{ + MinOutputTokens: configuredMinOutputTokens(s.cfg), + DeferReasoningEffortValidation: true, + }) if err != nil { return nil, fmt.Errorf("convert anthropic to responses: %w", err) } @@ -315,6 +318,11 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( } } + if err := validateGPT61SolCompatRequest(responsesBody, upstreamModel); err != nil { + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } + // 4c. Apply OpenAI fast policy (may filter service_tier or block the request). // Mirrors the Claude anthropic-beta "fast-mode-2026-02-01" filter, but keyed // on the body-level service_tier field (priority/flex). diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index d12918a3bb..2eca13ddca 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -63,7 +63,7 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( billingModel := resolveOpenAIForwardModel(account, anthropicReq.Model, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) - if err := validateGPT61SolCompatRequest(body, upstreamModel); err != nil { + if err := validateGPT61SolRawEffort(body, upstreamModel); err != nil { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } @@ -101,6 +101,10 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( chatBody = policyBody } } + if err := validateGPT61SolCompatRequest(chatBody, upstreamModel); err != nil { + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } // Provider normalization and policy caps can both change the converted effort. // Use the final outbound value for usage logs and billing. reasoningEffort := extractOpenAIReasoningEffortFromBody(chatBody, upstreamModel, billingModel, originalModel) diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 38cc743d9d..24bcb517b9 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -2604,6 +2604,16 @@ func supportsOpenAIReasoningEffortMax(model string) bool { // validateGPT61SolCompatRequest runs after model mapping, before conversion can // discard unsupported explicit effort selections or disabled thinking. func validateGPT61SolCompatRequest(body []byte, model string) error { + if err := validateGPT61SolRawEffort(body, model); err != nil { + return err + } + if gjson.GetBytes(body, "thinking.type").String() == "disabled" { + return openai.ValidateGPT61SolReasoningEffort(model, "none") + } + return nil +} + +func validateGPT61SolRawEffort(body []byte, model string) error { if !openai.IsGPT61SolModelSpelling(model) { return nil } @@ -2612,9 +2622,6 @@ func validateGPT61SolCompatRequest(body []byte, model string) error { return err } } - if gjson.GetBytes(body, "thinking.type").String() == "disabled" { - return openai.ValidateGPT61SolReasoningEffort(model, "none") - } requestedModel := gjson.GetBytes(body, "model").String() for _, effort := range []string{"none", "minimal"} { if strings.HasSuffix(strings.ToLower(requestedModel), "-"+effort) { diff --git a/backend/internal/service/openai_messages_effort_policy_test.go b/backend/internal/service/openai_messages_effort_policy_test.go new file mode 100644 index 0000000000..934de147ef --- /dev/null +++ b/backend/internal/service/openai_messages_effort_policy_test.go @@ -0,0 +1,156 @@ +//go:build unit + +package service + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestMessagesEffortPolicyHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + noneToLow := []ReasoningEffortMapping{{From: "none", To: "low"}} + for _, chat := range []bool{false, true} { + for _, auth := range []string{AccountTypeAPIKey, AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, test := range []struct { + name string + preference string + mappings []ReasoningEffortMapping + ceiling string + model string + terminal bool + want string + status int + }{ + {name: "omitted unchanged", want: "medium"}, + {name: "omitted unrelated mapping unchanged", mappings: []ReasoningEffortMapping{{From: "medium", To: "low"}}, want: "medium"}, + {name: "omitted ceiling unchanged", ceiling: "low", want: "medium"}, + {name: "omitted none mapping and ceiling unchanged", mappings: noneToLow, ceiling: "low", want: "medium"}, + {name: "omitted none mapping leaves default", mappings: noneToLow, want: "medium"}, + {name: "disabled omitted mapped", preference: `,"thinking":{"type":"disabled"}`, mappings: noneToLow, want: "low"}, + {name: "disabled low mapped", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"low"}`, mappings: noneToLow, want: "low"}, + {name: "disabled high mapped", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: noneToLow, want: "low"}, + {name: "disabled max mapped", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"max"}`, mappings: noneToLow, want: "low"}, + {name: "disabled no mapping rejected", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, status: 400}, + {name: "disabled omitted no mapping rejected", preference: `,"thinking":{"type":"disabled"}`, status: 400}, + {name: "disabled unrelated mapping rejected", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "high", To: "low"}}, status: 400}, + {name: "disabled wrong model scope rejected", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6-sol", MatchType: "exact"}}, status: 400}, + {name: "raw none cannot be mapped away", preference: `,"output_config":{"effort":"none"}`, mappings: noneToLow, status: 400}, + {name: "raw none disabled cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"none"}`, mappings: noneToLow, status: 400}, + {name: "raw minimal disabled cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"minimal"}`, mappings: append(append([]ReasoningEffortMapping{}, noneToLow...), ReasoningEffortMapping{From: "minimal", To: "low"}), status: 400}, + {name: "raw minimal cannot be mapped away", preference: `,"output_config":{"effort":"minimal"}`, mappings: []ReasoningEffortMapping{{From: "minimal", To: "low"}}, status: 400}, + {name: "raw reasoning none cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"},"reasoning":{"effort":"none"}`, mappings: noneToLow, status: 400}, + {name: "raw chat minimal cannot be hidden", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"},"reasoning_effort":"minimal"`, mappings: noneToLow, status: 400}, + {name: "raw alias cannot be hidden", model: "gpt-6.1-sol-minimal", preference: `,"thinking":{"type":"disabled"}`, mappings: noneToLow, status: 400}, + {name: "one hop mapping", preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "low"}, {From: "low", To: "high"}}, want: "low"}, + {name: "mapping final unsupported rejected", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "minimal"}}, status: 400}, + {name: "mapping deny preserved", preference: `,"thinking":{"type":"disabled"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "deny"}}, status: 403}, + {name: "adaptive explicit unchanged", preference: `,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"}`, mappings: noneToLow, want: "high"}, + {name: "adaptive explicit mapped", preference: `,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "high", To: "low"}, {From: "low", To: "medium"}}, want: "low"}, + {name: "explicit ceiling preserved", preference: `,"output_config":{"effort":"high"}`, ceiling: "medium", want: "medium"}, + {name: "terminal override not mapped twice", terminal: true, preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"high"}`, mappings: []ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6.1-sol", MatchType: "exact"}}, want: "low"}, + {name: "terminal override raw rejected", terminal: true, preference: `,"thinking":{"type":"disabled"},"output_config":{"effort":"none"}`, mappings: noneToLow, status: 400}, + } { + t.Run(fmt.Sprintf("chat=%t/%s/stream=%t/%s", chat, auth, stream, test.name), func(t *testing.T) { + model := test.model + if model == "" { + model = "gpt-6.1-sol" + } + account := rawGPT56ResponsesAPIKeyAccount(model, "gpt-6.1-sol") + if auth == AccountTypeOAuth { + account = rawGPT56ResponsesOAuthAccount(model, "gpt-6.1-sol") + } + if chat { + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions)} + } + defaultMapped := "" + if test.terminal { + model = "public-alias" + defaultMapped = "gpt-6.1-sol" + account.Credentials["model_mapping"] = map[string]any{"gpt-6.1-sol": "gpt-6-sol"} + } + usesChat := chat && auth == AccountTypeAPIKey + response := openAICompatSSECompletedResponse("resp_effort", "gpt-6.1-sol") + if usesChat { + payload := `{"id":"chat_effort","model":"gpt-6.1-sol","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}` + contentType := "application/json" + if stream { + payload = "data: " + `{"id":"chat_effort","model":"gpt-6.1-sol","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}` + "\n\ndata: [DONE]\n\n" + contentType = "text/event-stream" + } + response = &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))} + } + upstream := &httpUpstreamRecorder{resp: response} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body := fmt.Sprintf(`{"model":%q,"max_tokens":1024,"messages":[{"role":"user","content":"Hello"}],"stream":%t%s}`, model, stream, test.preference) + var forwardErr error + var result *OpenAIForwardResult + router := gin.New() + router.POST("/v1/messages", func(c *gin.Context) { + ctx := WithOpenAIReasoningEffortPolicyForMessages(c.Request.Context(), []byte(body), test.ceiling, test.mappings, "") + result, forwardErr = svc.ForwardAsAnthropic(ctx, c, account, []byte(body), "", defaultMapped) + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))) + if test.status != 0 { + require.Error(t, forwardErr) + require.Equal(t, test.status, recorder.Code, recorder.Body.String()) + require.Empty(t, upstream.requests) + return + } + preferredEffortPath := "reasoning.effort" + endpoint := "/responses" + if usesChat { + preferredEffortPath = "reasoning_effort" + endpoint = "/chat/completions" + } + require.NoError(t, forwardErr) + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Len(t, upstream.requests, 1) + require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, endpoint), upstream.lastReq.URL.String()) + require.Equal(t, "gpt-6.1-sol", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, test.want, gjson.GetBytes(upstream.lastBody, preferredEffortPath).String()) + require.NotNil(t, result) + require.NotNil(t, result.ReasoningEffort) + require.Equal(t, test.want, *result.ReasoningEffort) + require.Equal(t, stream, result.Stream) + require.Equal(t, stream || !usesChat, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + if stream { + require.Contains(t, recorder.Header().Get("Content-Type"), "text/event-stream") + require.Contains(t, recorder.Body.String(), "message_stop") + } else { + require.Contains(t, recorder.Header().Get("Content-Type"), "application/json") + require.Equal(t, "ok", gjson.GetBytes(recorder.Body.Bytes(), "content.0.text").String()) + } + }) + } + } + } + } +} + +func TestMessagesRawEffortValidation(t *testing.T) { + for _, test := range []struct { + body string + deny bool + }{ + {body: `{"output_config":{"effort":"high"},"thinking":{"type":"disabled"}}`}, + {body: `{"output_config":{"effort":"none"},"thinking":{"type":"disabled"}}`, deny: true}, + {body: `{"reasoning_effort":"none"}`, deny: true}, + {body: `{"reasoning":{"effort":"minimal"}}`, deny: true}, + {body: `{"model":"gpt-6.1-sol-none"}`, deny: true}, + } { + require.Equal(t, test.deny, validateGPT61SolRawEffort([]byte(test.body), "gpt-6.1-sol") != nil, test.body) + require.NoError(t, validateGPT61SolRawEffort([]byte(test.body), "gpt-6-sol")) + } +} diff --git a/backend/internal/service/openai_reasoning_effort_policy.go b/backend/internal/service/openai_reasoning_effort_policy.go index 907025597b..548aafea97 100644 --- a/backend/internal/service/openai_reasoning_effort_policy.go +++ b/backend/internal/service/openai_reasoning_effort_policy.go @@ -445,6 +445,22 @@ func WithOpenAIReasoningEffortPolicy(ctx context.Context, maxEffort string, mapp return context.WithValue(ctx, openAIReasoningEffortPolicyContextKey{}, policy) } +// WithOpenAIReasoningEffortPolicyForMessages preserves bridge defaults when the +// client omits output_config.effort, binding only mappings for synthesized none. +func WithOpenAIReasoningEffortPolicyForMessages(ctx context.Context, body []byte, maxEffort string, mappings []ReasoningEffortMapping, overLimit string) context.Context { + if strings.TrimSpace(gjson.GetBytes(body, "output_config.effort").String()) == "" { + maxEffort = "" + noneMappings := make([]ReasoningEffortMapping, 0, len(mappings)) + for _, mapping := range mappings { + if normalizeReasoningEffortMappingSource(mapping.From) == "none" { + noneMappings = append(noneMappings, mapping) + } + } + mappings = noneMappings + } + return WithOpenAIReasoningEffortPolicy(ctx, maxEffort, mappings, overLimit) +} + // ApplyOpenAIReasoningEffortPolicyFromContext applies a policy previously bound // to the request. An unbound request is returned byte-for-byte unchanged. func ApplyOpenAIReasoningEffortPolicyFromContext(ctx context.Context, body []byte) ([]byte, bool, error) { From b8de5e170006886b21ceee72e10d8cec7132dcdb Mon Sep 17 00:00:00 2001 From: hezhaoqian1 <115222059+hezhaoqian1@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:16:54 +0800 Subject: [PATCH 03/33] =?UTF-8?q?perf(keys):=20API=20=E5=AF=86=E9=92=A5?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E4=B8=8D=E5=86=8D=E7=AD=89=E5=BE=85=2030=20?= =?UTF-8?q?=E5=A4=A9=E7=94=A8=E9=87=8F=E7=BB=9F=E8=AE=A1=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E4=B8=BA=E5=85=B6=E5=8A=A0=E8=A6=86=E7=9B=96=E7=B4=A2=E5=BC=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /keys 页面要等密钥列表和每个 key 的用量统计都返回,才撤掉表格骨架屏。 用量统计(POST /usage/dashboard/api-keys-usage)按 api_key_id 汇总近 30 天的 usage_logs.actual_cost。数据量大时,要逐行回表读取几十万到上百万行,接口耗时 十几到三十几秒,甚至超时,页面就一直停在骨架屏。 - 前端:列表返回就渲染表格,用量列单独显示加载占位;统计失败时回落为 $0.0000。 - 后端:新增覆盖索引 (api_key_id, created_at) INCLUDE (actual_cost),使该统计可以 index-only scan,不再回表。迁移采用 CONCURRENTLY 建索引;与其他 usage_logs 索引迁移一样,重试前会先清理中断构建留下的 INVALID 索引。 Refs #5858 Co-Authored-By: Claude Opus 5.5 --- .../internal/repository/migrations_runner.go | 4 ++ ...grations_runner_api_key_cost_index_test.go | 49 +++++++++++++++++++ ...add_usage_logs_api_key_cost_index_notx.sql | 5 ++ .../usage_log_api_key_cost_index_test.go | 18 +++++++ frontend/src/views/user/KeysView.vue | 45 ++++++++++++----- .../src/views/user/__tests__/KeysView.spec.ts | 35 ++++++++++++- 6 files changed, 142 insertions(+), 14 deletions(-) create mode 100644 backend/internal/repository/migrations_runner_api_key_cost_index_test.go create mode 100644 backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql create mode 100644 backend/migrations/usage_log_api_key_cost_index_test.go diff --git a/backend/internal/repository/migrations_runner.go b/backend/internal/repository/migrations_runner.go index 8c69eb50dd..5ec51a0e99 100644 --- a/backend/internal/repository/migrations_runner.go +++ b/backend/internal/repository/migrations_runner.go @@ -64,6 +64,8 @@ const usageLogsEffectiveRequestedModelIndex = "idx_usage_logs_effective_requeste const usageLogsEffectiveUpstreamModelIndex = "idx_usage_logs_effective_upstream_model_created" const usageLogsUpstreamRequestIDIndexMigration = "233_add_usage_log_upstream_request_id_index_notx.sql" const usageLogsUpstreamRequestIDIndex = "idx_usage_logs_upstream_request_id" +const usageLogsAPIKeyCostIndexMigration = "249_add_usage_logs_api_key_cost_index_notx.sql" +const usageLogsAPIKeyCostIndex = "idx_usage_logs_api_key_created_cost" type migrationChecksumCompatibilityRule struct { fileChecksum string @@ -309,6 +311,8 @@ func prepareNonTransactionalMigration(ctx context.Context, db migrationConnectio return nil case usageLogsUpstreamRequestIDIndexMigration: return dropInvalidIndexIfPresent(ctx, db, usageLogsUpstreamRequestIDIndex) + case usageLogsAPIKeyCostIndexMigration: + return dropInvalidIndexIfPresent(ctx, db, usageLogsAPIKeyCostIndex) default: return nil } diff --git a/backend/internal/repository/migrations_runner_api_key_cost_index_test.go b/backend/internal/repository/migrations_runner_api_key_cost_index_test.go new file mode 100644 index 0000000000..a9c6e1ee41 --- /dev/null +++ b/backend/internal/repository/migrations_runner_api_key_cost_index_test.go @@ -0,0 +1,49 @@ +package repository + +import ( + "context" + "database/sql" + "testing" + "testing/fstest" + + sqlmock "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +func TestApplyMigrationsFS_NonTransactionalMigration_APIKeyCostIndexDropsInvalidIndexBeforeRetry(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + + prepareMigrationsBootstrapExpectations(mock) + mock.ExpectQuery("SELECT checksum FROM schema_migrations WHERE filename = \\$1"). + WithArgs(usageLogsAPIKeyCostIndexMigration). + WillReturnError(sql.ErrNoRows) + mock.ExpectQuery("SELECT EXISTS \\("). + WithArgs(usageLogsAPIKeyCostIndex). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + mock.ExpectExec("DROP INDEX CONCURRENTLY IF EXISTS idx_usage_logs_api_key_created_cost"). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost"). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO schema_migrations \\(filename, checksum\\) VALUES \\(\\$1, \\$2\\)"). + WithArgs(usageLogsAPIKeyCostIndexMigration, sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectExec("SELECT pg_advisory_unlock\\(\\$1\\)"). + WithArgs(migrationsAdvisoryLockID). + WillReturnResult(sqlmock.NewResult(0, 1)) + + fsys := fstest.MapFS{ + usageLogsAPIKeyCostIndexMigration: &fstest.MapFile{ + Data: []byte(` +CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost + ON usage_logs (api_key_id, created_at) + INCLUDE (actual_cost); +`), + }, + } + + err = applyMigrationsFS(context.Background(), db, fsys) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql b/backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql new file mode 100644 index 0000000000..740e1e516e --- /dev/null +++ b/backend/migrations/249_add_usage_logs_api_key_cost_index_notx.sql @@ -0,0 +1,5 @@ +-- Serve per-key 30-day / today cost sums (API key list usage column) from the index alone, +-- instead of fetching hundreds of thousands of usage_logs heap rows per page load. +CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost + ON usage_logs (api_key_id, created_at) + INCLUDE (actual_cost); diff --git a/backend/migrations/usage_log_api_key_cost_index_test.go b/backend/migrations/usage_log_api_key_cost_index_test.go new file mode 100644 index 0000000000..5a68667517 --- /dev/null +++ b/backend/migrations/usage_log_api_key_cost_index_test.go @@ -0,0 +1,18 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestUsageLogAPIKeyCostIndexMigration(t *testing.T) { + content, err := FS.ReadFile("249_add_usage_logs_api_key_cost_index_notx.sql") + require.NoError(t, err) + + sql := strings.Join(strings.Fields(string(content)), " ") + require.Contains(t, sql, "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost") + require.Contains(t, sql, "ON usage_logs (api_key_id, created_at)") + require.Contains(t, sql, "INCLUDE (actual_cost)") +} diff --git a/frontend/src/views/user/KeysView.vue b/frontend/src/views/user/KeysView.vue index dd779a0a8d..df56222ca2 100644 --- a/frontend/src/views/user/KeysView.vue +++ b/frontend/src/views/user/KeysView.vue @@ -212,13 +212,22 @@
{{ t('keys.today') }}: - + + ${{ (usageStats[row.id]?.today_actual_cost ?? 0).toFixed(4) }}
{{ t('keys.total') }}: - + + ${{ (usageStats[row.id]?.total_actual_cost ?? 0).toFixed(4) }}
@@ -1378,6 +1387,7 @@ const submitting = ref(false) const now = ref(new Date()) let resetTimer: ReturnType | null = null const usageStats = ref>({}) +const usageLoading = ref(false) const userGroupRates = ref>({}) const pagination = ref({ @@ -1589,6 +1599,7 @@ const loadApiKeys = async () => { abortController = controller const { signal } = controller loading.value = true + usageLoading.value = false try { // Build filters const filters: { @@ -1613,18 +1624,10 @@ const loadApiKeys = async () => { pagination.value.total = response.total pagination.value.pages = response.pages - // Load usage stats for all API keys in the list + // 用量统计要聚合 30 天的 usage_logs,可能比列表慢很多:不阻塞表格渲染,单独加载 + usageLoading.value = response.items.length > 0 if (response.items.length > 0) { - const keyIds = response.items.map((k) => k.id) - try { - const usageResponse = await usageAPI.getDashboardApiKeysUsage(keyIds, { signal }) - if (signal.aborted) return - usageStats.value = usageResponse.stats - } catch (e) { - if (!isAbortError(e)) { - console.error('Failed to load usage stats:', e) - } - } + void loadUsageStats(response.items.map((k) => k.id), signal) } } catch (error) { if (isAbortError(error)) { @@ -1638,6 +1641,22 @@ const loadApiKeys = async () => { } } +const loadUsageStats = async (keyIds: number[], signal: AbortSignal) => { + try { + const usageResponse = await usageAPI.getDashboardApiKeysUsage(keyIds, { signal }) + if (signal.aborted) return + usageStats.value = usageResponse.stats + } catch (e) { + if (!isAbortError(e)) { + console.error('Failed to load usage stats:', e) + } + } finally { + if (!signal.aborted) { + usageLoading.value = false + } + } +} + const loadGroups = async () => { try { groups.value = await userGroupsAPI.getAvailable() diff --git a/frontend/src/views/user/__tests__/KeysView.spec.ts b/frontend/src/views/user/__tests__/KeysView.spec.ts index ebf80be0a0..dbda4f4fc7 100644 --- a/frontend/src/views/user/__tests__/KeysView.spec.ts +++ b/frontend/src/views/user/__tests__/KeysView.spec.ts @@ -156,7 +156,7 @@ const TablePageLayoutStub = { const DataTableStub = { name: 'DataTable', - props: { columns: Array, data: Array, selectedKeys: Array, selectable: Boolean }, + props: { columns: Array, data: Array, selectedKeys: Array, selectable: Boolean, loading: Boolean }, emits: ['sort', 'update:selectedKeys'], template: `
@@ -177,6 +177,9 @@ const DataTableStub = {
+
+ +
{ expect(optionIds(wrapper)).toHaveLength(12) }) }) + + describe('usage stats loading', () => { + it('renders the key list without waiting for slow usage stats', async () => { + let resolveUsage!: (value: { stats: Record }) => void + getDashboardApiKeysUsage.mockReturnValue(new Promise((resolve) => { resolveUsage = resolve })) + const wrapper = await mountView() + + const table = wrapper.findComponent({ name: 'DataTable' }) + expect(table.props('loading')).toBe(false) + expect(table.props('data')).toHaveLength(1) + expect(wrapper.find('[data-test="usage-pending"]').exists()).toBe(true) + + resolveUsage({ + stats: { 1: { api_key_id: 1, today_actual_cost: 0.5, total_actual_cost: 12.25 } }, + }) + await flushPromises() + expect(wrapper.find('[data-test="usage-pending"]').exists()).toBe(false) + expect(wrapper.get('[data-test="usage"]').text()).toContain('$12.2500') + }) + + it('stops showing usage placeholders when the usage request fails', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + getDashboardApiKeysUsage.mockRejectedValue(new Error('timeout')) + const wrapper = await mountView() + + expect(wrapper.find('[data-test="usage-pending"]').exists()).toBe(false) + expect(wrapper.get('[data-test="usage"]').text()).toContain('$0.0000') + consoleError.mockRestore() + }) + }) }) From 390ba9905ae21cc2fbff3ad82006152b2c6c0772 Mon Sep 17 00:00:00 2001 From: ychy7001 <2043343224@qq.com> Date: Thu, 22 Oct 2026 11:37:53 +0800 Subject: [PATCH 04/33] =?UTF-8?q?fix(securityaudit):=20=E5=AE=A1=E8=AE=A1?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E5=85=A5=E9=98=9F=E5=90=8E=E7=AB=8B=E5=8D=B3?= =?UTF-8?q?=E5=94=A4=E9=86=92=E6=9C=AC=E8=BF=9B=E7=A8=8B=20worker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 异步审计 worker 每 500ms 轮询一次数据库认领任务,本进程刚入队的任务 平均要等约 250ms 才被处理。入队成功和租约回收后改为立即通知本进程的 worker 尝试认领;worker 启动时先认领一次遗留任务。500ms 轮询保留不变, 继续兜底到期重试和其他副本入队的任务。 --- .../internal/securityaudit/prompt_enqueue.go | 4 + .../internal/securityaudit/prompt_service.go | 1 + .../internal/securityaudit/prompt_worker.go | 67 ++++++++++----- .../securityaudit/prompt_worker_test.go | 2 + .../securityaudit/prompt_worker_wake_test.go | 81 +++++++++++++++++++ 5 files changed, 137 insertions(+), 18 deletions(-) create mode 100644 backend/internal/securityaudit/prompt_worker_wake_test.go diff --git a/backend/internal/securityaudit/prompt_enqueue.go b/backend/internal/securityaudit/prompt_enqueue.go index 625636c90e..6336b477dd 100644 --- a/backend/internal/securityaudit/prompt_enqueue.go +++ b/backend/internal/securityaudit/prompt_enqueue.go @@ -10,6 +10,7 @@ type Enqueuer struct { repo JobRepository payload PayloadStore metrics Metrics + notify func() } func NewEnqueuer(config ConfigStore, repo JobRepository, payload PayloadStore, metrics ...Metrics) *Enqueuer { @@ -82,6 +83,9 @@ func (e *Enqueuer) Enqueue(ctx context.Context, req Request) error { e.recordDropped() return err } + if e.notify != nil { + e.notify() + } LogInfo(EventJobEnqueued, mergeLogFields(baseFields, map[string]any{ "job_id": job.ID, "queue_capacity": cfg.QueueCapacity, "status": "queued", diff --git a/backend/internal/securityaudit/prompt_service.go b/backend/internal/securityaudit/prompt_service.go index a8cefcd648..322d3c75e3 100644 --- a/backend/internal/securityaudit/prompt_service.go +++ b/backend/internal/securityaudit/prompt_service.go @@ -42,6 +42,7 @@ func NewPromptService( enqueuer := NewEnqueuer(config, repo, payload, metrics) evaluator := NewGuardEvaluator(scanner, repo, metrics) runner := NewRunner(config, repo, payload, scanner, metrics) + enqueuer.notify = runner.Notify return &PromptService{ config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, enqueuer: enqueuer, evaluator: evaluator, runner: runner, clock: realClock{}, diff --git a/backend/internal/securityaudit/prompt_worker.go b/backend/internal/securityaudit/prompt_worker.go index 05ae828f05..89824299fb 100644 --- a/backend/internal/securityaudit/prompt_worker.go +++ b/backend/internal/securityaudit/prompt_worker.go @@ -8,6 +8,10 @@ import ( "time" ) +// workerIdlePoll is the fallback claim interval. Local enqueues also wake workers +// directly; polling still picks up retries that come due and jobs enqueued by other replicas. +const workerIdlePoll = 500 * time.Millisecond + type WorkerRuntime struct { active atomic.Int64 processed atomic.Int64 @@ -27,6 +31,7 @@ type Runner struct { metrics Metrics clock Clock runtime WorkerRuntime + wake []chan struct{} mu sync.Mutex cancel context.CancelFunc @@ -34,7 +39,27 @@ type Runner struct { } func NewRunner(config ConfigStore, repo JobRepository, payload PayloadStore, scanner PromptScanner, metrics Metrics) *Runner { - return &Runner{config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, clock: realClock{}} + wake := make([]chan struct{}, MaxWorkerCount) + for i := range wake { + // Pre-filled so each worker drains jobs left over from a previous run at start. + wake[i] = make(chan struct{}, 1) + wake[i] <- struct{}{} + } + return &Runner{config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, clock: realClock{}, wake: wake} +} + +// Notify wakes every worker to claim queued jobs. It never blocks; a worker that +// already has a pending wake-up keeps just one. +func (r *Runner) Notify() { + if r == nil { + return + } + for _, ch := range r.wake { + select { + case ch <- struct{}{}: + default: + } + } } func (r *Runner) Start(ctx context.Context) error { @@ -85,31 +110,36 @@ func (r *Runner) Shutdown(ctx context.Context) error { func (r *Runner) worker(ctx context.Context, workerID int) { defer r.wg.Done() - ticker := time.NewTicker(500 * time.Millisecond) + ticker := time.NewTicker(workerIdlePoll) defer ticker.Stop() + var wake <-chan struct{} + if workerID < len(r.wake) { + wake = r.wake[workerID] + } for { select { case <-ctx.Done(): return case <-ticker.C: - r.runtime.heartbeatNS.Store(r.clock.Now().UnixNano()) - cfg, ok := r.config.Active() - if !ok || !cfg.RiskControlEnabled || !cfg.Enabled || workerID >= cfg.WorkerCount { - continue + case <-wake: + } + r.runtime.heartbeatNS.Store(r.clock.Now().UnixNano()) + cfg, ok := r.config.Active() + if !ok || !cfg.RiskControlEnabled || !cfg.Enabled || workerID >= cfg.WorkerCount { + continue + } + for { + job, claimed, err := r.repo.ClaimNextJob(ctx, r.clock.Now()) + if err != nil { + r.setLastError("claim_job_failed", err.Error()) + break } - for { - job, claimed, err := r.repo.ClaimNextJob(ctx, r.clock.Now()) - if err != nil { - r.setLastError("claim_job_failed", err.Error()) - break - } - if !claimed { - break - } - r.runtime.active.Add(1) - r.processSafely(ctx, workerID, cfg, job) - r.runtime.active.Add(-1) + if !claimed { + break } + r.runtime.active.Add(1) + r.processSafely(ctx, workerID, cfg, job) + r.runtime.active.Add(-1) } } } @@ -273,6 +303,7 @@ func (r *Runner) reclaimer(ctx context.Context) { continue } if count > 0 { + r.Notify() LogWarn(EventProcessingReclaimed, map[string]any{"reclaimed_total": count, "status": "reclaimed"}) } } diff --git a/backend/internal/securityaudit/prompt_worker_test.go b/backend/internal/securityaudit/prompt_worker_test.go index a91569c2cf..a8de8833e8 100644 --- a/backend/internal/securityaudit/prompt_worker_test.go +++ b/backend/internal/securityaudit/prompt_worker_test.go @@ -84,6 +84,7 @@ type fakeJobRepository struct { refreshes int claimQueue []*Job + claims int recordBlockingCalls int recordBlockingSnapshot PromptSnapshot @@ -126,6 +127,7 @@ func (r *fakeJobRepository) MarkStagingFailed(_ context.Context, _ int64, code, func (r *fakeJobRepository) ClaimNextJob(context.Context, time.Time) (*Job, bool, error) { r.mu.Lock() defer r.mu.Unlock() + r.claims++ if len(r.claimQueue) == 0 { return nil, false, nil } diff --git a/backend/internal/securityaudit/prompt_worker_wake_test.go b/backend/internal/securityaudit/prompt_worker_wake_test.go new file mode 100644 index 0000000000..715aa43aa1 --- /dev/null +++ b/backend/internal/securityaudit/prompt_worker_wake_test.go @@ -0,0 +1,81 @@ +package securityaudit + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestEnqueuerNotifiesOnlyAfterPublish(t *testing.T) { + cases := []struct { + name string + publishErr error + want int + }{ + {name: "published", want: 1}, + {name: "publish failed", publishErr: errors.New("db down"), want: 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := &fakeJobRepository{createJob: &Job{ID: 41}, publishErr: tc.publishErr} + enqueuer := NewEnqueuer(&fakeConfigStore{cfg: asyncConfig(), active: true}, repo, &fakePayloadStore{values: map[int64]string{}}) + notified := 0 + enqueuer.notify = func() { notified++ } + _ = enqueuer.Enqueue(context.Background(), asyncRequest()) + require.Equal(t, tc.want, notified) + }) + } +} + +// Both cases must finish before the first fallback tick (workerIdlePoll), so they +// exercise the start-up drain and the wake path rather than polling. +func TestWorkerClaimsWithoutWaitingForIdlePoll(t *testing.T) { + newRunner := func(repo *fakeJobRepository) *Runner { + payload := &fakePayloadStore{values: map[int64]string{51: "abc"}} + return NewRunner(&fakeConfigStore{cfg: asyncConfig(), active: true}, repo, payload, PromptScannerFunc(func(context.Context, ActiveEndpoint, string, []string) (*NormalizedResult, error) { + return integrationResult(EventPass), nil + }), NewAtomicMetrics()) + } + completed := func(repo *fakeJobRepository) func() bool { + return func() bool { repo.mu.Lock(); defer repo.mu.Unlock(); return repo.completeCount == 1 } + } + stop := func(t *testing.T, runner *Runner) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + require.NoError(t, runner.Shutdown(ctx)) + } + + t.Run("jobs left from a previous run are drained at start", func(t *testing.T) { + repo := &fakeJobRepository{claimQueue: []*Job{workerJob(1, 3)}} + runner := newRunner(repo) + require.NoError(t, runner.Start(context.Background())) + defer stop(t, runner) + require.Eventually(t, completed(repo), workerIdlePoll/2, 5*time.Millisecond) + }) + + t.Run("notify wakes an idle worker", func(t *testing.T) { + repo := &fakeJobRepository{} + runner := newRunner(repo) + require.NoError(t, runner.Start(context.Background())) + defer stop(t, runner) + // wait for the start-up drain to find an empty queue + require.Eventually(t, func() bool { repo.mu.Lock(); defer repo.mu.Unlock(); return repo.claims > 0 }, workerIdlePoll/2, time.Millisecond) + repo.mu.Lock() + repo.claimQueue = append(repo.claimQueue, workerJob(1, 3)) + repo.mu.Unlock() + runner.Notify() + require.Eventually(t, completed(repo), workerIdlePoll/2, 5*time.Millisecond) + }) + + t.Run("notify never blocks", func(t *testing.T) { + runner := newRunner(&fakeJobRepository{}) + for i := 0; i < 3; i++ { + runner.Notify() + } + var nilRunner *Runner + nilRunner.Notify() + }) +} From 142d22cc4284678a729bce1a28986efcd175126c Mon Sep 17 00:00:00 2001 From: Anderson Date: Mon, 26 Oct 2026 18:03:52 +0800 Subject: [PATCH 05/33] fix(openai-ws): reconnect pooled OAuth sockets before search activation --- .../service/openai_ws_forwarder_ingress.go | 33 ++- backend/internal/service/openai_ws_pool.go | 6 + .../service/openai_ws_search_activation.go | 60 ++++++ .../openai_ws_search_activation_test.go | 202 ++++++++++++++++++ 4 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/openai_ws_search_activation.go create mode 100644 backend/internal/service/openai_ws_search_activation_test.go diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 10bb77450d..6fa1187851 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1255,7 +1255,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( Duration: time.Since(turnStart), FirstTokenMs: firstTokenMs, } - if replayInput := replayCollector.Items(); len(replayInput) > 0 { + replayInput := replayCollector.Items() + if account.IsOpenAIOAuthLike() && lease.initializedWithoutWebSearch() { + // Keep complete output while search activation can require a new socket. + replayInput = replayCollector.AllItems() + } + if len(replayInput) > 0 { result.wsReplayInput = replayInput result.wsReplayInputExists = true } @@ -1347,6 +1352,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( var lastTurnStrictState *openAIWSIngressPreviousTurnStrictState lastTurnReplayInput := []json.RawMessage(nil) lastTurnReplayInputExists := false + lastTurnReplayInputComplete := false currentTurnReplayInput := []json.RawMessage(nil) currentTurnReplayInputExists := false skipBeforeTurn := false @@ -1562,6 +1568,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentPayload, currentPreviousResponseID != "", ) + currentTurnReplayInputComplete := replayInputErr == nil && (currentPreviousResponseID == "" || + (lastTurnReplayInputComplete && currentPreviousResponseID == lastTurnResponseID)) if replayInputErr != nil { logOpenAIWSModeInfo( "ingress_ws_replay_input_skip account_id=%d turn=%d conn_id=%s reason=build_error cause=%s", @@ -1678,6 +1686,28 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( unpinSessionConn(sessionConnID) } } + if account.IsOpenAIOAuthLike() && sessionLease.initializedWithoutWebSearch() && openAIWSWebSearchDeclared(currentPayload) { + fullPayload, safe, err := buildOpenAIWSCurrentTurnRetryPayload(currentPayload, currentTurnReplayInput, currentTurnReplayInputExists, "") + if err != nil { + return fmt.Errorf("rebuild websocket input for web search activation: %w", err) + } + if !safe || !currentTurnReplayInputComplete { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "web search activation requires complete input history; please reconnect with full input", nil) + } + logOpenAIWSModeInfo("ingress_ws_web_search_activation account_id=%d turn=%d action=reconnect", account.ID, turn) + resetSessionLease(true) + acquiredLease, acquireErr := acquireTurnLease(turn, "", false, true) + if acquireErr != nil { + return fmt.Errorf("acquire upstream websocket for web search activation: %w", acquireErr) + } + sessionLease = acquiredLease + sessionConnID = strings.TrimSpace(sessionLease.ConnID()) + pinSessionConn(sessionConnID) + currentPayload = fullPayload + currentPayloadBytes = len(fullPayload) + currentPreviousResponseID = "" + forcePreferredConn = false + } shouldPreflightPing := turn > 1 && sessionLease != nil && sessionLease.SupportsIdlePingWithoutReader() && turnRetry == 0 if shouldPreflightPing && openAIWSIngressPreflightPingIdle > 0 && !lastTurnFinishedAt.IsZero() { if time.Since(lastTurnFinishedAt) < openAIWSIngressPreflightPingIdle { @@ -1857,6 +1887,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // collector 增量经 combine 合并(新头数组)。 lastTurnReplayInput = currentTurnReplayInput lastTurnReplayInputExists = currentTurnReplayInputExists + lastTurnReplayInputComplete = currentTurnReplayInputComplete if result.wsReplayInputExists { lastTurnReplayInput = combineOpenAIWSReplayItems(lastTurnReplayInput, result.wsReplayInput) lastTurnReplayInputExists = true diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index b632bba523..ae4e3fe2c7 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -292,6 +292,9 @@ type openAIWSConn struct { readMu sync.Mutex writeMu sync.Mutex + // The subscription backend fixes hosted-search support on the first create. + responseCreateSent bool // guarded by writeMu + initialWebSearch bool // guarded by writeMu // readerLoopResults 非 nil 表示池为该连接常驻了读循环:coder/websocket 只在 // 阻塞读期间应答上游 ping,空闲连接没有读循环会被上游按保活超时关闭。 @@ -600,6 +603,9 @@ func (c *openAIWSConn) writeJSON(value any, writeCtx context.Context) error { if err := c.ws.WriteJSON(writeCtx, value); err != nil { return err } + if !c.responseCreateSent { + c.recordInitialWebSearch(value) + } c.touch() return nil } diff --git a/backend/internal/service/openai_ws_search_activation.go b/backend/internal/service/openai_ws_search_activation.go new file mode 100644 index 0000000000..6d1e640c11 --- /dev/null +++ b/backend/internal/service/openai_ws_search_activation.go @@ -0,0 +1,60 @@ +package service + +import ( + "encoding/json" + + "github.com/tidwall/gjson" +) + +func openAIWSWebSearchDeclared(payload []byte) bool { + fields := gjson.GetMany(openAIWSPayloadStringView(payload), "tools", "input") + if gjsonToolsContainWebSearch(fields[0]) { + return true + } + for _, item := range fields[1].Array() { + if item.Get("type").String() == openAIAdditionalToolsItemType && gjsonToolsContainWebSearch(item.Get("tools")) { + return true + } + } + return false +} + +// Called under writeMu, only after the first response.create was written. +func (c *openAIWSConn) recordInitialWebSearch(value any) { + var body []byte + switch payload := value.(type) { + case json.RawMessage: + body = payload + case []byte: + body = payload + case map[string]any: + if payload["type"] != "response.create" { + return + } + c.responseCreateSent = true + c.initialWebSearch = openAIToolsContainWebSearch(payload["tools"]) + input, _ := payload["input"].([]any) + for _, raw := range input { + if item, ok := raw.(map[string]any); ok && item["type"] == openAIAdditionalToolsItemType && openAIToolsContainWebSearch(item["tools"]) { + c.initialWebSearch = true + } + } + return + default: + return + } + if gjson.GetBytes(body, "type").String() == "response.create" { + c.responseCreateSent = true + c.initialWebSearch = openAIWSWebSearchDeclared(body) + } +} + +func (l *openAIWSConnLease) initializedWithoutWebSearch() bool { + c, err := l.activeConn() + if err != nil { + return false + } + c.writeMu.Lock() + defer c.writeMu.Unlock() + return c.responseCreateSent && !c.initialWebSearch +} diff --git a/backend/internal/service/openai_ws_search_activation_test.go b/backend/internal/service/openai_ws_search_activation_test.go new file mode 100644 index 0000000000..d45387b050 --- /dev/null +++ b/backend/internal/service/openai_ws_search_activation_test.go @@ -0,0 +1,202 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIWSIngressWebSearchActivation(t *testing.T) { + const search = `,"tools":[{"type":"web_search","external_web_access":false}]` + const userInput = `[{"type":"message","role":"user","content":"continue"}]` + const toolOutput = `[{"type":"function_call_output","call_id":"fc_lookup","output":"42"}]` + const firstOutput = `[{"type":"reasoning","id":"rs_first","summary":[{"type":"summary_text","text":"Keep this reasoning"}]},{"type":"message","id":"msg_first","role":"assistant","content":[{"type":"output_text","text":"Keep this answer"}]},{"type":"function_call","id":"fc_lookup","call_id":"fc_lookup","name":"lookup","arguments":"{}"}]` + for _, tc := range []struct { + name string + accountType string + firstFields string + firstInput string + firstOutput string + nextFields string + nextInput string + nextPrevious string + wantReconnect bool + wantFailClose bool + wantTypes []string + }{ + {name: "empty OAuth prewarm", accountType: AccountTypeOAuth, firstFields: `,"generate":false`, nextFields: search, nextInput: userInput, wantReconnect: true, wantTypes: []string{"message"}}, + {name: "Lite search history injection", accountType: AccountTypeOAuth, firstFields: `,"generate":false`, nextFields: `,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}`, nextInput: `[{"type":"web_search_call","id":"ws_history","status":"completed","action":{"type":"search","query":"example"}},{"type":"message","role":"user","content":"continue"}]`, wantReconnect: true, wantTypes: []string{"web_search_call", "message", "additional_tools"}}, + {name: "tool continuation preserves all output", accountType: AccountTypeOAuth, firstFields: `,"tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, firstInput: `[{"type":"message","role":"user","content":"Run lookup for my original question"}]`, firstOutput: firstOutput, nextFields: search, nextInput: toolOutput, wantReconnect: true, wantTypes: []string{"message", "reasoning", "message", "function_call", "function_call_output"}}, + {name: "search initialized socket", accountType: AccountTypeOAuth, firstFields: search, nextFields: search, nextInput: userInput}, + {name: "API key provider", accountType: AccountTypeAPIKey, firstFields: `,"generate":false`, nextFields: search, nextInput: userInput}, + {name: "function called web_search", accountType: AccountTypeOAuth, nextFields: `,"tools":[{"type":"function","name":"web_search","parameters":{"type":"object"}}]`, nextInput: userInput}, + {name: "missing tool context fails closed", accountType: AccountTypeOAuth, nextFields: search, nextInput: toolOutput, wantFailClose: true}, + {name: "unknown response history fails closed", accountType: AccountTypeOAuth, nextFields: search, nextInput: userInput, nextPrevious: "resp_unknown", wantFailClose: true}, + } { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 2 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 2 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + output := tc.firstOutput + if output == "" { + output = "[]" + } + events := [][]byte{ + []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_first","model":"gpt-6.1-sol","output":%s,"usage":{"input_tokens":1,"output_tokens":1}}}`, output)), + []byte(`{"type":"response.completed","response":{"id":"resp_second","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_third","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_fourth","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + } + first := &openAIWSCaptureConn{events: append([][]byte(nil), events...)} + second := &openAIWSCaptureConn{events: append([][]byte(nil), events[1:]...)} + dialer := &openAIWSQueueDialer{conns: []openAIWSClientConn{first, second}} + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(dialer) + t.Cleanup(pool.Close) + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), openaiWSPool: pool} + account := &Account{ID: 71, Platform: PlatformOpenAI, Type: tc.accountType, Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token", "api_key": "test-token"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}} + serverErr := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + serverErr <- err + return + } + defer conn.CloseNow() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + _, payload, err := conn.Read(ctx) + if err == nil { + err = svc.ProxyResponsesWebSocketFromClient(ctx, c, conn, account, "test-token", payload, nil) + } + serverErr <- err + })) + defer server.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer client.CloseNow() + write := func(fields, input string) { + payload := fmt.Sprintf(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"input":%s%s}`, input, fields) + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(payload))) + } + read := func(id string) { + _, event, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, id, gjson.GetBytes(event, "response.id").String()) + } + input := tc.firstInput + if input == "" { + input = "[]" + } + write(tc.firstFields, input) + read("resp_first") + previous := tc.nextPrevious + if previous == "" { + previous = "resp_first" + } + write(fmt.Sprintf(`,"previous_response_id":%q`, previous)+tc.nextFields, tc.nextInput) + if tc.wantFailClose { + _, _, err := client.Read(ctx) + require.Error(t, err) + require.Error(t, <-serverErr) + require.Len(t, first.writes, 1, "unsafe continuation must not reach upstream") + return + } + read("resp_second") + // Removing and restoring search must keep the search-initialized socket. + write(`,"previous_response_id":"resp_second"`, userInput) + read("resp_third") + write(`,"previous_response_id":"resp_third"`+tc.nextFields, userInput) + read("resp_fourth") + require.NoError(t, client.Close(coderws.StatusNormalClosure, "done")) + require.NoError(t, <-serverErr) + if !tc.wantReconnect { + require.Equal(t, 1, dialer.DialCount()) + require.Len(t, first.writes, 4) + return + } + require.Equal(t, 2, dialer.DialCount()) + require.Len(t, first.writes, 1, "search must never be sent on the incompatible socket") + require.Len(t, second.writes, 3) + forwarded, err := json.Marshal(second.writes[0]) + require.NoError(t, err) + require.False(t, gjson.GetBytes(forwarded, "previous_response_id").Exists()) + var types []string + for _, item := range gjson.GetBytes(forwarded, "input").Array() { + types = append(types, item.Get("type").String()) + } + require.Equal(t, tc.wantTypes, types) + if tc.firstOutput != "" { + require.Contains(t, string(forwarded), "Run lookup for my original question") + require.Contains(t, string(forwarded), "Keep this reasoning") + require.Contains(t, string(forwarded), "Keep this answer") + require.Contains(t, string(forwarded), `"output":"42"`) + } + }) + } +} + +func TestOpenAIWSConnWebSearchInitialization(t *testing.T) { + const search = `{"type":"response.create","tools":[{"type":"web_search"}]}` + for _, first := range []struct { + name string + body string + wantReconnect bool + }{ + {"empty prewarm", `{"type":"response.create","generate":false,"input":[]}`, true}, + {"hosted search", search, false}, + {"Lite hosted search", `{"type":"response.create","input":[{"type":"additional_tools","tools":[{"type":"web_search"}]}]}`, false}, + {"function lookalike", `{"type":"response.create","tools":[{"type":"function","name":"web_search"}]}`, true}, + } { + for _, format := range []string{"map", "raw", "bytes"} { + t.Run(first.name+"/"+format, func(t *testing.T) { + conn := newOpenAIWSConn("test", 1, &openAIWSCaptureConn{}, nil) + defer conn.close() + lease := &openAIWSConnLease{conn: conn} + require.False(t, lease.initializedWithoutWebSearch(), "an unused socket is compatible") + var payload any + switch format { + case "map": + require.NoError(t, json.Unmarshal([]byte(first.body), &payload)) + case "raw": + payload = json.RawMessage(first.body) + case "bytes": + payload = []byte(first.body) + } + require.NoError(t, lease.WriteJSON(payload, time.Second)) + // Capability belongs to the socket, even after it is leased again. + lease = &openAIWSConnLease{conn: conn} + require.Equal(t, first.wantReconnect, lease.initializedWithoutWebSearch()) + require.NoError(t, lease.WriteJSON(json.RawMessage(search), time.Second)) + require.Equal(t, first.wantReconnect, lease.initializedWithoutWebSearch(), "later writes cannot change initial capability") + }) + } + } +} From 9c7380732df8ad4420b8be161504552a52b585a5 Mon Sep 17 00:00:00 2001 From: Anderson Date: Mon, 26 Oct 2026 18:24:38 +0800 Subject: [PATCH 06/33] test(openai-ws): explicitly discard deferred close errors --- backend/internal/service/openai_ws_search_activation_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_ws_search_activation_test.go b/backend/internal/service/openai_ws_search_activation_test.go index d45387b050..30fe9f0326 100644 --- a/backend/internal/service/openai_ws_search_activation_test.go +++ b/backend/internal/service/openai_ws_search_activation_test.go @@ -85,7 +85,7 @@ func TestOpenAIWSIngressWebSearchActivation(t *testing.T) { serverErr <- err return } - defer conn.CloseNow() + defer func() { _ = conn.CloseNow() }() c, _ := gin.CreateTestContext(httptest.NewRecorder()) c.Request = r ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) @@ -101,7 +101,7 @@ func TestOpenAIWSIngressWebSearchActivation(t *testing.T) { defer cancel() client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) require.NoError(t, err) - defer client.CloseNow() + defer func() { _ = client.CloseNow() }() write := func(fields, input string) { payload := fmt.Sprintf(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"input":%s%s}`, input, fields) require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(payload))) From 5965ac4e93a83d5386dee8981b47f81c1ab3c1b5 Mon Sep 17 00:00:00 2001 From: Jelvin Date: Tue, 27 Oct 2026 10:35:40 +0800 Subject: [PATCH 07/33] =?UTF-8?q?feat(settings):=20=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E4=BF=9D=E5=AD=98=E6=8C=89=E9=92=AE=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=BA=95=E9=83=A8=E5=90=B8=E9=99=84=E6=B5=AE=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 各 tab 表单很长,保存按钮只在滚到最底部时可见。改为 sticky 浮标贴在视口右下角, 样式沿用已有 tab 导航条的毛玻璃胶囊语言,深色模式覆盖放在非 scoped 块内。 --- frontend/src/views/admin/SettingsView.vue | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue index 5c344267fa..c878e42b0c 100644 --- a/frontend/src/views/admin/SettingsView.vue +++ b/frontend/src/views/admin/SettingsView.vue @@ -8901,8 +8901,8 @@
- -
+ +