mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
Merge origin/main into PR #9197
This commit is contained in:
commit
a08eb02ff8
84 files changed
+3423
-300
No files matched your search
+1
-1
@@ -55,7 +55,7 @@ require (
|
||||
github.com/zeromicro/go-zero v1.9.4
|
||||
go.uber.org/zap v1.24.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/image v0.45.0
|
||||
golang.org/x/mod v0.41.0
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/sync v0.24.0
|
||||
|
||||
@@ -591,6 +591,8 @@ golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
|
||||
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
|
||||
@@ -12,4 +12,11 @@ type GroupCodexModelsManifestConfig struct {
|
||||
// usable or all upstream fetches fail: fall back to the scheduler loop
|
||||
// (true) or return the upstream error / 503 (false, default).
|
||||
FallbackToScheduler bool `json:"fallback_to_scheduler,omitempty"`
|
||||
// KeepHiddenAutoModes keeps Codex automatic modes (codex-auto-*) that the
|
||||
// upstream manifest already hides from the picker, byte-for-byte, instead
|
||||
// of removing them when the group model list does not select them. Codex
|
||||
// then reviews approvals with its dedicated reviewer model, and an
|
||||
// otherwise untouched upstream manifest keeps the upstream ETag. It applies
|
||||
// to manifests fetched from upstream, with or without pinned accounts.
|
||||
KeepHiddenAutoModes bool `json:"keep_hidden_auto_modes,omitempty"`
|
||||
}
|
||||
@@ -646,16 +646,6 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// platformLiteLLMProvider maps a channel platform name to the corresponding
|
||||
// LiteLLM provider string used as the key in the pricing catalog (platform list).
|
||||
func platformLiteLLMProvider(platform string) (string, bool) {
|
||||
spec, ok := domain.LookupPlatform(platform)
|
||||
if !ok || spec.LiteLLMProvider == "" {
|
||||
return "", false
|
||||
}
|
||||
return spec.LiteLLMProvider, true
|
||||
}
|
||||
|
||||
// SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表
|
||||
// GET /api/v1/admin/channels/pricing/sync-models?platform=anthropic
|
||||
func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
|
||||
@@ -666,14 +656,14 @@ func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
provider, ok := platformLiteLLMProvider(platform)
|
||||
if !ok {
|
||||
spec, ok := domain.LookupPlatform(platform)
|
||||
if !ok || spec.LiteLLMProvider == "" {
|
||||
response.ErrorFrom(c, infraerrors.BadRequest("UNSUPPORTED_PLATFORM",
|
||||
fmt.Sprintf("unsupported platform: %s", platform)).
|
||||
WithMetadata(map[string]string{"param": "platform"}))
|
||||
return
|
||||
}
|
||||
|
||||
models := h.pricingService.ListModelNamesByProvider(provider)
|
||||
models := h.pricingService.ListModelNamesForPlatform(spec)
|
||||
response.Success(c, gin.H{"models": models})
|
||||
}
|
||||
@@ -547,7 +547,8 @@ func (h *SettingHandler) TestWebSearchEmulation(c *gin.Context) {
|
||||
|
||||
result, err := service.TestWebSearch(c.Request.Context(), req.Query)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
// Like the SMTP test, return the cause so the admin can fix the provider config.
|
||||
response.BadRequest(c, "Web search test failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
response.Success(c, result)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTestWebSearchEmulationReturnsFailureCause(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
service.SetWebSearchManager(nil)
|
||||
t.Cleanup(func() { service.SetWebSearchManager(nil) })
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/settings/web-search-emulation/test", bytes.NewBufferString(`{"query":"golang"}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
(&SettingHandler{}).TestWebSearchEmulation(c)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
var body struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
|
||||
require.Contains(t, body.Message, "Web search test failed")
|
||||
require.Contains(t, body.Message, "save config first", "the admin must see why the test failed, not a generic internal error")
|
||||
}
|
||||
@@ -17,6 +17,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
|
||||
Enabled: true,
|
||||
AccountIDs: []int64{101, 202},
|
||||
FallbackToScheduler: true,
|
||||
KeepHiddenAutoModes: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -27,6 +28,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
|
||||
Enabled bool `json:"enabled"`
|
||||
AccountIDs []int64 `json:"account_ids"`
|
||||
FallbackToScheduler bool `json:"fallback_to_scheduler"`
|
||||
KeepHiddenAutoModes bool `json:"keep_hidden_auto_modes"`
|
||||
} `json:"codex_models_manifest_config"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(adminJSON, &adminEnvelope))
|
||||
@@ -34,6 +36,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
|
||||
require.True(t, adminEnvelope.CodexModelsManifestConfig.Enabled)
|
||||
require.Equal(t, []int64{101, 202}, adminEnvelope.CodexModelsManifestConfig.AccountIDs)
|
||||
require.True(t, adminEnvelope.CodexModelsManifestConfig.FallbackToScheduler)
|
||||
require.True(t, adminEnvelope.CodexModelsManifestConfig.KeepHiddenAutoModes)
|
||||
|
||||
userJSON, err := json.Marshal(GroupFromService(group))
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -7,17 +7,33 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
|
||||
|
||||
// codexContextTagName is the shape of the context names Codex derives from
|
||||
// its context keys; only such names are safe to embed in a tag.
|
||||
var codexContextTagName = regexp.MustCompile(`^[A-Za-z0-9_]{1,128}$`)
|
||||
|
||||
// mayContainCodexAgentContext is the cheap gate for agent context outputs.
|
||||
// Names are not enumerated: Codex keeps adding context tools, and any agent
|
||||
// namespace output without a call_id is injected context, not a tool result.
|
||||
// The type and namespace are JSON strings, which appear literally unless a
|
||||
// \u escape spells their letters; without either the body cannot match.
|
||||
func mayContainCodexAgentContext(body []byte) bool {
|
||||
if !service.JSONMayEscapePlainASCII(body) &&
|
||||
(!bytes.Contains(body, []byte("function_call_output")) || !bytes.Contains(body, []byte("agent"))) {
|
||||
return false
|
||||
}
|
||||
return service.ResponsesInputHasAgentFunctionCallOutput(body)
|
||||
}
|
||||
|
||||
// Codex injects external context as standalone outputs, without a model tool call.
|
||||
// Use the legacy user-message representation for HTTP Responses interoperability.
|
||||
func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
if !mayContainCodexCallOutputCandidate(body,
|
||||
"codex_apps_open_page", "codex_apps_selected_page_part_",
|
||||
"browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan",
|
||||
) || !hasUniqueJSONMembers(body) {
|
||||
if !mayContainCodexAgentContext(body) || !hasUniqueJSONMembers(body) {
|
||||
return body, false
|
||||
}
|
||||
var request map[string]json.RawMessage
|
||||
@@ -50,12 +66,12 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
}
|
||||
name := readString("name")
|
||||
var output *string
|
||||
if json.Unmarshal(item["output"], &output) != nil || output == nil || !validCodexUntrustedContext(name, *output) {
|
||||
if json.Unmarshal(item["output"], &output) != nil || output == nil {
|
||||
continue
|
||||
}
|
||||
text := "<external_" + name + ">" + *output + "</external_" + name + ">"
|
||||
if validCodexPageContext(name, *output) {
|
||||
text = "<external_" + name + ">\n" + *output + "\n</external_" + name + ">"
|
||||
text, ok := codexUntrustedContextText(name, *output)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
message := map[string]any{
|
||||
"type": "message",
|
||||
@@ -87,9 +103,42 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
// codexUntrustedContextText renders an agent context output as user text.
|
||||
// Known context names keep their existing tags and format checks. Any other
|
||||
// name is still context when it comes from the agent namespace, so it is
|
||||
// rendered the way Codex renders context when it does not send it as a tool
|
||||
// output: <external_{name}>. The name is client supplied, so it is only used
|
||||
// as a tag when it has the shape Codex derives names in; anything else falls
|
||||
// back to a generic tag.
|
||||
func codexUntrustedContextText(name, output string) (string, bool) {
|
||||
if !knownCodexUntrustedContextName(name) {
|
||||
tag := "agent_context"
|
||||
if codexContextTagName.MatchString(name) {
|
||||
tag = name
|
||||
}
|
||||
return "<external_" + tag + ">" + output + "</external_" + tag + ">", true
|
||||
}
|
||||
if !validCodexUntrustedContext(name, output) {
|
||||
return "", false
|
||||
}
|
||||
text := "<external_" + name + ">" + output + "</external_" + name + ">"
|
||||
if validCodexPageContext(name, output) {
|
||||
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
|
||||
}
|
||||
return text, true
|
||||
}
|
||||
|
||||
func knownCodexUntrustedContextName(name string) bool {
|
||||
switch name {
|
||||
case "codex_apps_open_page", "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan":
|
||||
return true
|
||||
}
|
||||
return codexSelectedPageName.MatchString(name)
|
||||
}
|
||||
|
||||
func validCodexUntrustedContext(name, output string) bool {
|
||||
switch name {
|
||||
case "browser_info", "terminal_info", "goal_objective", "untrusted_context", "ide_context":
|
||||
case "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "ide_context":
|
||||
return strings.TrimSpace(output) != ""
|
||||
case "untrusted_content":
|
||||
// Codex's fallback for an unnamed context source can carry any text, including an empty value.
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -54,7 +55,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
|
||||
require.Equal(t, got, again)
|
||||
}
|
||||
|
||||
var codexTextContextNamesForTest = []string{"browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
|
||||
var codexTextContextNamesForTest = []string{"browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
|
||||
|
||||
func TestNormalizeCodexTerminalInfoIssue8991(t *testing.T) {
|
||||
body := []byte(`{"model":"deepseek-flash","input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"retest context"}]}`)
|
||||
@@ -89,9 +90,6 @@ func TestNormalizeCodexTerminalInfoBoundaries(t *testing.T) {
|
||||
{"boolean output", "output", false},
|
||||
{"numeric output", "output", 42},
|
||||
{"object output", "output", map[string]any{"text": "context"}},
|
||||
{"name prefix", "name", "terminal_info_extra"},
|
||||
{"name case", "name", "Terminal_info"},
|
||||
{"unknown context", "name", "arbitrary_context"},
|
||||
{"other type", "type", "custom_tool_call_output"},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
@@ -126,7 +124,7 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) {
|
||||
body := pageContextRequest(t,
|
||||
pageContextItem("terminal_info", "retest context"),
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info", "call_id": "call_real", "output": "real result"},
|
||||
pageContextItem("read_file", "unrelated result"))
|
||||
map[string]any{"type": "function_call_output", "name": "read_file", "output": "unrelated result"})
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
|
||||
@@ -141,6 +139,103 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) {
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextUnknownNames(t *testing.T) {
|
||||
const browserTabs = `{"tabs":[{"title":"Example","url":"https://example.com"}]}`
|
||||
longName := strings.Repeat("a", 129)
|
||||
body := pageContextRequest(t,
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": browserTabs},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "some_new_context", "output": "new context"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info_extra", "output": "suffix name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "Terminal_info", "output": "case name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "bad>name</x", "output": "unsafe name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "output": "missing name"},
|
||||
map[string]any{"type": "function_call_output", "namespace": "agent", "name": longName, "output": ""},
|
||||
map[string]any{"role": "user", "content": "hello"},
|
||||
)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.False(t, c.Writer.Written())
|
||||
for i, want := range []struct{ tag, output string }{
|
||||
{"browser_tabs", browserTabs},
|
||||
{"some_new_context", "new context"},
|
||||
{"terminal_info_extra", "suffix name"},
|
||||
{"Terminal_info", "case name"},
|
||||
{"agent_context", "unsafe name"},
|
||||
{"agent_context", "missing name"},
|
||||
{"agent_context", ""},
|
||||
} {
|
||||
item := gjson.GetBytes(got, "input").Array()[i]
|
||||
require.Equal(t, "message", item.Get("type").String())
|
||||
require.Equal(t, "user", item.Get("role").String())
|
||||
require.Equal(t, "<external_"+want.tag+">"+want.output+"</external_"+want.tag+">", item.Get("content.0.text").String())
|
||||
require.False(t, item.Get("call_id").Exists())
|
||||
require.False(t, item.Get("id").Exists())
|
||||
}
|
||||
require.Equal(t, "hello", gjson.GetBytes(got, "input.7.content").String())
|
||||
again, changed := normalizeCodexUntrustedContext(got)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, got, again)
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextEscapedAndBlankCallID(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"input":[{"type":"function_call_output","namespace":"\u0061gent","name":"browser_tabs","output":"tabs"}]}`,
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":" ","output":"tabs"}]}`,
|
||||
} {
|
||||
got, changed := normalizeCodexUntrustedContext([]byte(body))
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "<external_browser_tabs>tabs</external_browser_tabs>", gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextKeepsToolOutputsRejected(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
item map[string]any
|
||||
}{
|
||||
{"no namespace", map[string]any{"type": "function_call_output", "name": "read_file", "output": "file body"}},
|
||||
{"other namespace", map[string]any{"type": "function_call_output", "namespace": "codex_app", "name": "read_file", "output": "file body"}},
|
||||
{"non-string output", map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": []any{map[string]any{"url": "https://example.com"}}}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
body := pageContextRequest(t, testCase.item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAgentContextLeavesCallIDItems(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":"call_real","output":"tabs"}]}`)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
// Items with a call_id keep the original validation path.
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "item_reference")
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
|
||||
for _, name := range codexTextContextNamesForTest {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
@@ -209,7 +304,7 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput
|
||||
}
|
||||
// Recognized external context cannot make an unrelated tool result valid.
|
||||
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
|
||||
pageContextItem("read_file", "result"))
|
||||
map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"})
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
@@ -304,7 +399,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
|
||||
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
|
||||
}
|
||||
|
||||
badTool := pageContextItem("read_file", "result")
|
||||
badTool := map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"}
|
||||
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
|
||||
got, changed = normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
@@ -346,7 +441,6 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
{"null call id", "call_id", nil},
|
||||
{"other namespace", "namespace", "codex_app"},
|
||||
{"missing namespace", "namespace", ""},
|
||||
{"other tool", "name", "read_file"},
|
||||
{"other type", "type", "custom_tool_call_output"},
|
||||
{"not JSON", "output", "some text"},
|
||||
{"not snapshot", "output", `{"other":null}`},
|
||||
@@ -373,3 +467,62 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexBrowserTabs(t *testing.T) {
|
||||
// Shape sent by the Codex desktop in-app browser: an agent-namespace output
|
||||
// with an item id but no call_id, followed by the user's question.
|
||||
tabs := "<in-app-browser-context source=\"ambient-ui-state\">\nTab 1 (active): https://example.com/\nTab 2: https://example.org/\n</in-app-browser-context>"
|
||||
body := pageContextRequest(t,
|
||||
map[string]any{"type": "function_call_output", "id": "fco_123", "namespace": "agent", "name": "browser_tabs", "output": tabs},
|
||||
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "How many tabs are open?"}}})
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
|
||||
require.Equal(t, "user", gjson.GetBytes(got, "input.0.role").String())
|
||||
require.Equal(t, "<external_browser_tabs>"+tabs+"</external_browser_tabs>", gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
require.JSONEq(t, gjson.GetBytes(body, "input.1").Raw, gjson.GetBytes(got, "input.1").Raw)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.False(t, c.Writer.Written())
|
||||
}
|
||||
|
||||
func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
key string
|
||||
value any
|
||||
}{
|
||||
{"real call id", "call_id", "call_real"},
|
||||
{"other namespace", "namespace", "browser"},
|
||||
{"empty output", "output", ""},
|
||||
{"blank output", "output", " \n\t"},
|
||||
{"object output", "output", map[string]any{"tabs": 2}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
item := pageContextItem("browser_tabs", "Tab 1: https://example.com/")
|
||||
item[testCase.key] = testCase.value
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexBrowserTabsNameVariantsUseOwnTag(t *testing.T) {
|
||||
for _, name := range []string{"browser_tabs_extra", "Browser_tabs"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
body := pageContextRequest(t, pageContextItem(name, "Tab 1: https://example.com/"))
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "<external_"+name+">Tab 1: https://example.com/</external_"+name+">", gjson.GetBytes(got, "input.0.content.0.text").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -421,9 +421,21 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans
|
||||
}
|
||||
|
||||
// buildContents 构建 contents
|
||||
//
|
||||
// {role: "system"} messages before the first model turn are the conversation's
|
||||
// standing context and go to systemInstruction. Later ones are notices an agent
|
||||
// client adds as the conversation goes on (Claude Code adds one after each tool
|
||||
// result); they stay at their place as user text. systemInstruction precedes
|
||||
// the contents in the prompt, and Gemini's implicit cache only matches a prompt
|
||||
// prefix, so a notice appended there would change every request's prefix and
|
||||
// leave the whole conversation uncached.
|
||||
func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isThinkingEnabled, allowDummyThought, multimodalToolResults bool) ([]GeminiContent, []GeminiPart, bool, error) {
|
||||
var contents []GeminiContent
|
||||
var systemParts []GeminiPart
|
||||
// Notices that follow a model turn wait for the next user turn: a
|
||||
// functionCall must be followed directly by its functionResponse.
|
||||
var pendingNotices []GeminiPart
|
||||
seenModel := false
|
||||
strippedThinking := false
|
||||
|
||||
for i, msg := range messages {
|
||||
@@ -441,10 +453,31 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT
|
||||
}
|
||||
|
||||
if role == "system" {
|
||||
systemParts = append(systemParts, parts...)
|
||||
parts = trimSystemTextParts(parts)
|
||||
if !seenModel {
|
||||
systemParts = append(systemParts, parts...)
|
||||
continue
|
||||
}
|
||||
notice := systemReminderParts(parts)
|
||||
if n := len(contents); n > 0 && contents[n-1].Role == "user" && len(pendingNotices) == 0 {
|
||||
contents[n-1].Parts = append(contents[n-1].Parts, notice...)
|
||||
} else {
|
||||
pendingNotices = append(pendingNotices, notice...)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if role == "model" {
|
||||
seenModel = true
|
||||
if len(pendingNotices) > 0 {
|
||||
contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices})
|
||||
pendingNotices = nil
|
||||
}
|
||||
} else if len(pendingNotices) > 0 {
|
||||
parts = append(parts, pendingNotices...)
|
||||
pendingNotices = nil
|
||||
}
|
||||
|
||||
// 只有 Gemini 模型支持 dummy thinking block workaround
|
||||
// 只对最后一条 assistant 消息添加(Pre-fill 场景)
|
||||
// 历史 assistant 消息不能添加没有 signature 的 dummy thinking block
|
||||
@@ -475,10 +508,48 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT
|
||||
Parts: parts,
|
||||
})
|
||||
}
|
||||
if len(pendingNotices) > 0 {
|
||||
contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices})
|
||||
}
|
||||
|
||||
return contents, systemParts, strippedThinking, nil
|
||||
}
|
||||
|
||||
// trimSystemTextParts renders a system message's text the same way whether
|
||||
// the client sent it as a string (which buildParts trims) or as text blocks:
|
||||
// Claude Code sends its newest system message as blocks with cache_control and
|
||||
// the same message as a string once it is history.
|
||||
func trimSystemTextParts(parts []GeminiPart) []GeminiPart {
|
||||
out := parts[:0]
|
||||
for _, p := range parts {
|
||||
if isPlainTextPart(p) {
|
||||
p.Text = strings.TrimSpace(p.Text)
|
||||
if p.Text == "" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// systemReminderParts marks a system notice placed in a user turn the way
|
||||
// agent clients mark harness text in user turns.
|
||||
func systemReminderParts(parts []GeminiPart) []GeminiPart {
|
||||
out := make([]GeminiPart, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if isPlainTextPart(p) {
|
||||
p.Text = "<system-reminder>\n" + p.Text + "\n</system-reminder>"
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isPlainTextPart(p GeminiPart) bool {
|
||||
return !p.Thought && p.InlineData == nil && p.FunctionCall == nil && p.FunctionResponse == nil
|
||||
}
|
||||
|
||||
// DummyThoughtSignature 用于跳过 Gemini 3 thought_signature 验证
|
||||
// 参考: https://ai.google.dev/gemini-api/docs/thought-signatures
|
||||
// 导出供跨包使用(如 gemini_native_signature_cleaner 跨账号修复)
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/quick"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Messages shaped like Claude Code's: a {role: "system"} message with the
|
||||
// environment after the first user message, and another {role: "system"}
|
||||
// notice after every tool result. The newest system message carries
|
||||
// cache_control as a block list; once it is history the client sends it as a
|
||||
// plain string.
|
||||
const (
|
||||
ccAsk = `{"role":"user","content":[{"type":"text","text":"read f.txt"}]}`
|
||||
ccEnvLatest = `{"role":"system","content":[{"type":"text","text":"# Environment\nPrimary working directory: /repo","cache_control":{"type":"ephemeral"}}]}`
|
||||
ccEnv = `{"role":"system","content":"# Environment\nPrimary working directory: /repo"}`
|
||||
ccCall1 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/repo/f.txt"}}]}`
|
||||
ccResult1 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"hello"}]}`
|
||||
ccCall2 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_2","name":"Read","input":{"file_path":"/repo/g.txt"}}]}`
|
||||
ccResult2 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_2","content":"world"}]}`
|
||||
ccNotice = `{"role":"system","content":"Plain output style is active."}`
|
||||
ccNoticeLast = `{"role":"system","content":[{"type":"text","text":"Plain output style is active.","cache_control":{"type":"ephemeral"}}]}`
|
||||
)
|
||||
|
||||
func transformClaudeCodeMessages(t *testing.T, msgs ...string) V1InternalRequest {
|
||||
t.Helper()
|
||||
var messages []ClaudeMessage
|
||||
require.NoError(t, json.Unmarshal([]byte("["+strings.Join(msgs, ",")+"]"), &messages))
|
||||
body, err := TransformClaudeToGeminiWithOptions(&ClaudeRequest{
|
||||
Model: "gemini-4-neon",
|
||||
System: json.RawMessage(`"You are Claude Code."`),
|
||||
Messages: messages,
|
||||
Tools: []ClaudeTool{{Name: "Read", Description: "Read a file", InputSchema: map[string]any{"type": "object"}}},
|
||||
}, "project-1", "gemini-4-neon-high", DefaultTransformOptions())
|
||||
require.NoError(t, err)
|
||||
var req V1InternalRequest
|
||||
require.NoError(t, json.Unmarshal(body, &req))
|
||||
return req
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, v any) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(v)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Gemini's implicit cache matches the prompt from its first byte, and the
|
||||
// systemInstruction comes before the conversation. Each request of a tool loop
|
||||
// must therefore keep the previous request's systemInstruction, tools and
|
||||
// contents byte for byte and only add to the end.
|
||||
func TestClaudeCodeToolLoopKeepsThePromptPrefix(t *testing.T) {
|
||||
requests := []V1InternalRequest{
|
||||
transformClaudeCodeMessages(t, ccAsk, ccEnvLatest),
|
||||
transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNoticeLast),
|
||||
transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast),
|
||||
}
|
||||
for n := 1; n < len(requests); n++ {
|
||||
before, now := requests[n-1].Request, requests[n].Request
|
||||
require.Equal(t, mustJSON(t, before.SystemInstruction), mustJSON(t, now.SystemInstruction), "request %d changed the systemInstruction", n+1)
|
||||
require.Equal(t, mustJSON(t, before.Tools), mustJSON(t, now.Tools), "request %d changed the tools", n+1)
|
||||
require.Greater(t, len(now.Contents), len(before.Contents))
|
||||
for i := range before.Contents {
|
||||
require.Equal(t, mustJSON(t, before.Contents[i]), mustJSON(t, now.Contents[i]), "request %d changed content %d of the request before", n+1, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The same holds for any conversation that grows the way Claude Code grows
|
||||
// it: tool calls, tool results with notices after some of them or between a
|
||||
// call and its result, finished replies and new questions.
|
||||
func TestGrowingConversationOnlyAddsToThePrompt(t *testing.T) {
|
||||
notices := []string{"Plain output style is active.", " The user hasn't heard from you in a while.\n", "Today's date is 2026-12-01."}
|
||||
// system renders a system message; the newest one comes as blocks with
|
||||
// cache_control, older ones as strings.
|
||||
system := func(text string, newest bool) string {
|
||||
if newest {
|
||||
return mustJSON(t, map[string]any{"role": "system", "content": []map[string]any{{"type": "text", "text": text, "cache_control": map[string]string{"type": "ephemeral"}}}})
|
||||
}
|
||||
return mustJSON(t, map[string]any{"role": "system", "content": text})
|
||||
}
|
||||
type message struct {
|
||||
json string
|
||||
notice string // the text of a system message, rendered by position
|
||||
}
|
||||
render := func(msgs []message) []string {
|
||||
out := make([]string, len(msgs))
|
||||
for i, m := range msgs {
|
||||
if m.notice != "" {
|
||||
out[i] = system(m.notice, i == len(msgs)-1)
|
||||
} else {
|
||||
out[i] = m.json
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
property := func(seed int64) bool {
|
||||
rng := rand.New(rand.NewSource(seed))
|
||||
msgs := []message{{json: ccAsk}, {notice: "# Environment\nPrimary working directory: /repo"}}
|
||||
var requests [][]string
|
||||
requests = append(requests, render(msgs))
|
||||
for step := 0; step < 2+rng.Intn(8); step++ {
|
||||
id := fmt.Sprintf("toolu_%d", step)
|
||||
if rng.Intn(4) == 0 {
|
||||
msgs = append(msgs,
|
||||
message{json: mustJSON(t, map[string]any{"role": "assistant", "content": fmt.Sprintf("answer %d", step)})},
|
||||
message{json: mustJSON(t, map[string]any{"role": "user", "content": fmt.Sprintf("question %d", step)})})
|
||||
} else {
|
||||
msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "assistant", "content": []map[string]any{
|
||||
{"type": "tool_use", "id": id, "name": "Read", "input": map[string]string{"file_path": id}}}})})
|
||||
if rng.Intn(5) == 0 {
|
||||
msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]})
|
||||
}
|
||||
msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "user", "content": []map[string]any{
|
||||
{"type": "tool_result", "tool_use_id": id, "content": fmt.Sprintf("result %d", step)}}})})
|
||||
}
|
||||
for n := rng.Intn(3); n > 0; n-- {
|
||||
msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]})
|
||||
}
|
||||
requests = append(requests, render(msgs))
|
||||
}
|
||||
var before V1InternalRequest
|
||||
for n, r := range requests {
|
||||
now := transformClaudeCodeMessages(t, r...)
|
||||
for i, c := range now.Request.Contents {
|
||||
if c.Role == "system" || (i > 0 && now.Request.Contents[i-1].Role == c.Role) {
|
||||
t.Logf("seed %d request %d: content %d has role %q after %q", seed, n, i, c.Role, now.Request.Contents[max(i-1, 0)].Role)
|
||||
return false
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
if mustJSON(t, before.Request.SystemInstruction) != mustJSON(t, now.Request.SystemInstruction) {
|
||||
t.Logf("seed %d request %d changed the systemInstruction", seed, n)
|
||||
return false
|
||||
}
|
||||
for i := range before.Request.Contents {
|
||||
if mustJSON(t, before.Request.Contents[i]) != mustJSON(t, now.Request.Contents[i]) {
|
||||
t.Logf("seed %d request %d changed content %d", seed, n, i)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
before = now
|
||||
}
|
||||
return true
|
||||
}
|
||||
require.NoError(t, quick.Check(property, &quick.Config{MaxCount: 300}))
|
||||
}
|
||||
|
||||
func TestSystemMessagesBeforeTheFirstModelTurnStayInSystemInstruction(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnvLatest, ccCall1, ccResult1, ccNoticeLast).Request
|
||||
|
||||
var system []string
|
||||
for _, p := range req.SystemInstruction.Parts {
|
||||
system = append(system, p.Text)
|
||||
}
|
||||
joined := strings.Join(system, "\n")
|
||||
require.Contains(t, joined, "# Environment")
|
||||
require.NotContains(t, joined, "Plain output style is active.")
|
||||
}
|
||||
|
||||
func TestSystemNoticeFollowsTheToolResultsOfItsUserTurn(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast).Request
|
||||
|
||||
require.Len(t, req.Contents, 5)
|
||||
for i, c := range req.Contents {
|
||||
require.NotEqual(t, "system", c.Role)
|
||||
if i > 0 {
|
||||
require.NotEqual(t, req.Contents[i-1].Role, c.Role, "contents %d and %d share a role", i-1, i)
|
||||
}
|
||||
}
|
||||
for _, i := range []int{2, 4} {
|
||||
parts := req.Contents[i].Parts
|
||||
require.Equal(t, "user", req.Contents[i].Role)
|
||||
require.Len(t, parts, 2)
|
||||
require.NotNil(t, parts[0].FunctionResponse, "the tool result must come first")
|
||||
require.Equal(t, "<system-reminder>\nPlain output style is active.\n</system-reminder>", parts[1].Text)
|
||||
}
|
||||
}
|
||||
|
||||
// A notice between a model turn and the user turn holding its tool results
|
||||
// joins that user turn after the results: a functionCall must be followed
|
||||
// directly by its functionResponse.
|
||||
func TestSystemNoticeAfterAModelTurnWaitsForTheNextUserTurn(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccNotice, ccResult1).Request
|
||||
|
||||
require.Len(t, req.Contents, 3)
|
||||
require.Equal(t, "model", req.Contents[1].Role)
|
||||
last := req.Contents[2]
|
||||
require.Equal(t, "user", last.Role)
|
||||
require.Len(t, last.Parts, 2)
|
||||
require.NotNil(t, last.Parts[0].FunctionResponse)
|
||||
require.Contains(t, last.Parts[1].Text, "Plain output style is active.")
|
||||
}
|
||||
|
||||
func TestSystemNoticeEndingTheRequestAfterAModelTurnBecomesAUserTurn(t *testing.T) {
|
||||
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, `{"role":"assistant","content":"partial answer"}`, ccNotice).Request
|
||||
|
||||
require.Len(t, req.Contents, 3)
|
||||
require.Equal(t, "model", req.Contents[1].Role)
|
||||
require.Equal(t, "user", req.Contents[2].Role)
|
||||
require.Contains(t, req.Contents[2].Parts[0].Text, "Plain output style is active.")
|
||||
}
|
||||
@@ -147,10 +147,30 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
|
||||
}
|
||||
}
|
||||
}
|
||||
ensureMaxTokensAboveThinkingBudget(out)
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// thinkingBudgetMaxTokensPadding is the room left above budget_tokens when
|
||||
// max_tokens has to be raised; same value as antigravity.MaxTokensBudgetPadding.
|
||||
const thinkingBudgetMaxTokensPadding = 1000
|
||||
|
||||
// ensureMaxTokensAboveThinkingBudget keeps an enabled thinking budget valid.
|
||||
// Anthropic requires max_tokens > thinking.budget_tokens, but the effort-derived
|
||||
// budget (high 10240, max 32768) is larger than the 8192 default used when the
|
||||
// Responses request carries no max_output_tokens, and Codex never sends one,
|
||||
// so every effort above medium was rejected with a 400. Raise max_tokens the
|
||||
// same way the Antigravity transformer does (ensureMaxTokensGreaterThanBudget).
|
||||
func ensureMaxTokensAboveThinkingBudget(out *AnthropicRequest) {
|
||||
if out == nil || out.Thinking == nil || out.Thinking.Type != "enabled" {
|
||||
return
|
||||
}
|
||||
if budget := out.Thinking.BudgetTokens; budget > 0 && out.MaxTokens <= budget {
|
||||
out.MaxTokens = budget + thinkingBudgetMaxTokensPadding
|
||||
}
|
||||
}
|
||||
|
||||
// defaultThinkingBudget returns a sensible thinking budget based on effort level.
|
||||
func defaultThinkingBudget(effort string) int {
|
||||
switch effort {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// #6569: Anthropic rejects thinking.budget_tokens >= max_tokens. The matrix
|
||||
// mirrors the reported probes on claude-opus-4-6, where every effort above
|
||||
// medium returned 400 without max_output_tokens (Codex never sends it).
|
||||
func TestResponsesToAnthropicRequestKeepsMaxTokensAboveThinkingBudget(t *testing.T) {
|
||||
intPtr := func(v int) *int { return &v }
|
||||
tests := []struct {
|
||||
name string
|
||||
effort string
|
||||
maxOutput *int
|
||||
wantBudget int
|
||||
wantMaxTokens int
|
||||
}{
|
||||
{name: "medium default fits", effort: "medium", wantBudget: 4096, wantMaxTokens: 8192},
|
||||
{name: "high default is raised", effort: "high", wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high 8192 is raised", effort: "high", maxOutput: intPtr(8192), wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high 10000 is raised", effort: "high", maxOutput: intPtr(10000), wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high equal to budget is raised", effort: "high", maxOutput: intPtr(10240), wantBudget: 10240, wantMaxTokens: 11240},
|
||||
{name: "high 12000 already fits", effort: "high", maxOutput: intPtr(12000), wantBudget: 10240, wantMaxTokens: 12000},
|
||||
{name: "xhigh default is raised", effort: "xhigh", wantBudget: 32768, wantMaxTokens: 33768},
|
||||
{name: "xhigh 32000 is raised", effort: "xhigh", maxOutput: intPtr(32000), wantBudget: 32768, wantMaxTokens: 33768},
|
||||
{name: "xhigh 64000 already fits", effort: "xhigh", maxOutput: intPtr(64000), wantBudget: 32768, wantMaxTokens: 64000},
|
||||
{name: "max default is raised", effort: "max", wantBudget: 32768, wantMaxTokens: 33768},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
out, err := ResponsesToAnthropicRequest(&ResponsesRequest{
|
||||
Model: "claude-opus-4-6",
|
||||
Input: json.RawMessage(`"hi"`),
|
||||
MaxOutputTokens: tt.maxOutput,
|
||||
Reasoning: &ResponsesReasoning{Effort: tt.effort},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.Thinking)
|
||||
require.Equal(t, "enabled", out.Thinking.Type)
|
||||
require.Equal(t, tt.wantBudget, out.Thinking.BudgetTokens)
|
||||
require.Equal(t, tt.wantMaxTokens, out.MaxTokens)
|
||||
require.Greater(t, out.MaxTokens, out.Thinking.BudgetTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesToAnthropicRequestLeavesMaxTokensWithoutEnabledThinking(t *testing.T) {
|
||||
low, err := ResponsesToAnthropicRequest(&ResponsesRequest{
|
||||
Model: "claude-opus-4-6", Input: json.RawMessage(`"hi"`), Reasoning: &ResponsesReasoning{Effort: "low"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, low.Thinking)
|
||||
require.Equal(t, 8192, low.MaxTokens)
|
||||
|
||||
noReasoning, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-opus-4-6", Input: json.RawMessage(`"hi"`)})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, noReasoning.Thinking)
|
||||
require.Equal(t, 8192, noReasoning.MaxTokens)
|
||||
}
|
||||
|
||||
func TestEnsureMaxTokensAboveThinkingBudgetIgnoresNonEnabledThinking(t *testing.T) {
|
||||
adaptive := &AnthropicRequest{MaxTokens: 8192, Thinking: &AnthropicThinking{Type: "adaptive", BudgetTokens: 10240}}
|
||||
ensureMaxTokensAboveThinkingBudget(adaptive)
|
||||
require.Equal(t, 8192, adaptive.MaxTokens)
|
||||
|
||||
ensureMaxTokensAboveThinkingBudget(nil)
|
||||
noThinking := &AnthropicRequest{MaxTokens: 100}
|
||||
ensureMaxTokensAboveThinkingBudget(noThinking)
|
||||
require.Equal(t, 100, noThinking.MaxTokens)
|
||||
}
|
||||
@@ -350,21 +350,27 @@ func (m *Manager) rollbackQuota(ctx context.Context, cfg ProviderConfig) {
|
||||
// --- Search execution ---
|
||||
|
||||
// TestSearch executes a search using the first available provider without reserving quota.
|
||||
// Intended for admin test functionality only.
|
||||
// Intended for admin test functionality only, so a failure keeps each provider's error:
|
||||
// the admin needs to see why the test failed (bad key, quota, network), not a generic message.
|
||||
func (m *Manager) TestSearch(ctx context.Context, req SearchRequest) (*SearchResponse, string, error) {
|
||||
if strings.TrimSpace(req.Query) == "" {
|
||||
return nil, "", fmt.Errorf("websearch: empty search query")
|
||||
}
|
||||
var failures []error
|
||||
for _, cfg := range m.configs {
|
||||
if !m.isProviderAvailable(cfg) {
|
||||
continue
|
||||
}
|
||||
resp, err := m.executeSearch(ctx, cfg, req)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
return resp, cfg.Type, nil
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return nil, "", fmt.Errorf("websearch: all providers failed: %w", errors.Join(failures...))
|
||||
}
|
||||
return nil, "", fmt.Errorf("websearch: no available provider")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package websearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// hostStatusClient answers every request with the status and body configured for its host.
|
||||
func hostStatusClient(byHost map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}) *http.Client {
|
||||
return &http.Client{Transport: exaRoundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
reply := byHost[r.URL.Host]
|
||||
return &http.Response{
|
||||
StatusCode: reply.status,
|
||||
Body: io.NopCloser(strings.NewReader(reply.body)),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}
|
||||
}
|
||||
|
||||
func TestManager_TestSearch_ReportsEveryProviderFailure(t *testing.T) {
|
||||
m := NewManager([]ProviderConfig{
|
||||
{Type: ProviderTypeTavily, APIKey: "tvly-bad"},
|
||||
{Type: ProviderTypeExa, APIKey: "exa-bad"},
|
||||
}, nil)
|
||||
m.clientCache[""] = hostStatusClient(map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
"api.tavily.com": {http.StatusUnauthorized, `{"detail":{"error":"Unauthorized: missing or invalid API key."}}`},
|
||||
"api.exa.ai": {http.StatusPaymentRequired, `{"error":"credits exhausted"}`},
|
||||
})
|
||||
|
||||
_, _, err := m.TestSearch(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.Error(t, err)
|
||||
msg := err.Error()
|
||||
require.Contains(t, msg, "all providers failed")
|
||||
require.Contains(t, msg, "tavily: status 401")
|
||||
require.Contains(t, msg, "invalid API key")
|
||||
require.Contains(t, msg, "exa: status 402")
|
||||
require.Contains(t, msg, "credits exhausted")
|
||||
}
|
||||
|
||||
func TestManager_TestSearch_FallsThroughToWorkingProvider(t *testing.T) {
|
||||
m := NewManager([]ProviderConfig{
|
||||
{Type: ProviderTypeTavily, APIKey: "tvly-bad"},
|
||||
{Type: ProviderTypeExa, APIKey: "exa-good"},
|
||||
}, nil)
|
||||
m.clientCache[""] = hostStatusClient(map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
"api.tavily.com": {http.StatusUnauthorized, `{"detail":{"error":"Unauthorized"}}`},
|
||||
"api.exa.ai": {http.StatusOK, `{"results":[{"url":"https://go.dev","title":"Go","highlights":["Go"]}]}`},
|
||||
})
|
||||
|
||||
resp, provider, err := m.TestSearch(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ProviderTypeExa, provider)
|
||||
require.Len(t, resp.Results, 1)
|
||||
}
|
||||
|
||||
func TestManager_TestSearch_NoUsableProviderKeepsMessage(t *testing.T) {
|
||||
m := NewManager([]ProviderConfig{{Type: ProviderTypeTavily, APIKey: ""}}, nil)
|
||||
|
||||
_, _, err := m.TestSearch(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.EqualError(t, err, "websearch: no available provider")
|
||||
}
|
||||
@@ -39,7 +39,6 @@ func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*Search
|
||||
}
|
||||
|
||||
payload := tavilyRequest{
|
||||
APIKey: t.apiKey,
|
||||
Query: req.Query,
|
||||
MaxResults: maxResults,
|
||||
SearchDepth: tavilySearchDepthBasic,
|
||||
@@ -55,6 +54,8 @@ func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*Search
|
||||
return nil, fmt.Errorf("tavily: build request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
// Tavily authenticates with a Bearer token; the documented request body has no api_key field.
|
||||
httpReq.Header.Set("Authorization", "Bearer "+t.apiKey)
|
||||
|
||||
resp, err := t.httpClient.Do(httpReq)
|
||||
if err != nil {
|
||||
@@ -89,7 +90,6 @@ func (t *TavilyProvider) Search(ctx context.Context, req SearchRequest) (*Search
|
||||
}
|
||||
|
||||
type tavilyRequest struct {
|
||||
APIKey string `json:"api_key"`
|
||||
Query string `json:"query"`
|
||||
MaxResults int `json:"max_results"`
|
||||
SearchDepth string `json:"search_depth"`
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package websearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -12,23 +14,40 @@ func TestTavilyProvider_Name(t *testing.T) {
|
||||
require.Equal(t, "tavily", p.Name())
|
||||
}
|
||||
|
||||
func TestTavilyProvider_Search_RequestConstruction(t *testing.T) {
|
||||
// Verify tavilyRequest struct fields map correctly
|
||||
req := tavilyRequest{
|
||||
APIKey: "test-key",
|
||||
Query: "golang",
|
||||
MaxResults: 3,
|
||||
SearchDepth: tavilySearchDepthBasic,
|
||||
}
|
||||
data, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
func TestTavilyProvider_Search_SendsBearerAuth(t *testing.T) {
|
||||
var seen http.Request
|
||||
var seenBody []byte
|
||||
resp := `{"results":[{"url":"https://go.dev","title":"Go","content":"Go programming language","score":0.95}]}`
|
||||
p := NewTavilyProvider("tvly-test-key", exaTestClient(http.StatusOK, resp, &seen, &seenBody))
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &parsed))
|
||||
require.Equal(t, "test-key", parsed["api_key"])
|
||||
require.Equal(t, "golang", parsed["query"])
|
||||
require.Equal(t, float64(3), parsed["max_results"])
|
||||
require.Equal(t, "basic", parsed["search_depth"])
|
||||
out, err := p.Search(context.Background(), SearchRequest{Query: "golang", MaxResults: 3})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.MethodPost, seen.Method)
|
||||
require.Equal(t, tavilySearchEndpoint, seen.URL.String())
|
||||
require.Equal(t, "Bearer tvly-test-key", seen.Header.Get("Authorization"))
|
||||
require.Equal(t, "application/json", seen.Header.Get("Content-Type"))
|
||||
var body map[string]any
|
||||
require.NoError(t, json.Unmarshal(seenBody, &body))
|
||||
require.Equal(t, map[string]any{
|
||||
"query": "golang",
|
||||
"max_results": float64(3),
|
||||
"search_depth": "basic",
|
||||
}, body, "the API key must travel in the Authorization header, not the request body")
|
||||
|
||||
require.Equal(t, []SearchResult{
|
||||
{URL: "https://go.dev", Title: "Go", Snippet: "Go programming language"},
|
||||
}, out.Results)
|
||||
}
|
||||
|
||||
func TestTavilyProvider_Search_ReportsUpstreamStatus(t *testing.T) {
|
||||
var seen http.Request
|
||||
var seenBody []byte
|
||||
p := NewTavilyProvider("bad-key", exaTestClient(http.StatusUnauthorized, `{"detail":{"error":"Unauthorized"}}`, &seen, &seenBody))
|
||||
|
||||
_, err := p.Search(context.Background(), SearchRequest{Query: "golang"})
|
||||
|
||||
require.ErrorContains(t, err, "tavily: status 401")
|
||||
}
|
||||
|
||||
func TestTavilyProvider_Search_ResponseParsing(t *testing.T) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -1196,11 +1197,39 @@ func decodeCachedAccountPayload(payload string) (*service.Account, error) {
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
// schedulerAccountCacheWrite 是一个已编码、待写入的账号载荷。
|
||||
type schedulerAccountCacheWrite struct {
|
||||
keyID string
|
||||
platform string
|
||||
fullPayload []byte
|
||||
metaPayload []byte
|
||||
}
|
||||
|
||||
// schedulerCachedAccountPayload 是写前从 Redis 读回的旧载荷;present 为 false 表示键不存在。
|
||||
type schedulerCachedAccountPayload struct {
|
||||
full string
|
||||
fullPresent bool
|
||||
meta string
|
||||
metaPresent bool
|
||||
}
|
||||
|
||||
// schedulerAccountCacheChange 描述一个账号相对 Redis 中旧载荷的变化。
|
||||
// platformChanged 仅在读到旧精简记录且平台不一致时为 true,用于保留旧平台 bucket 的失效语义。
|
||||
type schedulerAccountCacheChange struct {
|
||||
fullChanged bool
|
||||
metaChanged bool
|
||||
platformChanged bool
|
||||
}
|
||||
|
||||
// writeAccountIDs 分块写入整账号与精简记录,返回成功编码并写入的有序账号 ID。
|
||||
// 每块在追加下一个账号前才执行,最后一块总是非空;所涉平台的修订号追加在最后一块末尾,
|
||||
// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。
|
||||
// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,
|
||||
// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
|
||||
// 写入前按块读回旧载荷(完整记录与精简记录同批 MGET),只写入发生变化的账号:
|
||||
// 调度刷新反复写入相同内容时不再产生整键 SET,避免 AOF/复制放大。
|
||||
// 未变化的账号仍返回其 ID,调用方需要的成员列表不因此改变。
|
||||
// 所涉平台的修订号追加在最后一个有写入的块末尾,与最后一批精简记录同一次往返发出,
|
||||
// 且排在全部精简记录写入之后;全部未变化时不写修订号,读侧进程内缓存继续复用。
|
||||
// 读取失败时降级为原全量写(fail-open),此时用 SET ... GET 取回旧值:
|
||||
// 旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号,全部写入完成后另行写入全局修订号。
|
||||
// 该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值),
|
||||
// 漏检由进程内快照缓存的直接复用时长与宽限期兜底。
|
||||
// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。
|
||||
func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) {
|
||||
@@ -1208,46 +1237,13 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type metaWrite struct {
|
||||
platform string
|
||||
previous *redis.StatusCmd
|
||||
}
|
||||
pipe := c.rdb.Pipeline()
|
||||
accountIDs := make([]int64, 0, len(accounts))
|
||||
platforms := make([]string, 0, 1)
|
||||
writes := make([]metaWrite, 0, min(len(accounts), c.writeChunkSize))
|
||||
pending := 0
|
||||
execFailed := false
|
||||
platformChanged := false
|
||||
defer func() {
|
||||
if execFailed {
|
||||
c.scheduleGlobalAccountMetaRevision(ctx)
|
||||
}
|
||||
}()
|
||||
exec := func() error {
|
||||
cmds, err := pipe.Exec(ctx)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
execFailed = true
|
||||
return err
|
||||
}
|
||||
// SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。
|
||||
for _, cmd := range cmds {
|
||||
if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) {
|
||||
execFailed = true
|
||||
return cmdErr
|
||||
}
|
||||
}
|
||||
for _, write := range writes {
|
||||
if schedulerMetaPlatformChanged(write.previous, write.platform) {
|
||||
platformChanged = true
|
||||
}
|
||||
}
|
||||
writes = writes[:0]
|
||||
pipe = c.rdb.Pipeline()
|
||||
pending = 0
|
||||
return nil
|
||||
chunkSize := c.writeChunkSize
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = defaultSchedulerSnapshotWriteChunkSize
|
||||
}
|
||||
|
||||
writes := make([]schedulerAccountCacheWrite, 0, len(accounts))
|
||||
accountIDs := make([]int64, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
fullPayload, metaPayload, err := marshalSchedulerCacheAccount(account)
|
||||
if err != nil {
|
||||
@@ -1257,35 +1253,94 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
)
|
||||
continue
|
||||
}
|
||||
if pending >= c.writeChunkSize {
|
||||
if err := exec(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
id := strconv.FormatInt(account.ID, 10)
|
||||
pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0)
|
||||
writes = append(writes, metaWrite{
|
||||
platform: account.Platform,
|
||||
previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(id), metaPayload, redis.SetArgs{Get: true}),
|
||||
writes = append(writes, schedulerAccountCacheWrite{
|
||||
keyID: strconv.FormatInt(account.ID, 10),
|
||||
platform: account.Platform,
|
||||
fullPayload: fullPayload,
|
||||
metaPayload: metaPayload,
|
||||
})
|
||||
// Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild
|
||||
// must not overwrite a newer scheduler update.
|
||||
accountIDs = append(accountIDs, account.ID)
|
||||
if !slices.Contains(platforms, account.Platform) {
|
||||
platforms = append(platforms, account.Platform)
|
||||
}
|
||||
pending++
|
||||
}
|
||||
|
||||
if pending == 0 {
|
||||
if len(writes) == 0 {
|
||||
return accountIDs, nil
|
||||
}
|
||||
for _, platform := range platforms {
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
|
||||
|
||||
changes, unconditional, lastWriteChunk := c.planSchedulerAccountWrites(ctx, writes, chunkSize)
|
||||
if lastWriteChunk < 0 {
|
||||
return accountIDs, nil
|
||||
}
|
||||
if err := exec(); err != nil {
|
||||
return nil, err
|
||||
|
||||
type metaWrite struct {
|
||||
platform string
|
||||
previous *redis.StatusCmd
|
||||
}
|
||||
execFailed := false
|
||||
platformChanged := false
|
||||
defer func() {
|
||||
if execFailed {
|
||||
c.scheduleGlobalAccountMetaRevision(ctx)
|
||||
}
|
||||
}()
|
||||
platforms := make([]string, 0, 2)
|
||||
for chunkIndex, start := 0, 0; start < len(writes); chunkIndex, start = chunkIndex+1, start+chunkSize {
|
||||
end := min(start+chunkSize, len(writes))
|
||||
chunk := writes[start:end]
|
||||
pipe := c.rdb.Pipeline()
|
||||
metaWrites := make([]metaWrite, 0, len(chunk))
|
||||
queued := 0
|
||||
for offset := range chunk {
|
||||
change := changes[start+offset]
|
||||
if !change.fullChanged && !change.metaChanged {
|
||||
continue
|
||||
}
|
||||
write := chunk[offset]
|
||||
if change.fullChanged {
|
||||
pipe.Set(ctx, schedulerAccountKey(write.keyID), write.fullPayload, 0)
|
||||
queued++
|
||||
}
|
||||
if change.metaChanged {
|
||||
if unconditional {
|
||||
metaWrites = append(metaWrites, metaWrite{
|
||||
platform: write.platform,
|
||||
previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(write.keyID), write.metaPayload, redis.SetArgs{Get: true}),
|
||||
})
|
||||
} else {
|
||||
pipe.Set(ctx, schedulerAccountMetaKey(write.keyID), write.metaPayload, 0)
|
||||
platformChanged = platformChanged || change.platformChanged
|
||||
}
|
||||
queued++
|
||||
}
|
||||
if !slices.Contains(platforms, write.platform) {
|
||||
platforms = append(platforms, write.platform)
|
||||
}
|
||||
}
|
||||
if queued == 0 {
|
||||
continue
|
||||
}
|
||||
if chunkIndex == lastWriteChunk {
|
||||
for _, platform := range platforms {
|
||||
pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0)
|
||||
}
|
||||
}
|
||||
cmds, err := pipe.Exec(ctx)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
execFailed = true
|
||||
return nil, err
|
||||
}
|
||||
// SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。
|
||||
for _, cmd := range cmds {
|
||||
if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) {
|
||||
execFailed = true
|
||||
return nil, cmdErr
|
||||
}
|
||||
}
|
||||
for _, write := range metaWrites {
|
||||
if schedulerMetaPlatformChanged(write.previous, write.platform) {
|
||||
platformChanged = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if platformChanged {
|
||||
c.advanceGlobalAccountMetaRevision(ctx)
|
||||
@@ -1293,6 +1348,84 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service
|
||||
return accountIDs, nil
|
||||
}
|
||||
|
||||
// planSchedulerAccountWrites 按块读回旧载荷并标记需要写入的账号,返回最后一个有写入的块序号。
|
||||
// 读取失败时把剩余块标记为全量写(unconditional),由调用方沿用原写入与平台变化检测路径。
|
||||
func (c *schedulerCache) planSchedulerAccountWrites(ctx context.Context, writes []schedulerAccountCacheWrite, chunkSize int) ([]schedulerAccountCacheChange, bool, int) {
|
||||
changes := make([]schedulerAccountCacheChange, len(writes))
|
||||
unconditional := false
|
||||
lastWriteChunk := -1
|
||||
for chunkIndex, start := 0, 0; start < len(writes); chunkIndex, start = chunkIndex+1, start+chunkSize {
|
||||
end := min(start+chunkSize, len(writes))
|
||||
chunk := writes[start:end]
|
||||
var previous []schedulerCachedAccountPayload
|
||||
if !unconditional {
|
||||
cached, err := c.readSchedulerAccountPayloads(ctx, chunk)
|
||||
if err != nil {
|
||||
// 读失败时不能跳过任何账号,否则缓存可能停留在旧值;降级为原全量写。
|
||||
slog.Warn("scheduler cache falls back to unconditional account writes", "error", err)
|
||||
unconditional = true
|
||||
} else {
|
||||
previous = cached
|
||||
}
|
||||
}
|
||||
chunkChanged := false
|
||||
for offset := range chunk {
|
||||
change := schedulerAccountCacheChange{fullChanged: true, metaChanged: true}
|
||||
if !unconditional {
|
||||
cached := previous[offset]
|
||||
change.fullChanged = !cached.fullPresent || cached.full != string(chunk[offset].fullPayload)
|
||||
change.metaChanged = !cached.metaPresent || cached.meta != string(chunk[offset].metaPayload)
|
||||
if change.metaChanged && cached.metaPresent {
|
||||
change.platformChanged = schedulerMetaPlatformChangedValue(cached.meta, chunk[offset].platform)
|
||||
}
|
||||
}
|
||||
changes[start+offset] = change
|
||||
if change.fullChanged || change.metaChanged {
|
||||
chunkChanged = true
|
||||
}
|
||||
}
|
||||
if chunkChanged {
|
||||
lastWriteChunk = chunkIndex
|
||||
}
|
||||
}
|
||||
return changes, unconditional, lastWriteChunk
|
||||
}
|
||||
|
||||
// readSchedulerAccountPayloads 读回一批账号的完整与精简记录旧值,键顺序与 writes 一致。
|
||||
func (c *schedulerCache) readSchedulerAccountPayloads(ctx context.Context, writes []schedulerAccountCacheWrite) ([]schedulerCachedAccountPayload, error) {
|
||||
keys := make([]string, 0, len(writes)*2)
|
||||
for _, write := range writes {
|
||||
keys = append(keys, schedulerAccountKey(write.keyID), schedulerAccountMetaKey(write.keyID))
|
||||
}
|
||||
values, err := c.mgetChunked(ctx, keys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(values) != len(keys) {
|
||||
return nil, fmt.Errorf("scheduler cache read %d cached payloads for %d keys", len(values), len(keys))
|
||||
}
|
||||
cached := make([]schedulerCachedAccountPayload, len(writes))
|
||||
for index := range writes {
|
||||
if raw := values[index*2]; raw != nil {
|
||||
payload, err := schedulerCachePayload(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cached[index].full = payload
|
||||
cached[index].fullPresent = true
|
||||
}
|
||||
if raw := values[index*2+1]; raw != nil {
|
||||
payload, err := schedulerCachePayload(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cached[index].meta = payload
|
||||
cached[index].metaPresent = true
|
||||
}
|
||||
}
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// schedulerMetaPlatformChanged 判断 SET ... GET 取回的旧精简记录是否属于另一个平台;
|
||||
// 旧值不是合法 JSON 或缺少字符串类型的顶层 Platform 时按已变化处理。
|
||||
func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bool {
|
||||
@@ -1300,6 +1433,11 @@ func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bo
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return schedulerMetaPlatformChangedValue(raw, platform)
|
||||
}
|
||||
|
||||
// schedulerMetaPlatformChangedValue 是 schedulerMetaPlatformChanged 的载荷版本,供写前读取的旧精简记录复用。
|
||||
func schedulerMetaPlatformChangedValue(raw string, platform string) bool {
|
||||
if !gjson.Valid(raw) {
|
||||
return true
|
||||
}
|
||||
@@ -1393,7 +1531,7 @@ func (c *schedulerCache) mgetChunked(ctx context.Context, keys []string) ([]any,
|
||||
}
|
||||
|
||||
func buildSchedulerMetadataAccount(account service.Account) service.Account {
|
||||
return service.Account{
|
||||
metadata := service.Account{
|
||||
ID: account.ID,
|
||||
Name: account.Name,
|
||||
Platform: account.Platform,
|
||||
@@ -1422,6 +1560,21 @@ func buildSchedulerMetadataAccount(account service.Account) service.Account {
|
||||
Credentials: filterSchedulerCredentials(account.Credentials),
|
||||
Extra: filterSchedulerExtra(account.Extra),
|
||||
}
|
||||
// Media admission runs on this projection before full-account hydration.
|
||||
// Preserve the live JWT tier precedence without copying tokens to metadata.
|
||||
if account.IsGrokOAuth() {
|
||||
tier := xai.SubscriptionTierFromJWT(account.GetCredential("access_token"))
|
||||
if tier == "" {
|
||||
tier = account.GetCredential("subscription_tier")
|
||||
}
|
||||
if tier != "" {
|
||||
if metadata.Credentials == nil {
|
||||
metadata.Credentials = make(map[string]any)
|
||||
}
|
||||
metadata.Credentials["subscription_tier"] = tier
|
||||
}
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
func filterSchedulerAccountGroups(accountGroups []service.AccountGroup) []service.AccountGroup {
|
||||
|
||||
@@ -577,9 +577,13 @@ func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T)
|
||||
require.Len(t, first, schedulerAccountMetaRevisionBytes*2)
|
||||
require.Len(t, memoRevision(t, cache, geminiRevisionKey), schedulerAccountMetaRevisionBytes*2)
|
||||
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, accounts[:1])
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, first, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
require.Equal(t, []string{"mget " + schedulerAccountKey("131")}, recorder.recorded(),
|
||||
"an unchanged payload is only read back")
|
||||
require.Equal(t, first, memoRevision(t, cache, memoAnthropicRevisionKey),
|
||||
"an unchanged payload must not rewrite the account or advance its revision")
|
||||
})
|
||||
|
||||
t.Run("account count is a multiple of the chunk size", func(t *testing.T) {
|
||||
@@ -601,7 +605,8 @@ func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T)
|
||||
"set " + schedulerAccountMetaKey("144"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, batches[1])
|
||||
require.Len(t, recorder.recorded(), 9, "every command travels inside the two pipelines")
|
||||
require.Len(t, recorder.recorded(), 11, "one payload read per chunk plus every write inside the two pipelines")
|
||||
require.Equal(t, 2, recorder.countPrefix("mget "), "each chunk reads its old payloads once")
|
||||
})
|
||||
|
||||
t.Run("failure in a later chunk advances the global revision", func(t *testing.T) {
|
||||
@@ -1200,12 +1205,14 @@ func TestSchedulerCacheSnapshotMemoNilBeforeRealPipelineError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
mr.HSet(schedulerAccountMetaKey("262"), "field", "value")
|
||||
// 让写前读取失败,覆盖降级后的 SET ... GET 错误处理路径。
|
||||
cache.rdb.AddHook(&schedulerCacheMGetFailHook{})
|
||||
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{
|
||||
memoTestAccount(261, "fresh"),
|
||||
memoTestAccount(262, "wrong-type"),
|
||||
})
|
||||
require.Error(t, err, "a WRONGTYPE reply after a nil SET ... GET reply must fail the write")
|
||||
require.Error(t, err, "a WRONGTYPE reply on the fallback SET ... GET path must fail the write")
|
||||
require.Eventually(t, func() bool {
|
||||
return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != ""
|
||||
}, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background")
|
||||
|
||||
@@ -4,6 +4,7 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -372,6 +373,59 @@ func TestBuildSchedulerMetadataAccount_KeepsGrokMediaEligibility(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildSchedulerMetadataAccount_ProjectsGrokSubscriptionTier(t *testing.T) {
|
||||
jwt := func(tier int) string {
|
||||
return "e30." + base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf(`{"tier":%d}`, tier))) + ".signature"
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
platform string
|
||||
token string
|
||||
saved string
|
||||
wantTier string
|
||||
wantEligible bool
|
||||
}{
|
||||
{"paid_live_jwt", service.PlatformGrok, jwt(7), "free", "supergrok_plus", true},
|
||||
{"paid_saved_tier", service.PlatformGrok, "", "supergrok_plus", "supergrok_plus", true},
|
||||
{"live_free_downgrade", service.PlatformGrok, jwt(0), "supergrok_plus", "free", false},
|
||||
{"live_basic_downgrade", service.PlatformGrok, jwt(2), "supergrok_plus", "x_basic", false},
|
||||
{"unclassified_billing", service.PlatformGrok, "", "", "", false},
|
||||
{"malformed_token_fallback", service.PlatformGrok, "invalid", "supergrok_plus", "supergrok_plus", true},
|
||||
{"other_platform_unchanged", service.PlatformOpenAI, jwt(7), "supergrok_plus", "", false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
account := service.Account{
|
||||
Platform: tc.platform,
|
||||
Type: service.AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"access_token": tc.token,
|
||||
"refresh_token": "never-copy",
|
||||
"subscription_tier": tc.saved,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"grok_billing_snapshot": map[string]any{
|
||||
"status_code": 200,
|
||||
"monthly_limit_cents": 0,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
meta := buildSchedulerMetadataAccount(account)
|
||||
|
||||
require.Equal(t, tc.wantTier, meta.GetCredential("subscription_tier"))
|
||||
require.NotContains(t, meta.Credentials, "access_token")
|
||||
require.NotContains(t, meta.Credentials, "refresh_token")
|
||||
|
||||
eligible, _ := meta.GrokMediaGenerationEligibility()
|
||||
require.Equal(t, tc.wantEligible, eligible)
|
||||
require.Equal(t, tc.saved, account.GetCredential("subscription_tier"), "projection must not mutate original credentials")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSchedulerMetadataAccount_KeepsSlimGroupMembership(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 42,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var errSchedulerCacheInjectedMGet = errors.New("injected scheduler cache mget failure")
|
||||
|
||||
// schedulerCacheMGetFailHook 让写前读取失败,用于覆盖 MGET 失败后的降级写入路径。
|
||||
type schedulerCacheMGetFailHook struct {
|
||||
mu sync.Mutex
|
||||
failures int
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
if strings.EqualFold(cmd.Name(), "mget") {
|
||||
h.recordFailure()
|
||||
return errSchedulerCacheInjectedMGet
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
for _, cmd := range cmds {
|
||||
if strings.EqualFold(cmd.Name(), "mget") {
|
||||
h.recordFailure()
|
||||
return errSchedulerCacheInjectedMGet
|
||||
}
|
||||
}
|
||||
return next(ctx, cmds)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) recordFailure() {
|
||||
h.mu.Lock()
|
||||
h.failures++
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *schedulerCacheMGetFailHook) failureCount() int {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.failures
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsSkipsUnchangedPayloads(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(901, "steady"),
|
||||
memoTestAccountOn(service.PlatformGemini, 902, "steady-gemini"),
|
||||
}
|
||||
|
||||
ids, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{901, 902}, ids)
|
||||
firstAnthropic := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
firstGemini := memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini))
|
||||
require.NotEmpty(t, firstAnthropic)
|
||||
|
||||
recorder.reset()
|
||||
ids, err = cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{901, 902}, ids, "unchanged accounts are still reported to the caller")
|
||||
// 记录器只保留命令名与首个参数:一次 MGET 覆盖整块旧载荷。
|
||||
require.Equal(t, []string{"mget " + schedulerAccountKey("901")}, recorder.recorded(),
|
||||
"unchanged payloads must not be rewritten")
|
||||
require.Equal(t, firstAnthropic, memoRevision(t, cache, memoAnthropicRevisionKey),
|
||||
"a stable payload must not advance its platform revision")
|
||||
require.Equal(t, firstGemini, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a stable payload must not advance the global revision")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsRewritesChangedPayloads(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(911, "steady"),
|
||||
memoTestAccount(912, "before"),
|
||||
}
|
||||
_, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
before := memoRevision(t, cache, memoAnthropicRevisionKey)
|
||||
|
||||
changed := []service.Account{accounts[0], accounts[1]}
|
||||
changed[1].Name = "after"
|
||||
changed[1].Status = service.StatusDisabled
|
||||
changed[1].GroupIDs = []int64{77}
|
||||
recorder.reset()
|
||||
ids, err := cache.writeAccountIDs(ctx, changed)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []int64{911, 912}, ids)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerAccountKey("911"),
|
||||
"set " + schedulerAccountKey("912"),
|
||||
"set " + schedulerAccountMetaKey("912"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, recorder.recorded(), "only the changed account is rewritten; the revision shares the write batch")
|
||||
require.NotEqual(t, before, memoRevision(t, cache, memoAnthropicRevisionKey))
|
||||
|
||||
cached, err := cache.GetAccount(ctx, 912)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cached)
|
||||
require.Equal(t, "after", cached.Name)
|
||||
require.Equal(t, service.StatusDisabled, cached.Status)
|
||||
require.Equal(t, []int64{77}, cached.GroupIDs)
|
||||
|
||||
unchanged, err := cache.GetAccount(ctx, 911)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, unchanged)
|
||||
require.Equal(t, "steady", unchanged.Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsSkipsUnchangedChunks(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, 1)
|
||||
accounts := []service.Account{
|
||||
memoTestAccount(921, "a"),
|
||||
memoTestAccount(922, "b"),
|
||||
}
|
||||
_, err := cache.writeAccountIDs(ctx, accounts)
|
||||
require.NoError(t, err)
|
||||
|
||||
changed := []service.Account{accounts[0], accounts[1]}
|
||||
changed[1].Name = "b2"
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, changed)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerAccountKey("921"),
|
||||
"mget " + schedulerAccountKey("922"),
|
||||
"set " + schedulerAccountKey("922"),
|
||||
"set " + schedulerAccountMetaKey("922"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, recorder.recorded(), "unchanged chunks are read but not rewritten")
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsPlatformChangeAdvancesGlobalRevision(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
moved := memoTestAccountOn(service.PlatformGemini, 931, "moved")
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{moved})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini)))
|
||||
require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey))
|
||||
|
||||
moved.Platform = service.PlatformAnthropic
|
||||
moved.Name = "moved-again"
|
||||
_, err = cache.writeAccountIDs(ctx, []service.Account{moved})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey),
|
||||
"a platform change must still advance the global revision")
|
||||
|
||||
cached, err := cache.GetAccount(ctx, 931)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cached)
|
||||
require.Equal(t, service.PlatformAnthropic, cached.Platform)
|
||||
require.Equal(t, "moved-again", cached.Name)
|
||||
}
|
||||
|
||||
func TestSchedulerCacheWriteAccountIDsFallsBackWhenPayloadReadFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize)
|
||||
account := memoTestAccount(941, "initial")
|
||||
_, err := cache.writeAccountIDs(ctx, []service.Account{account})
|
||||
require.NoError(t, err)
|
||||
|
||||
hook := &schedulerCacheMGetFailHook{}
|
||||
cache.rdb.AddHook(hook)
|
||||
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, []service.Account{account})
|
||||
require.NoError(t, err, "a payload read failure must not fail the write")
|
||||
require.Positive(t, hook.failureCount())
|
||||
require.Equal(t, []string{
|
||||
"mget " + schedulerAccountKey("941"),
|
||||
"set " + schedulerAccountKey("941"),
|
||||
"set " + schedulerAccountMetaKey("941"),
|
||||
"set " + memoAnthropicRevisionKey,
|
||||
}, recorder.recorded(), "the fallback reads first, then rewrites the account unconditionally")
|
||||
|
||||
account.Platform = service.PlatformGemini
|
||||
account.Name = "moved"
|
||||
recorder.reset()
|
||||
_, err = cache.writeAccountIDs(ctx, []service.Account{account})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey),
|
||||
"the fallback SET ... GET path still detects platform changes")
|
||||
|
||||
cachedPayload, err := cache.rdb.Get(ctx, schedulerAccountKey("941")).Result()
|
||||
require.NoError(t, err)
|
||||
cached, err := decodeCachedAccount(cachedPayload)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, service.PlatformGemini, cached.Platform)
|
||||
}
|
||||
@@ -529,39 +529,35 @@ func (s *BillingService) initFallbackPricing() {
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// Gemini 4 Argon (Google AI pricing: $2 input / $10 output / $0.10 cached
|
||||
// input per MTok, promotional through 2026-11-30; official rates double to
|
||||
// $4/$20/$0.20 from 2026-12-01). One rate covers every prompt length.
|
||||
// Gemini 4 Argon (Google AI pricing: $4 input / $20 output / $0.20 cached
|
||||
// input per MTok; Priority is 1.8x). One rate covers every prompt length.
|
||||
// Antigravity's -high/-low/-medium aliases are matched below so unavailable
|
||||
// remote pricing never records token-bearing requests at $0.
|
||||
s.fallbackPrices["gemini-4-argon"] = &ModelPricing{
|
||||
InputPricePerToken: 2e-6,
|
||||
OutputPricePerToken: 10e-6,
|
||||
CacheReadPricePerToken: 0.1e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// Gemini 4 Carbon: introductory Google AI rates through 2026-11-30.
|
||||
// From 2026-12-01 the published $2/$10/$0.10 per MTok rates double
|
||||
// to $4/$20/$0.20. Only implicit caching is supported (no storage fee).
|
||||
s.fallbackPrices["gemini-4-carbon"] = &ModelPricing{
|
||||
InputPricePerToken: 2e-6,
|
||||
OutputPricePerToken: 10e-6,
|
||||
CacheReadPricePerToken: 0.1e-6,
|
||||
InputPricePerTokenPriority: 3.6e-6,
|
||||
OutputPricePerTokenPriority: 18e-6,
|
||||
CacheReadPricePerTokenPriority: 0.18e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// Gemini 4 Argon Cyber Permissive (Vertex AI pricing: $4 input / $20 output /
|
||||
// $0.20 cached input per MTok). The Gemini 4 Argon promotion does not apply.
|
||||
s.fallbackPrices["gemini-4-argon-cyber-permissive"] = &ModelPricing{
|
||||
s.fallbackPrices["gemini-4-argon"] = pricingWithPriorityMultiplier(&ModelPricing{
|
||||
InputPricePerToken: 4e-6,
|
||||
OutputPricePerToken: 20e-6,
|
||||
CacheReadPricePerToken: 0.2e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
}, 1.8)
|
||||
|
||||
// Gemini 4 Carbon (Google AI pricing: $4 input / $20 output / $0.20 cached
|
||||
// input per MTok; Priority is 1.8x). One rate covers every prompt length.
|
||||
// Only implicit caching is supported (no storage fee).
|
||||
s.fallbackPrices["gemini-4-carbon"] = pricingWithPriorityMultiplier(&ModelPricing{
|
||||
InputPricePerToken: 4e-6,
|
||||
OutputPricePerToken: 20e-6,
|
||||
CacheReadPricePerToken: 0.2e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}, 1.8)
|
||||
|
||||
// Gemini 4 Argon Cyber Permissive (Vertex AI pricing: $4 input / $20 output /
|
||||
// $0.20 cached input per MTok; Priority is 1.8x).
|
||||
s.fallbackPrices["gemini-4-argon-cyber-permissive"] = pricingWithPriorityMultiplier(&ModelPricing{
|
||||
InputPricePerToken: 4e-6,
|
||||
OutputPricePerToken: 20e-6,
|
||||
CacheReadPricePerToken: 0.2e-6,
|
||||
SupportsCacheBreakdown: false,
|
||||
}, 1.8)
|
||||
|
||||
// Gemini 4 Hydrogen (Google AI pricing: $1.50 input / $7.50 output /
|
||||
// $0.075 cached input per MTok; Priority is 1.8x). One rate covers every
|
||||
@@ -1240,7 +1236,7 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
if normalizeGeminiThinkingTierAlias(lastSegment(strings.TrimSpace(modelLower))) == "gemini-4-carbon" {
|
||||
return s.fallbackPrices["gemini-4-carbon"]
|
||||
}
|
||||
// Cyber 变体不享受 Gemini 4 Argon 的优惠价,必须先于 "gemini-4-argon" 判。
|
||||
// Cyber 变体按独立条目匹配,须先于 "gemini-4-argon" 判断。
|
||||
if strings.Contains(modelLower, "gemini-4-argon-cyber") {
|
||||
return s.fallbackPrices["gemini-4-argon-cyber-permissive"]
|
||||
}
|
||||
|
||||
@@ -547,6 +547,11 @@ type ContentModerationService struct {
|
||||
runtimeRefreshRetryAt atomic.Int64
|
||||
keyHealthMu sync.Mutex
|
||||
keyHealth map[string]*contentModerationKeyHealth
|
||||
// stopCh is closed by Stop; workers tracks the goroutines started by
|
||||
// NewContentModerationService so Stop can wait for them to exit.
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
workers sync.WaitGroup
|
||||
}
|
||||
|
||||
type contentModerationRuntimeSnapshot struct {
|
||||
@@ -611,16 +616,68 @@ func NewContentModerationService(
|
||||
asyncQueueLazy: true,
|
||||
asyncWake: make(chan struct{}),
|
||||
keyHealth: make(map[string]*contentModerationKeyHealth),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
if settingRepo != nil && repo != nil {
|
||||
svc.workers.Add(svc.workerCount + 1)
|
||||
for i := 0; i < svc.workerCount; i++ {
|
||||
go svc.worker(i)
|
||||
go func(id int) {
|
||||
defer svc.workers.Done()
|
||||
svc.worker(id)
|
||||
}(i)
|
||||
}
|
||||
go svc.cleanupWorker()
|
||||
go func() {
|
||||
defer svc.workers.Done()
|
||||
svc.cleanupWorker()
|
||||
}()
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// Stop stops the background goroutines started by NewContentModerationService
|
||||
// and waits for them to exit, then waits for an in-flight runtime snapshot
|
||||
// refresh. A worker finishes the task it is processing before it exits.
|
||||
// Refreshes that callers trigger after Stop still run; calling Stop again
|
||||
// waits for them. Stop is safe to call more than once and on a service that
|
||||
// started no goroutines.
|
||||
func (s *ContentModerationService) Stop() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.stopCh != nil {
|
||||
s.stopOnce.Do(func() { close(s.stopCh) })
|
||||
s.workers.Wait()
|
||||
}
|
||||
s.waitRuntimeRefresh()
|
||||
}
|
||||
|
||||
// waitRuntimeRefresh waits for an in-flight runtime snapshot refresh, which
|
||||
// holds runtimeRefreshMu until it finishes.
|
||||
func (s *ContentModerationService) waitRuntimeRefresh() {
|
||||
s.runtimeRefreshMu.Lock()
|
||||
defer s.runtimeRefreshMu.Unlock()
|
||||
}
|
||||
|
||||
// stopped reports whether Stop has been called.
|
||||
func (s *ContentModerationService) stopped() bool {
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// sleepUnlessStopped waits for d, returning early when Stop is called.
|
||||
func (s *ContentModerationService) sleepUnlessStopped(d time.Duration) {
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ContentModerationService) GetConfig(ctx context.Context) (*ContentModerationConfigView, error) {
|
||||
cfg, err := s.loadConfig(ctx)
|
||||
if err != nil {
|
||||
@@ -1361,12 +1418,12 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp
|
||||
}
|
||||
|
||||
func (s *ContentModerationService) worker(id int) {
|
||||
for {
|
||||
for !s.stopped() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), maxContentModerationTimeoutMS*time.Millisecond+10*time.Second)
|
||||
runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx)
|
||||
if err != nil || runtimeSnapshot == nil || runtimeSnapshot.config == nil || id >= runtimeSnapshot.config.WorkerCount {
|
||||
cancel()
|
||||
time.Sleep(time.Second)
|
||||
s.sleepUnlessStopped(time.Second)
|
||||
continue
|
||||
}
|
||||
cfg := runtimeSnapshot.config
|
||||
@@ -1438,6 +1495,9 @@ func (s *ContentModerationService) dequeueAsyncTask(ctx context.Context, idleWai
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return zero, false
|
||||
case <-s.stopCh:
|
||||
timer.Stop()
|
||||
return zero, false
|
||||
case <-timer.C:
|
||||
return zero, false
|
||||
}
|
||||
@@ -1454,6 +1514,9 @@ func (s *ContentModerationService) dequeueAsyncTask(ctx context.Context, idleWai
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return zero, false
|
||||
case <-s.stopCh:
|
||||
timer.Stop()
|
||||
return zero, false
|
||||
case <-timer.C:
|
||||
return zero, false
|
||||
}
|
||||
@@ -1619,7 +1682,11 @@ func (s *ContentModerationService) cleanupWorker() {
|
||||
timer := time.NewTimer(contentModerationCleanupDelay)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
<-timer.C
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
s.runCleanupOnce()
|
||||
timer.Reset(contentModerationCleanupInterval)
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ func TestRecordCyberPolicyEvent_DisabledWhenRiskControlOff(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
UserID: 1,
|
||||
@@ -107,6 +108,7 @@ func TestRecordCyberPolicyEvent_WritesLogWhenEnabled(t *testing.T) {
|
||||
nil,
|
||||
nil, // emailService=nil: email path safely skipped
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
UserID: 1,
|
||||
@@ -211,6 +213,7 @@ func TestRecordCyberPolicyEvent_RespectsContentModerationScope(t *testing.T) {
|
||||
}},
|
||||
repo, nil, nil, userRepo, nil, nil, nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
UserID: 1,
|
||||
@@ -241,6 +244,7 @@ func TestRecordCyberPolicyEvent_InitialRuntimeSnapshotLoadFailureSkipsEvent(t *t
|
||||
SettingKeyContentModerationConfig: `{invalid`,
|
||||
}}
|
||||
svc := NewContentModerationService(settingRepo, repo, nil, nil, nil, nil, nil, nil)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
UserID: 1,
|
||||
@@ -261,6 +265,10 @@ func TestRecordCyberPolicyEvent_RuntimeSnapshotRefreshFailureKeepsStaleScope(t *
|
||||
SettingKeyContentModerationConfig: `{"all_groups":true,"model_filter":{"type":"include","models":["gpt-5"]}}`,
|
||||
}}
|
||||
svc := NewContentModerationService(settingRepo, repo, nil, nil, nil, nil, nil, nil)
|
||||
t.Cleanup(svc.Stop)
|
||||
// This test drives the snapshot itself; stop the workers before changing
|
||||
// the TTL they read.
|
||||
svc.Stop()
|
||||
svc.runtimeCacheTTL = time.Minute
|
||||
|
||||
_, err := svc.loadRuntimeSnapshot(context.Background())
|
||||
@@ -315,6 +323,7 @@ func TestRecordCyberPolicyEvent_CreateLogBeforeEmail(t *testing.T) {
|
||||
nil,
|
||||
nil, // emailService=nil: email path safely skipped; see doc comment above
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
RequestID: "req-1",
|
||||
@@ -369,6 +378,7 @@ func TestApplyFlaggedAccountSideEffects_PassesExcludeCyberFlag(t *testing.T) {
|
||||
&contentModerationTestSettingRepo{values: map[string]string{}},
|
||||
repo, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
userID := int64(42)
|
||||
|
||||
cfgExclude := defaultContentModerationConfig()
|
||||
@@ -391,6 +401,7 @@ func TestRecordCyberPolicyEvent_ExcludeFromBanCount_SkipsBanJudgment(t *testing.
|
||||
}},
|
||||
repo, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
UserID: 1,
|
||||
@@ -418,6 +429,7 @@ func TestRecordCyberPolicyEvent_DefaultCountsTowardBan(t *testing.T) {
|
||||
}},
|
||||
repo, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
UserID: 1,
|
||||
|
||||
@@ -123,6 +123,7 @@ func newImageSafetyTestService(t *testing.T, settings map[string]string) (*Conte
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
return svc, repo
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -211,3 +212,140 @@ func TestContentModerationWorkerConsumesConcurrentQueue(t *testing.T) {
|
||||
seen[log.RequestID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// TestContentModerationStopEndsBackgroundGoroutines:Stop 要等构造函数启动的 worker 与清理协程全部退出才返回——
|
||||
// 正在处理任务的 worker 处理完再退出,正在空等任务的、以及编号超出配置 WorkerCount 正在退避的 worker 都要被唤醒;
|
||||
// 重复调用、没有启动协程的服务与零值服务上调用都安全。没有 Stop 时这些协程永不退出,测试里会一直读 time.Now,
|
||||
// 与改 time.Local 的测试形成数据竞争。
|
||||
func TestContentModerationStopEndsBackgroundGoroutines(t *testing.T) {
|
||||
cfg := defaultContentModerationConfig()
|
||||
cfg.Enabled = true
|
||||
cfg.Mode = ContentModerationModePreBlock
|
||||
cfg.WorkerCount = 2
|
||||
rawCfg, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &contentModerationBlockingLogRepo{
|
||||
contentModerationTestRepo: &contentModerationTestRepo{},
|
||||
entered: make(chan struct{}),
|
||||
release: make(chan struct{}),
|
||||
}
|
||||
releaseTask := sync.OnceFunc(func() { close(repo.release) })
|
||||
t.Cleanup(releaseTask) // 失败提前退出时也放行,不留下卡在 CreateLog 里的 worker
|
||||
// 不经 newContentModerationModelFilterTestService:它注册的 t.Cleanup(svc.Stop) 在协程不退出时会把测试挂到超时,
|
||||
// 这里要在超时内直接报失败。
|
||||
svc := NewContentModerationService(
|
||||
&contentModerationTestSettingRepo{values: map[string]string{
|
||||
SettingKeyRiskControlEnabled: "true",
|
||||
SettingKeyContentModerationConfig: string(rawCfg),
|
||||
}},
|
||||
repo,
|
||||
&contentModerationTestHashCache{},
|
||||
nil, nil, nil, nil, nil,
|
||||
)
|
||||
svc.enqueueRecord(ContentModerationCheckInput{}, cfg, &ContentModerationLog{
|
||||
RequestID: "stop-in-flight",
|
||||
Mode: ContentModerationModePreBlock,
|
||||
Action: ContentModerationActionAllow,
|
||||
}, "", false, false)
|
||||
select {
|
||||
case <-repo.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no worker picked up the queued task")
|
||||
}
|
||||
|
||||
done := stopInBackground(svc, 2)
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("Stop returned while a worker was still processing a task")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
releaseTask()
|
||||
requireStopReturns(t, done, "service with workers")
|
||||
if got := svc.asyncProcessed.Load(); got != 1 {
|
||||
t.Fatalf("asyncProcessed = %d, want the in-flight task finished before Stop returned", got)
|
||||
}
|
||||
if got := len(repo.snapshotLogs()); got != 1 {
|
||||
t.Fatalf("persisted logs = %d, want 1", got)
|
||||
}
|
||||
|
||||
requireStopReturns(t, stopInBackground(NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil), 1), "service without workers")
|
||||
requireStopReturns(t, stopInBackground(&ContentModerationService{}, 1), "zero-value service")
|
||||
}
|
||||
|
||||
// TestContentModerationStopWaitsForRuntimeSnapshotRefresh:快照过期后在后台刷新的协程也要等它结束,Stop 才返回。
|
||||
func TestContentModerationStopWaitsForRuntimeSnapshotRefresh(t *testing.T) {
|
||||
settings := &contentModerationRuntimeSettingRepo{values: map[string]string{
|
||||
SettingKeyRiskControlEnabled: "true",
|
||||
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
|
||||
}}
|
||||
svc := runtimeCacheTestService(settings, time.Nanosecond)
|
||||
input := runtimeCacheTestInput("blocked")
|
||||
if _, err := svc.Check(context.Background(), input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
started := make(chan struct{}, 1)
|
||||
release := make(chan struct{})
|
||||
releaseRefresh := sync.OnceFunc(func() { close(release) })
|
||||
t.Cleanup(releaseRefresh) // 失败提前退出时也放行,不留下卡住的刷新
|
||||
settings.blockNextMultiple(started, release)
|
||||
// Windows 单调时钟步进约 0.5ms,反复调用直到快照过期、触发后台刷新。
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for refreshing := false; !refreshing; {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the snapshot refresh did not start")
|
||||
}
|
||||
_, _ = svc.Check(context.Background(), input)
|
||||
select {
|
||||
case <-started:
|
||||
refreshing = true
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
done := stopInBackground(svc, 1)
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("Stop returned while a runtime snapshot refresh was still running")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
releaseRefresh()
|
||||
requireStopReturns(t, done, "service with an in-flight refresh")
|
||||
}
|
||||
|
||||
// stopInBackground 在后台调用 times 次 Stop,全部返回后关闭返回的通道。
|
||||
func stopInBackground(svc *ContentModerationService, times int) <-chan struct{} {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for range times {
|
||||
svc.Stop()
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
func requireStopReturns(t *testing.T, done <-chan struct{}, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("Stop did not return within 5s on a %s", what)
|
||||
}
|
||||
}
|
||||
|
||||
// contentModerationBlockingLogRepo 让第一次 CreateLog 停住,直到测试放行。
|
||||
type contentModerationBlockingLogRepo struct {
|
||||
*contentModerationTestRepo
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (r *contentModerationBlockingLogRepo) CreateLog(ctx context.Context, log *ContentModerationLog) error {
|
||||
r.once.Do(func() { close(r.entered) })
|
||||
<-r.release
|
||||
return r.contentModerationTestRepo.CreateLog(ctx, log)
|
||||
}
|
||||
@@ -47,8 +47,7 @@ func TestContentModerationQueueStartsSmallAndGrowsToQueueSize(t *testing.T) {
|
||||
// newConcurrentQueueTestService returns a constructor-built service with no
|
||||
// setting repository, so it has the lazy queue but starts no worker goroutines.
|
||||
// The queue tests drive dequeueAsyncTask directly, which is the exact call the
|
||||
// worker loop makes. A real worker() cannot be used inside synctest because it
|
||||
// has no stop handle; TestContentModerationWorkerConsumesConcurrentQueue covers
|
||||
// worker loop makes; TestContentModerationWorkerConsumesConcurrentQueue covers
|
||||
// the real worker loop separately.
|
||||
func newConcurrentQueueTestService() *ContentModerationService {
|
||||
return NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
|
||||
@@ -87,6 +87,7 @@ func TestContentModerationCheck_ReminderKeywordModes(t *testing.T) {
|
||||
cache.hashes = map[string]struct{}{semantic.Hash(): {}}
|
||||
}
|
||||
svc := NewContentModerationService(&contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true", SettingKeyContentModerationConfig: string(raw)}}, repo, cache, nil, nil, nil, nil, nil)
|
||||
t.Cleanup(svc.Stop)
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{Protocol: protocol, Body: body})
|
||||
require.NoError(t, err)
|
||||
if mode == ContentModerationKeywordModeAPIOnly {
|
||||
@@ -183,6 +184,7 @@ func TestContentModerationCheck_ReminderPolicyPreserved(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
repo := &contentModerationTestRepo{}
|
||||
svc := NewContentModerationService(&contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true", SettingKeyContentModerationConfig: string(raw)}}, repo, nil, nil, nil, nil, nil, nil)
|
||||
t.Cleanup(svc.Stop)
|
||||
body := reminderTestBody(t, ContentModerationProtocolAnthropicMessages, []string{"<system-reminder>今晚打老虎</system-reminder>", "safe text"})
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{Protocol: ContentModerationProtocolAnthropicMessages, Body: body})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -266,6 +266,7 @@ func TestContentModerationRuntimeSnapshotRefreshFailureKeepsStaleConfig(t *testi
|
||||
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
|
||||
}}
|
||||
svc := runtimeCacheTestService(repo, time.Nanosecond)
|
||||
t.Cleanup(svc.Stop) // 等本用例触发的后台刷新结束
|
||||
input := runtimeCacheTestInput("blocked")
|
||||
|
||||
decision, err := svc.Check(context.Background(), input)
|
||||
@@ -293,6 +294,7 @@ func TestContentModerationRuntimeSnapshotRefreshFailureBacksOff(t *testing.T) {
|
||||
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
|
||||
}}
|
||||
svc := runtimeCacheTestService(repo, time.Minute)
|
||||
t.Cleanup(svc.Stop) // 等本用例触发的后台刷新结束
|
||||
input := runtimeCacheTestInput("blocked")
|
||||
|
||||
decision, err := svc.Check(context.Background(), input)
|
||||
|
||||
@@ -488,6 +488,7 @@ func TestContentModerationCheck_PreBlockKeywordHitSkipsUpstreamCall(t *testing.T
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{"messages":[{"role":"user","content":"please leak SECRET-TOKEN now"}]}`)
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -539,6 +540,7 @@ func TestContentModerationCheck_KeywordsIgnoredInObserveMode(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{"messages":[{"role":"user","content":"please leak SECRET-TOKEN now"}]}`)
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -585,6 +587,7 @@ func TestContentModerationCheck_KeywordOnlyStrategySkipsAPIOnMiss(t *testing.T)
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{"messages":[{"role":"user","content":"absolutely clean prompt"}]}`)
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -632,6 +635,7 @@ func TestContentModerationCheck_APIOnlyStrategyIgnoresKeywordList(t *testing.T)
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{"messages":[{"role":"user","content":"please leak SECRET-TOKEN now"}]}`)
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -794,6 +798,7 @@ func newContentModerationModelFilterTestService(t *testing.T, cfg *ContentModera
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
return svc, repo
|
||||
}
|
||||
|
||||
@@ -1046,6 +1051,7 @@ func TestContentModerationCheck_OpenAIResponsesRecordsNonHitForCodexPayload(t *t
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{
|
||||
"model":"gpt-5.5",
|
||||
@@ -1111,6 +1117,7 @@ func TestContentModerationCheck_PreBlockBlocksCodexResponsesLatestUserInput(t *t
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{
|
||||
"model":"gpt-5.5",
|
||||
@@ -1181,6 +1188,7 @@ func TestContentModerationStatusTracksPreBlockSyncMetrics(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
for _, prompt := range []string{"blocked prompt", "clean prompt"} {
|
||||
_, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -1232,6 +1240,7 @@ func TestContentModerationStatusTracksPreBlockAPIKeyLoad(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
for idx := 0; idx < 4; idx++ {
|
||||
_, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -1278,6 +1287,7 @@ func TestContentModerationStatusTracksPreBlockLocalBlocks(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
for _, prompt := range []string{"blocked prompt", "clean prompt"} {
|
||||
_, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -1444,6 +1454,7 @@ func TestContentModerationCheck_PreHashUsesRedisHashCache(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
UserID: 1001,
|
||||
@@ -1512,6 +1523,7 @@ func TestContentModerationCheck_HashBlockLogsDoNotIncreaseNextViolationCount(t *
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
UserID: userID,
|
||||
@@ -1653,6 +1665,7 @@ func TestContentModerationCheck_PreBlockFlaggedWritesRedisHashCache(t *testing.T
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
body := []byte(`{"messages":[{"role":"user","content":"repeat blocked prompt"}]}`)
|
||||
decision, err := svc.Check(context.Background(), ContentModerationCheckInput{
|
||||
@@ -1767,6 +1780,7 @@ func TestContentModerationCheck_AsyncFlaggedWritesRedisHashCache(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
|
||||
decision := svc.checkSync(context.Background(), ContentModerationCheckInput{
|
||||
Protocol: ContentModerationProtocolOpenAIChat,
|
||||
|
||||
@@ -44,6 +44,7 @@ func TestRecordCyberPolicyEventLogOnlyPreservesEvidenceWithoutSideEffects(t *tes
|
||||
&contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true"}},
|
||||
repo, nil, nil, nil, nil, nil, &EmailService{},
|
||||
)
|
||||
t.Cleanup(svc.Stop)
|
||||
// An unconfigured email service must never be invoked in log-only mode.
|
||||
svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{
|
||||
LogOnly: true, UserID: 12, UserEmail: "test@example.com", Model: "gpt-5",
|
||||
|
||||
@@ -806,6 +806,12 @@ type UpstreamFailoverError struct {
|
||||
ClientStatusCode int
|
||||
ClientMessage string
|
||||
StreamFailedFrame *OpenAIStreamFailedFrame // 触发本次 failover 的流内 failed/error 帧;耗尽时用于错误透传规则匹配
|
||||
// ConnectionResetBeforeOutput marks a connection reset/EOF observed after the
|
||||
// upstream connection was established and before any byte reached the client.
|
||||
// The request body is replayable, so it may be retried once on the same
|
||||
// account over a fresh connection; the reset is not an account failure and
|
||||
// must not trigger sticky-session escape or a schedule-result failure.
|
||||
ConnectionResetBeforeOutput bool
|
||||
}
|
||||
|
||||
func (e *UpstreamFailoverError) Error() string {
|
||||
|
||||
@@ -7,11 +7,12 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGeminiCarbonPricingAliases(t *testing.T) {
|
||||
base := &LiteLLMModelPricing{InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6, CacheReadInputTokenCost: 0.1e-6}
|
||||
base := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6, CacheReadInputTokenCost: 0.2e-6}
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{"gemini-4-carbon": base}}
|
||||
for _, model := range []string{
|
||||
"gemini-4-carbon", "gemini-4-carbon-high", "gemini-4-carbon-medium", "gemini-4-carbon-low", "gemini-4-carbon-tiered",
|
||||
@@ -35,13 +36,13 @@ func TestGeminiCarbonFallbackBilling(t *testing.T) {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
cost, err := svc.CalculateCost(model, tokens, 1)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 2, cost.InputCost, 1e-12)
|
||||
require.InDelta(t, 10, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, 0.1, cost.CacheReadCost, 1e-12)
|
||||
require.InDelta(t, 12.1, cost.TotalCost, 1e-12)
|
||||
require.InDelta(t, 4, cost.InputCost, 1e-12)
|
||||
require.InDelta(t, 20, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, 0.2, cost.CacheReadCost, 1e-12)
|
||||
require.InDelta(t, 24.2, cost.TotalCost, 1e-12)
|
||||
priority, err := svc.CalculateCostWithServiceTier(model, tokens, 1, "priority")
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 12.1*1.8, priority.TotalCost, 1e-12)
|
||||
require.InDelta(t, 24.2*1.8, priority.TotalCost, 1e-12)
|
||||
require.Zero(t, svc.CacheStoragePricePerTokenHour(model))
|
||||
})
|
||||
}
|
||||
@@ -56,15 +57,15 @@ func TestDefaultPricingIncludesGeminiCarbon(t *testing.T) {
|
||||
pricing := svc.GetIdentifiedModelPricing("gemini-4-carbon")
|
||||
require.NotNil(t, pricing)
|
||||
require.Equal(t, "gemini", pricing.LiteLLMProvider)
|
||||
require.InDelta(t, 2e-6, pricing.InputCostPerToken, 1e-15)
|
||||
require.InDelta(t, 10e-6, pricing.OutputCostPerToken, 1e-15)
|
||||
require.InDelta(t, 0.1e-6, pricing.CacheReadInputTokenCost, 1e-15)
|
||||
require.InDelta(t, 3.6e-6, pricing.InputCostPerTokenPriority, 1e-15)
|
||||
require.InDelta(t, 18e-6, pricing.OutputCostPerTokenPriority, 1e-15)
|
||||
require.InDelta(t, 0.18e-6, pricing.CacheReadInputTokenCostPriority, 1e-15)
|
||||
require.InDelta(t, 4e-6, pricing.InputCostPerToken, 1e-15)
|
||||
require.InDelta(t, 20e-6, pricing.OutputCostPerToken, 1e-15)
|
||||
require.InDelta(t, 0.2e-6, pricing.CacheReadInputTokenCost, 1e-15)
|
||||
require.InDelta(t, 7.2e-6, pricing.InputCostPerTokenPriority, 1e-15)
|
||||
require.InDelta(t, 36e-6, pricing.OutputCostPerTokenPriority, 1e-15)
|
||||
require.InDelta(t, 0.36e-6, pricing.CacheReadInputTokenCostPriority, 1e-15)
|
||||
require.Zero(t, pricing.LongContextInputTokenThreshold)
|
||||
require.Zero(t, pricing.CacheStorageCostPerTokenPerHour)
|
||||
require.Contains(t, svc.ListModelNamesByProvider("gemini"), "gemini-4-carbon")
|
||||
require.Contains(t, svc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "gemini"}), "gemini-4-carbon")
|
||||
|
||||
var catalog map[string]map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &catalog))
|
||||
|
||||
@@ -3909,6 +3909,23 @@ func cleanToolSchema(schema any) any {
|
||||
return cleanToolSchemaNode(schema, true)
|
||||
}
|
||||
|
||||
// vertexSchemaFields 是 Vertex AI v1 Schema 类型的字段,其它关键字会被上游以 400 拒收
|
||||
// (如 Unknown name "propertyNames"),见 https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema
|
||||
var vertexSchemaFields = map[string]bool{
|
||||
"type": true, "format": true, "title": true, "description": true, "nullable": true, "default": true,
|
||||
"items": true, "minItems": true, "maxItems": true, "enum": true, "properties": true, "propertyOrdering": true,
|
||||
"required": true, "minProperties": true, "maxProperties": true, "minimum": true, "maximum": true,
|
||||
"minLength": true, "maxLength": true, "pattern": true, "example": true, "anyOf": true,
|
||||
"additionalProperties": true, "ref": true, "defs": true,
|
||||
}
|
||||
|
||||
// vertexSchemaFormats 是同一参考页按类型列出的 format 取值。
|
||||
var vertexSchemaFormats = map[string]map[string]bool{
|
||||
"STRING": {"email": true, "byte": true, "date": true, "date-time": true, "password": true, "enum": true},
|
||||
"NUMBER": {"float": true, "double": true},
|
||||
"INTEGER": {"int32": true, "int64": true},
|
||||
}
|
||||
|
||||
func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
if schema == nil {
|
||||
return nil
|
||||
@@ -3925,6 +3942,7 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
}
|
||||
|
||||
cleaned := make(map[string]any)
|
||||
dropped := make(map[string]any)
|
||||
for key, value := range v {
|
||||
// 跳过不支持的字段
|
||||
if key == "$schema" || key == "$id" || key == "$ref" ||
|
||||
@@ -3934,9 +3952,22 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
key == "deprecated" || key == "examples" {
|
||||
continue
|
||||
}
|
||||
// const 在下方折算为 enum。
|
||||
if key == "const" {
|
||||
continue
|
||||
}
|
||||
if key == "oneOf" {
|
||||
if _, hasAnyOf := v["anyOf"]; !hasAnyOf {
|
||||
key = "anyOf"
|
||||
}
|
||||
}
|
||||
if !vertexSchemaFields[key] {
|
||||
dropped[key] = value
|
||||
continue
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "properties", "dependentSchemas":
|
||||
case "properties", "defs":
|
||||
if propertySchemas, ok := value.(map[string]any); ok {
|
||||
cleanedProperties := make(map[string]any, len(propertySchemas))
|
||||
for propertyName, propertySchema := range propertySchemas {
|
||||
@@ -3946,24 +3977,9 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
} else {
|
||||
cleaned[key] = cleanToolSchemaNode(value, false)
|
||||
}
|
||||
case "items", "contains", "propertyNames", "if", "then", "else", "not", "contentSchema",
|
||||
"additionalItems", "unevaluatedItems", "unevaluatedProperties":
|
||||
case "items":
|
||||
cleaned[key] = cleanToolSchemaNode(value, true)
|
||||
case "dependencies":
|
||||
if dependencies, ok := value.(map[string]any); ok {
|
||||
cleanedDependencies := make(map[string]any, len(dependencies))
|
||||
for propertyName, dependency := range dependencies {
|
||||
if dependencySchema, ok := dependency.(map[string]any); ok {
|
||||
cleanedDependencies[propertyName] = cleanToolSchemaNode(dependencySchema, true)
|
||||
} else {
|
||||
cleanedDependencies[propertyName] = cleanToolSchemaNode(dependency, false)
|
||||
}
|
||||
}
|
||||
cleaned[key] = cleanedDependencies
|
||||
} else {
|
||||
cleaned[key] = cleanToolSchemaNode(value, false)
|
||||
}
|
||||
case "anyOf", "allOf", "oneOf", "prefixItems":
|
||||
case "anyOf":
|
||||
if schemas, ok := value.([]any); ok {
|
||||
cleanedSchemas := make([]any, len(schemas))
|
||||
for i, childSchema := range schemas {
|
||||
@@ -4028,6 +4044,14 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
}
|
||||
}
|
||||
}
|
||||
if format, ok := cleaned["format"].(string); ok {
|
||||
typeName, _ := cleaned["type"].(string)
|
||||
if !vertexSchemaFormats[typeName][format] {
|
||||
dropped["format"] = format
|
||||
delete(cleaned, "format")
|
||||
}
|
||||
}
|
||||
appendDroppedSchemaConstraints(cleaned, dropped)
|
||||
return cleaned
|
||||
case []any:
|
||||
cleaned := make([]any, len(v))
|
||||
@@ -4040,6 +4064,38 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
}
|
||||
}
|
||||
|
||||
// appendDroppedSchemaConstraints 把删掉的关键字以提示写进 description 末尾,模型仍能读到这些约束。
|
||||
// 按关键字排序,同一份 schema 每次得到相同的请求体。
|
||||
func appendDroppedSchemaConstraints(schema map[string]any, dropped map[string]any) {
|
||||
keys := make([]string, 0, len(dropped))
|
||||
for key := range dropped {
|
||||
if !strings.HasPrefix(key, "$") {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return
|
||||
}
|
||||
sort.Strings(keys)
|
||||
hints := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
value, isString := dropped[key].(string)
|
||||
if !isString {
|
||||
encoded, err := json.Marshal(dropped[key])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
value = string(encoded)
|
||||
}
|
||||
hints = append(hints, key+": "+value)
|
||||
}
|
||||
hint := "[Constraint: " + strings.Join(hints, ", ") + "]"
|
||||
if description, _ := schema["description"].(string); strings.TrimSpace(description) != "" {
|
||||
hint = description + " " + hint
|
||||
}
|
||||
schema["description"] = hint
|
||||
}
|
||||
|
||||
func normalizeGeminiEnum(values []any) ([]any, bool) {
|
||||
normalized := make([]any, len(values))
|
||||
for i, value := range values {
|
||||
|
||||
@@ -589,57 +589,37 @@ func TestCleanToolSchema_NormalizesConstAndExamplesAtNestedSchemaNodes(t *testin
|
||||
require.NotContains(t, secondBranch, "examples")
|
||||
}
|
||||
|
||||
func TestCleanToolSchema_TraversesRetainedSchemaValuedKeywords(t *testing.T) {
|
||||
func TestCleanToolSchema_DropsNonVertexSchemaValuedKeywordsIntoDescription(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"type": "object",
|
||||
"additionalItems": map[string]any{
|
||||
"type": "string",
|
||||
"const": "additional",
|
||||
"examples": []any{"additional example"},
|
||||
"type": "string",
|
||||
"const": "additional",
|
||||
},
|
||||
"unevaluatedItems": map[string]any{
|
||||
"type": "string",
|
||||
"const": "unevaluated item",
|
||||
"examples": []any{"item example"},
|
||||
"type": "string",
|
||||
"const": "unevaluated item",
|
||||
},
|
||||
"unevaluatedProperties": map[string]any{
|
||||
"type": "string",
|
||||
"const": "unevaluated property",
|
||||
"examples": []any{"property example"},
|
||||
"type": "string",
|
||||
"const": "unevaluated property",
|
||||
},
|
||||
"dependencies": map[string]any{
|
||||
"schema dependency": map[string]any{
|
||||
"type": "string",
|
||||
"const": "dependency",
|
||||
"examples": []any{"dependency example"},
|
||||
},
|
||||
"required dependency": []any{"first", "second"},
|
||||
},
|
||||
}
|
||||
|
||||
cleaned, ok := cleanToolSchema(schema).(map[string]any)
|
||||
require.True(t, ok)
|
||||
expectedEnums := map[string][]any{
|
||||
"additionalItems": {"additional"},
|
||||
"unevaluatedItems": {"unevaluated item"},
|
||||
"unevaluatedProperties": {"unevaluated property"},
|
||||
for _, keyword := range []string{"additionalItems", "unevaluatedItems", "unevaluatedProperties", "dependencies"} {
|
||||
require.NotContains(t, cleaned, keyword)
|
||||
}
|
||||
for keyword, expectedEnum := range expectedEnums {
|
||||
child, ok := cleaned[keyword].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, expectedEnum, child["enum"])
|
||||
require.NotContains(t, child, "const")
|
||||
require.NotContains(t, child, "examples")
|
||||
}
|
||||
|
||||
dependencies, ok := cleaned["dependencies"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
dependencySchema, ok := dependencies["schema dependency"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []any{"dependency"}, dependencySchema["enum"])
|
||||
require.NotContains(t, dependencySchema, "const")
|
||||
require.NotContains(t, dependencySchema, "examples")
|
||||
require.Equal(t, []any{"first", "second"}, dependencies["required dependency"])
|
||||
require.Equal(t,
|
||||
`[Constraint: additionalItems: {"const":"additional","type":"string"}, `+
|
||||
`dependencies: {"required dependency":["first","second"]}, `+
|
||||
`unevaluatedItems: {"const":"unevaluated item","type":"string"}, `+
|
||||
`unevaluatedProperties: {"const":"unevaluated property","type":"string"}]`,
|
||||
cleaned["description"])
|
||||
}
|
||||
|
||||
func TestCleanToolSchema_IntersectsStringConstWithEnum(t *testing.T) {
|
||||
@@ -699,7 +679,7 @@ func TestCleanToolSchema_DropsNonStringConstAndRetainsExistingTypeAndEnum(t *tes
|
||||
require.Equal(t, []any{"8"}, cleaned["enum"])
|
||||
}
|
||||
|
||||
func TestCleanToolSchema_PreservesNestedOneOfCombinator(t *testing.T) {
|
||||
func TestCleanToolSchema_MapsNestedOneOfToAnyOf(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
@@ -718,12 +698,13 @@ func TestCleanToolSchema_PreservesNestedOneOfCombinator(t *testing.T) {
|
||||
require.True(t, ok)
|
||||
valueSchema, ok := properties["value"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
oneOf, ok := valueSchema["oneOf"].([]any)
|
||||
require.NotContains(t, valueSchema, "oneOf")
|
||||
anyOf, ok := valueSchema["anyOf"].([]any)
|
||||
require.True(t, ok)
|
||||
require.Len(t, oneOf, 2)
|
||||
firstBranch, ok := oneOf[0].(map[string]any)
|
||||
require.Len(t, anyOf, 2)
|
||||
firstBranch, ok := anyOf[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
secondBranch, ok := oneOf[1].(map[string]any)
|
||||
secondBranch, ok := anyOf[1].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []any{"a"}, firstBranch["enum"])
|
||||
require.Equal(t, []any{"b"}, secondBranch["enum"])
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCleanToolSchema_KeepsOnlyVertexSchemaFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
schema string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "record with propertyNames",
|
||||
schema: `{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"type":"string"}}`,
|
||||
want: `{"type":"OBJECT","description":"[Constraint: propertyNames: {\"type\":\"string\"}]"}`,
|
||||
},
|
||||
{
|
||||
name: "discriminated union oneOf becomes anyOf",
|
||||
schema: `{"oneOf":[{"type":"object","properties":{"action":{"type":"string","const":"click"}}},{"type":"object","properties":{"action":{"type":"string","const":"type"}}}]}`,
|
||||
want: `{"anyOf":[{"type":"OBJECT","properties":{"action":{"type":"STRING","enum":["click"]}}},{"type":"OBJECT","properties":{"action":{"type":"STRING","enum":["type"]}}}]}`,
|
||||
},
|
||||
{
|
||||
name: "oneOf next to anyOf is dropped into the description",
|
||||
schema: `{"anyOf":[{"type":"string"}],"oneOf":[{"type":"number"}]}`,
|
||||
want: `{"anyOf":[{"type":"STRING"}],"description":"[Constraint: oneOf: [{\"type\":\"number\"}]]"}`,
|
||||
},
|
||||
{
|
||||
name: "only listed formats survive",
|
||||
schema: `{"type":"object","properties":{"url":{"type":"string","format":"uri"},"id":{"type":"string","format":"uuid","description":"Row id."},"day":{"type":"string","format":"date"},"at":{"type":"string","format":"date-time"},"n":{"type":"integer","format":"int64"},"x":{"type":"number","format":"double"},"wrongType":{"type":"integer","format":"float"},"untyped":{"format":"date"}}}`,
|
||||
want: `{"type":"OBJECT","properties":{` +
|
||||
`"url":{"type":"STRING","description":"[Constraint: format: uri]"},` +
|
||||
`"id":{"type":"STRING","description":"Row id. [Constraint: format: uuid]"},` +
|
||||
`"day":{"type":"STRING","format":"date"},` +
|
||||
`"at":{"type":"STRING","format":"date-time"},` +
|
||||
`"n":{"type":"INTEGER","format":"int64"},` +
|
||||
`"x":{"type":"NUMBER","format":"double"},` +
|
||||
`"wrongType":{"type":"INTEGER","description":"[Constraint: format: float]"},` +
|
||||
`"untyped":{"description":"[Constraint: format: date]"}}}`,
|
||||
},
|
||||
{
|
||||
name: "conditional and composition keywords",
|
||||
schema: `{"type":"object","description":"Pick one.","properties":{"a":{"type":"string"}},"if":{"required":["a"]},"then":{"required":["b"]},"else":{"required":["c"]},"not":{"required":["d"]},"allOf":[{"required":["a"]}],"dependentSchemas":{"a":{"required":["b"]}}}`,
|
||||
want: `{"type":"OBJECT","properties":{"a":{"type":"STRING"}},"description":"Pick one. [Constraint: ` +
|
||||
`allOf: [{\"required\":[\"a\"]}], dependentSchemas: {\"a\":{\"required\":[\"b\"]}}, else: {\"required\":[\"c\"]}, ` +
|
||||
`if: {\"required\":[\"a\"]}, not: {\"required\":[\"d\"]}, then: {\"required\":[\"b\"]}]"}`,
|
||||
},
|
||||
{
|
||||
name: "array and number constraints nested under items",
|
||||
schema: `{"type":"array","items":{"type":"number","minimum":0,"maximum":10,"multipleOf":0.5,"exclusiveMaximum":10},"prefixItems":[{"type":"string"}],"contains":{"type":"number"},"uniqueItems":true}`,
|
||||
want: `{"type":"ARRAY","items":{"type":"NUMBER","minimum":0,"maximum":10,"description":"[Constraint: exclusiveMaximum: 10, multipleOf: 0.5]"},` +
|
||||
`"description":"[Constraint: contains: {\"type\":\"number\"}, prefixItems: [{\"type\":\"string\"}], uniqueItems: true]"}`,
|
||||
},
|
||||
{
|
||||
name: "properties named like keywords stay",
|
||||
schema: `{"type":"object","properties":{"not":{"type":"boolean"},"format":{"type":"string"},"propertyNames":{"type":"array","items":{"type":"string"}}},"required":["not"]}`,
|
||||
want: `{"type":"OBJECT","properties":{"not":{"type":"BOOLEAN"},"format":{"type":"STRING"},"propertyNames":{"type":"ARRAY","items":{"type":"STRING"}}},"required":["not"]}`,
|
||||
},
|
||||
{
|
||||
name: "meta keywords are dropped without a hint",
|
||||
schema: `{"type":"string","$comment":"internal","title":"Name","nullable":true,"default":"x","example":"y","pattern":"^a"}`,
|
||||
want: `{"type":"STRING","title":"Name","nullable":true,"default":"x","example":"y","pattern":"^a"}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var schema any
|
||||
require.NoError(t, json.Unmarshal([]byte(tt.schema), &schema))
|
||||
got, err := json.Marshal(cleanToolSchema(schema))
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, tt.want, string(got))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// requireOnlyVertexSchemaFields 断言 schema 每个节点只剩 Vertex Schema 字段。
|
||||
func requireOnlyVertexSchemaFields(t *testing.T, path string, node any) {
|
||||
t.Helper()
|
||||
schema, ok := node.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if format, ok := schema["format"]; ok {
|
||||
typeName, _ := schema["type"].(string)
|
||||
require.True(t, vertexSchemaFormats[typeName][format.(string)], "%s: format %v not listed for %s", path, format, typeName)
|
||||
}
|
||||
for key, value := range schema {
|
||||
require.True(t, vertexSchemaFields[key], "%s: non-Vertex key %q", path, key)
|
||||
switch key {
|
||||
case "properties", "defs":
|
||||
for name, child := range value.(map[string]any) {
|
||||
requireOnlyVertexSchemaFields(t, path+"."+key+"."+name, child)
|
||||
}
|
||||
case "items":
|
||||
requireOnlyVertexSchemaFields(t, path+".items", value)
|
||||
case "anyOf":
|
||||
for _, child := range value.([]any) {
|
||||
requireOnlyVertexSchemaFields(t, path+".anyOf", child)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertClaudeToolsToGeminiTools_SendsOnlyVertexSchemaFieldsAndKeepsEveryTool(t *testing.T) {
|
||||
// Shapes that zod-generated MCP tool schemas produce, plus a deferred tool.
|
||||
toolsJSON := `[
|
||||
{"name":"render_flow","description":"Render a flow.","input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{
|
||||
"vars":{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"type":"string","minLength":1}},
|
||||
"steps":{"type":"array","minItems":1,"uniqueItems":true,"contains":{"type":"object"},"maxContains":3,"items":{"oneOf":[
|
||||
{"type":"object","properties":{"action":{"type":"string","const":"click"},"target":{"type":"string","format":"uri"}},"required":["action","target"],"additionalProperties":false},
|
||||
{"type":"object","properties":{"action":{"type":"string","const":"wait"},"ms":{"type":"integer","exclusiveMinimum":0,"maximum":60000}},"required":["action","ms"]}
|
||||
]}},
|
||||
"runId":{"type":"string","format":"uuid"}
|
||||
},"required":["steps"],"additionalProperties":false}},
|
||||
{"name":"Read","description":"Read a file.","input_schema":{"type":"object","properties":{"file_path":{"type":"string"},"limit":{"type":"integer","exclusiveMinimum":0}},"required":["file_path"]}},
|
||||
{"name":"DeferredToolPlaceholder","description":"Placeholder.","defer_loading":true,"input_schema":{"type":"object","properties":{}}}
|
||||
]`
|
||||
var tools []any
|
||||
require.NoError(t, json.Unmarshal([]byte(toolsJSON), &tools))
|
||||
|
||||
first := convertClaudeToolsToGeminiTools(tools)
|
||||
firstJSON, err := json.Marshal(first)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(firstJSON), `[Constraint: contains: {\"type\":\"object\"}, maxContains: 3, uniqueItems: true]`)
|
||||
for i := 0; i < 20; i++ {
|
||||
again, err := json.Marshal(convertClaudeToolsToGeminiTools(tools))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(firstJSON), string(again), "the same tools must produce the same request bytes")
|
||||
}
|
||||
|
||||
require.Len(t, first, 1)
|
||||
decls := first[0].(map[string]any)["functionDeclarations"].([]any)
|
||||
require.Len(t, decls, 3)
|
||||
for _, decl := range decls {
|
||||
d := decl.(map[string]any)
|
||||
requireOnlyVertexSchemaFields(t, d["name"].(string), d["parameters"])
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ func normalizeCodexModelsManifestConfig(platform string, cfg GroupCodexModelsMan
|
||||
out := GroupCodexModelsManifestConfig{
|
||||
Enabled: cfg.Enabled,
|
||||
FallbackToScheduler: cfg.FallbackToScheduler,
|
||||
KeepHiddenAutoModes: cfg.KeepHiddenAutoModes,
|
||||
}
|
||||
if len(cfg.AccountIDs) == 0 {
|
||||
return out
|
||||
|
||||
@@ -165,6 +165,30 @@ func TestResponsesInputHasFunctionCallOutputNamed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesInputHasAgentFunctionCallOutput(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
want bool
|
||||
}{
|
||||
{"unknown name", `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","output":"tabs"}]}`, true},
|
||||
{"blank call id", `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":" ","output":"tabs"}]}`, true},
|
||||
{"no namespace", `{"input":[{"type":"function_call_output","name":"read_file","output":"body"}]}`, false},
|
||||
{"other namespace", `{"input":[{"type":"function_call_output","namespace":"codex_app","name":"read_file","output":"body"}]}`, false},
|
||||
{"real call id", `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":"call_real","output":"tabs"}]}`, false},
|
||||
{"escaped type", `{"input":[{"` + jsonUEscape("0074") + `ype":"function_call_output","namespace":"agent","name":"browser_tabs"}]}`, true},
|
||||
{"escaped namespace", `{"input":[{"type":"function_call_output","namespace":"` + jsonUEscape("0061") + `gent","name":"browser_tabs"}]}`, true},
|
||||
{"type not output", `{"input":[{"type":"function_call","namespace":"agent","name":"browser_tabs"}]}`, false},
|
||||
{"non-object item", `{"input":["function_call_output agent browser_tabs"]}`, false},
|
||||
{"input not array", `{"input":{"type":"function_call_output","namespace":"agent","name":"browser_tabs"}}`, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, ResponsesInputHasAgentFunctionCallOutput([]byte(tc.body)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// referenceOpenAIRequestBodyHasTools is the scan without the literal gate.
|
||||
func referenceOpenAIRequestBodyHasTools(body []byte) bool {
|
||||
if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 {
|
||||
|
||||
@@ -6,6 +6,32 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ResponsesInputHasAgentFunctionCallOutput reports whether the top-level input
|
||||
// array holds a function_call_output item in the "agent" namespace without a
|
||||
// call_id. Codex injects external agent context this way, including context
|
||||
// tools this gateway does not know by name. Keys and string values are compared
|
||||
// after JSON unescaping, through a zero-copy view of body. When a member is
|
||||
// duplicated, the first occurrence is read; callers that decode the body treat
|
||||
// duplicate members separately.
|
||||
func ResponsesInputHasAgentFunctionCallOutput(body []byte) bool {
|
||||
input := parseRawJSONView(body).Get("input")
|
||||
if !input.IsArray() {
|
||||
return false
|
||||
}
|
||||
found := false
|
||||
input.ForEach(func(_, item gjson.Result) bool {
|
||||
if !item.IsObject() || item.Get("type").String() != "function_call_output" || item.Get("namespace").String() != "agent" {
|
||||
return true
|
||||
}
|
||||
if strings.TrimSpace(item.Get("call_id").String()) != "" {
|
||||
return true
|
||||
}
|
||||
found = true
|
||||
return false
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
// ResponsesInputHasFunctionCallOutputNamed reports whether the top-level input
|
||||
// array holds an object item whose type is "function_call_output" and whose
|
||||
// name starts with one of namePrefixes. Keys and string values are compared
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func keepHiddenAutoModesGroup(groupID int64, keep bool) *Group {
|
||||
return &Group{
|
||||
ID: groupID,
|
||||
Platform: PlatformOpenAI,
|
||||
CodexModelsManifestConfig: GroupCodexModelsManifestConfig{KeepHiddenAutoModes: keep},
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario: with the group switch on, an upstream manifest whose automatic
|
||||
// mode is hidden by upstream is forwarded byte-for-byte and keeps its ETag.
|
||||
func TestMergeGroupConfiguredCodexModelsKeepsHiddenAutoModesWhenEnabled(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{}}
|
||||
upstreamBody := []byte(`{"models":[{"slug":"gpt-5.6","visibility":"list"},{"slug":"codex-auto-review","visibility":"hide","model_messages":{"auto_review":{"enabled":true}}}]}`)
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: append([]byte(nil), upstreamBody...),
|
||||
ETag: `W/"upstream-catalog"`,
|
||||
}
|
||||
|
||||
require.NoError(t, svc.MergeGroupConfiguredCodexModels(context.Background(), keepHiddenAutoModesGroup(81, true), manifest, ""))
|
||||
require.Equal(t, upstreamBody, manifest.Body)
|
||||
require.Equal(t, `W/"upstream-catalog"`, manifest.ETag)
|
||||
}
|
||||
|
||||
// Scenario: the switch is off by default and hidden automatic modes are still
|
||||
// removed, matching the existing opt-in behavior.
|
||||
func TestMergeGroupConfiguredCodexModelsDropsHiddenAutoModesByDefault(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{}}
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"gpt-5.6","visibility":"list"},{"slug":"codex-auto-review","visibility":"hide"}]}`),
|
||||
ETag: `W/"upstream-catalog"`,
|
||||
}
|
||||
|
||||
require.NoError(t, svc.MergeGroupConfiguredCodexModels(context.Background(), keepHiddenAutoModesGroup(82, false), manifest, ""))
|
||||
require.Equal(t, []string{"gpt-5.6"}, codexManifestModelSlugs(t, manifest.Body))
|
||||
require.Equal(t, codexModelsManifestBodyETag(manifest.Body), manifest.ETag)
|
||||
}
|
||||
|
||||
// Scenario: the switch never exposes automatic modes in the picker; entries
|
||||
// that upstream marks as visible are still removed unless selected.
|
||||
func TestMergeGroupConfiguredCodexModelsKeepHiddenAutoModesStillDropsVisibleOnes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{}}
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"codex-auto-review","visibility":"list"},{"slug":"codex-auto-hidden","visibility":"hide"},{"slug":"gpt-5.6","visibility":"list"}]}`),
|
||||
}
|
||||
|
||||
require.NoError(t, svc.MergeGroupConfiguredCodexModels(context.Background(), keepHiddenAutoModesGroup(83, true), manifest, ""))
|
||||
require.Equal(t, []string{"codex-auto-hidden", "gpt-5.6"}, codexManifestModelSlugs(t, manifest.Body))
|
||||
}
|
||||
|
||||
// Scenario: an explicit model-list selection still lists the automatic mode in
|
||||
// the picker, with or without the switch.
|
||||
func TestMergeGroupConfiguredCodexModelsKeepHiddenAutoModesHonorsExplicitSelection(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{}}
|
||||
group := keepHiddenAutoModesGroup(84, true)
|
||||
group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"codex-auto-review", "gpt-5.6"}}
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"codex-auto-review","visibility":"hide"},{"slug":"gpt-5.6","visibility":"list"}]}`),
|
||||
}
|
||||
|
||||
require.NoError(t, svc.MergeGroupConfiguredCodexModels(context.Background(), group, manifest, ""))
|
||||
models := decodeCodexManifestModels(t, manifest.Body)
|
||||
require.Equal(t, []string{"codex-auto-review", "gpt-5.6"}, codexManifestModelSlugs(t, manifest.Body))
|
||||
require.Equal(t, "list", models[0]["visibility"])
|
||||
}
|
||||
|
||||
func TestNormalizeCodexModelsManifestConfigKeepsHiddenAutoModesSwitch(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got := normalizeCodexModelsManifestConfig(PlatformOpenAI, GroupCodexModelsManifestConfig{KeepHiddenAutoModes: true})
|
||||
require.True(t, got.KeepHiddenAutoModes)
|
||||
|
||||
got = normalizeCodexModelsManifestConfig(PlatformAnthropic, GroupCodexModelsManifestConfig{KeepHiddenAutoModes: true})
|
||||
require.False(t, got.KeepHiddenAutoModes, "non-OpenAI groups persist a zero config")
|
||||
}
|
||||
@@ -156,6 +156,7 @@ func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
|
||||
nil,
|
||||
group.ModelAllowlist.Models,
|
||||
group.ModelAllowlistEnabled(),
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("build group configured Codex models: %w", err)
|
||||
@@ -201,6 +202,7 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
|
||||
configuredModels,
|
||||
group.ModelAllowlist.Models,
|
||||
group.ModelAllowlistEnabled(),
|
||||
group.CodexModelsManifestConfig.KeepHiddenAutoModes,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("merge group configured Codex models: %w", err)
|
||||
@@ -1453,11 +1455,17 @@ func BuildDeepSeekCodexModelsManifest(modelIDs []string) ([]byte, error) {
|
||||
return BuildCodexModelsManifest(modelIDs)
|
||||
}
|
||||
|
||||
// mergeConfiguredCodexModelsManifest applies the group's picker policy to a
|
||||
// Codex manifest. keepHiddenAutoModes keeps automatic modes (codex-auto-*) that
|
||||
// the group did not explicitly select, provided the source already hides them
|
||||
// from the picker, byte-for-byte as they appear in body. Visible automatic
|
||||
// modes are still removed unless selected.
|
||||
func mergeConfiguredCodexModelsManifest(
|
||||
body []byte,
|
||||
configuredModels []string,
|
||||
selectedModels []string,
|
||||
filterBySelection bool,
|
||||
keepHiddenAutoModes bool,
|
||||
) ([]byte, bool, error) {
|
||||
var envelope map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &envelope); err != nil {
|
||||
@@ -1505,7 +1513,15 @@ func mergeConfiguredCodexModelsManifest(
|
||||
_, explicitlyEnabled := selected[descriptor.Slug]
|
||||
explicitlyEnabled = filterBySelection && explicitlyEnabled
|
||||
if !explicitlyEnabled {
|
||||
changed = true
|
||||
if !keepHiddenAutoModes || !codexModelHidden(rawModel) {
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
// Codex resolves its approval reviewer from this catalog, and
|
||||
// upstream already hides the entry from the picker; forward it
|
||||
// untouched so the manifest can keep the upstream ETag.
|
||||
seen[descriptor.Slug] = struct{}{}
|
||||
merged = append(merged, rawModel)
|
||||
continue
|
||||
}
|
||||
visibleModel, visibilityChanged, err := codexModelWithVisibility(rawModel, "list")
|
||||
@@ -1558,6 +1574,17 @@ func mergeConfiguredCodexModelsManifest(
|
||||
return mergedBody, true, nil
|
||||
}
|
||||
|
||||
// codexModelHidden reports whether a manifest entry is hidden from the picker.
|
||||
func codexModelHidden(rawModel json.RawMessage) bool {
|
||||
var descriptor struct {
|
||||
Visibility string `json:"visibility"`
|
||||
}
|
||||
if err := json.Unmarshal(rawModel, &descriptor); err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSpace(descriptor.Visibility), "hide")
|
||||
}
|
||||
|
||||
func codexModelWithVisibility(rawModel json.RawMessage, visibility string) (json.RawMessage, bool, error) {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(rawModel, &fields); err != nil {
|
||||
|
||||
@@ -260,6 +260,7 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest(
|
||||
// 官方 OpenCode / Command Code 上游收敛为规范客户端 UA:客户端透传的编程库
|
||||
// UA 会命中其前置 Cloudflare bot 拦截(CF 1010/403),并被计入账号 403 strike。
|
||||
applyOpenCodeUpstreamUserAgent(account, targetURL, upstreamReq.Header)
|
||||
applyOpenAIChatSessionIDHeader(c, account, upstreamReq.Header, body)
|
||||
|
||||
// 账号级请求头覆写:放在所有内置默认头(含 Grok CLI 身份头)之后应用,
|
||||
// 使配置值获得除共享传输层强制头之外的最高优先级。
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// OpenAIChatSessionIDExtraKey 是账号 extra 中的可选开关,通过 admin 账号更新 API 的 extra
|
||||
// 字段设置。为 true 时,OpenAI API Key 账号的 CC 出站请求携带按 API Key 隔离的会话标识,
|
||||
// 供可信的自托管上游(如 vLLM router)做会话亲和。
|
||||
const OpenAIChatSessionIDExtraKey = "openai_chat_session_id"
|
||||
|
||||
// openAIChatSessionIDHeader 是 vLLM router 读取会话标识的请求头。
|
||||
const openAIChatSessionIDHeader = "X-Session-ID"
|
||||
|
||||
// applyOpenAIChatSessionIDHeader 为开启 OpenAIChatSessionIDExtraKey 的账号写入会话头。
|
||||
// 会话来源与 x-opencode-session 相同:客户端会话头优先,其次是协议转换前记下的
|
||||
// prompt_cache_key / metadata.user_id。出站值经 isolateOpenAIUpstreamSessionID 隔离,
|
||||
// 不同 API Key 的同名会话互不冲突。
|
||||
func applyOpenAIChatSessionIDHeader(c *gin.Context, account *Account, headers http.Header, body []byte) {
|
||||
if account == nil || !account.IsOpenAIApiKey() || !account.getExtraBool(OpenAIChatSessionIDExtraKey) {
|
||||
return
|
||||
}
|
||||
clientSessionID := resolveOpenCodeSessionID(c, nil, false, append(openCodeInboundBodies(c), body)...)
|
||||
sessionID := isolateOpenAIUpstreamSessionID(getAPIKeyIDFromContext(c), codexAccountIdentitySource(c, account), clientSessionID)
|
||||
if sessionID != "" {
|
||||
headers.Set(openAIChatSessionIDHeader, sessionID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func openAIChatSessionTestContext(path string, apiKeyID int64, header http.Header, body []byte) *gin.Context {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
|
||||
for key, values := range header {
|
||||
c.Request.Header[key] = values
|
||||
}
|
||||
c.Set("api_key", &APIKey{ID: apiKeyID})
|
||||
return c
|
||||
}
|
||||
|
||||
func openAIChatSessionTestUpstream() *httpUpstreamRecorder {
|
||||
return &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"id":"chatcmpl_session","object":"chat.completion","model":"deepseek-v4.1-flash","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
|
||||
)),
|
||||
}}
|
||||
}
|
||||
|
||||
// sendOpenAIChatSessionTestRequest sends a Chat Completions request through the
|
||||
// shared CC outbound path and returns the headers the upstream received.
|
||||
func sendOpenAIChatSessionTestRequest(t *testing.T, apiKeyID int64, account *Account, header http.Header, body string) http.Header {
|
||||
t.Helper()
|
||||
c := openAIChatSessionTestContext("/v1/chat/completions", apiKeyID, header, []byte(body))
|
||||
upstream := openAIChatSessionTestUpstream()
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
resp, err := svc.sendCCUpstreamRequest(context.Background(), c, account, "http://vllm.internal:8000/v1/chat/completions", []byte(body), false, "sk-test", "", "")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, resp.Body.Close())
|
||||
return upstream.lastReq.Header
|
||||
}
|
||||
|
||||
func openAIChatSessionClientHeader(pairs ...string) http.Header {
|
||||
header := http.Header{}
|
||||
for i := 0; i+1 < len(pairs); i += 2 {
|
||||
header.Set(pairs[i], pairs[i+1])
|
||||
}
|
||||
return header
|
||||
}
|
||||
|
||||
func TestOpenAIChatSessionIDHeaderDisabledKeepsHeaders(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
oauth := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true})
|
||||
oauth.Type = AccountTypeOAuth
|
||||
disabled := map[string]*Account{
|
||||
"not opted in": selfHostedRawChatCompletionsTestAccount(nil),
|
||||
"explicitly false": selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: false}),
|
||||
"string value": selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: "true"}),
|
||||
"OAuth account": oauth,
|
||||
}
|
||||
client := openAIChatSessionClientHeader(
|
||||
"session_id", "conv-1",
|
||||
"X-Session-ID", "client-session",
|
||||
"User-Agent", "opencode/1.19.6",
|
||||
"Accept-Language", "zh-CN",
|
||||
)
|
||||
want := http.Header{
|
||||
"Content-Type": []string{"application/json"},
|
||||
"Authorization": []string{"Bearer sk-test"},
|
||||
"Accept": []string{"application/json"},
|
||||
"User-Agent": []string{"opencode/1.19.6"},
|
||||
"Accept-Language": []string{"zh-CN"},
|
||||
}
|
||||
for name, account := range disabled {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
got := sendOpenAIChatSessionTestRequest(t, 7, account, client, `{"model":"deepseek-v4.1-flash","prompt_cache_key":"pck-1"}`)
|
||||
require.Equal(t, want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIChatSessionIDHeaderStablePerSession(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
account := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true})
|
||||
client := openAIChatSessionClientHeader("session_id", "conv-1", "X-Session-ID", "client-session")
|
||||
body := `{"model":"deepseek-v4.1-flash"}`
|
||||
|
||||
first := sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Values(openAIChatSessionIDHeader)
|
||||
require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, "conv-1")}, first, "the client session header wins and the raw X-Session-ID is never forwarded")
|
||||
require.Regexp(t, `^[0-9a-f]{16}$`, first[0])
|
||||
require.Equal(t, first, sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Values(openAIChatSessionIDHeader))
|
||||
|
||||
fromPromptCacheKey := sendOpenAIChatSessionTestRequest(t, 7, account, nil, `{"model":"deepseek-v4.1-flash","prompt_cache_key":"pck-1"}`)
|
||||
require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, "pck-1")}, fromPromptCacheKey.Values(openAIChatSessionIDHeader))
|
||||
|
||||
require.Empty(t, sendOpenAIChatSessionTestRequest(t, 7, account, nil, body).Values(openAIChatSessionIDHeader))
|
||||
}
|
||||
|
||||
func TestOpenAIChatSessionIDHeaderIsolatesAPIKeys(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
account := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true})
|
||||
client := openAIChatSessionClientHeader("session_id", "conv-1")
|
||||
body := `{"model":"deepseek-v4.1-flash"}`
|
||||
|
||||
first := sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Get(openAIChatSessionIDHeader)
|
||||
second := sendOpenAIChatSessionTestRequest(t, 8, account, client, body).Get(openAIChatSessionIDHeader)
|
||||
require.NotEmpty(t, first)
|
||||
require.NotEmpty(t, second)
|
||||
require.NotEqual(t, first, second)
|
||||
}
|
||||
|
||||
func TestForwardResponses_ChatFallbackSessionIDFromPromptCacheKey(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
account := forceChatResponsesFallbackAccount()
|
||||
account.Extra[OpenAIChatSessionIDExtraKey] = true
|
||||
body := []byte(`{"model":"deepseek-v4.1-flash","input":"hello","prompt_cache_key":"codex-thread-1","stream":false}`)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
header http.Header
|
||||
want string
|
||||
}{
|
||||
{name: "without session header", want: "codex-thread-1"},
|
||||
{name: "session header first", header: openAIChatSessionClientHeader("session_id", "conv-9"), want: "conv-9"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := openAIChatSessionTestContext("/v1/responses", 7, tt.header, body)
|
||||
upstream := openAIChatSessionTestUpstream()
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
|
||||
_, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "http://upstream.example/v1/chat/completions", upstream.lastReq.URL.String())
|
||||
require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, tt.want)}, upstream.lastReq.Header.Values(openAIChatSessionIDHeader))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1058,6 +1058,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
httpInvalidEncryptedContentRetryTried := false
|
||||
compactModelFallbackRetried := false
|
||||
agentTaskRecoveryTried := false
|
||||
// #8933: the whole request gets at most one extra attempt after an upstream
|
||||
// connection reset that happened before any byte reached the client. The
|
||||
// retry stays on the same account and is invisible to failover accounting.
|
||||
connectionResetRetryUsed := false
|
||||
rejectedFieldRetryState := openAIResponsesRejectedFieldRetryStateForRequest(c, body)
|
||||
for {
|
||||
// Build upstream request
|
||||
@@ -1088,6 +1092,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
|
||||
// Send request
|
||||
upstreamStart := time.Now()
|
||||
// Snapshot the client-visible byte count before the attempt so the reset
|
||||
// retry below can prove this attempt wrote nothing (keepalive comments are
|
||||
// excluded, matching the first-output failover accounting).
|
||||
attemptOutputSizeBefore := OpenAICompactKeepaliveAdjustedWrittenSize(c)
|
||||
resp, err := s.doOpenAIUpstream(upstreamReq, proxyURL, account)
|
||||
SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds())
|
||||
if headerGuard != nil && headerGuard.stopHeaderWait() {
|
||||
@@ -1108,6 +1116,17 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
if headerGuard != nil {
|
||||
headerGuard.close()
|
||||
}
|
||||
// #8933: a reset/EOF on the established upstream connection failed this
|
||||
// request before the first client byte. The same account is still healthy
|
||||
// (the shared connection died), so replay once on a fresh connection
|
||||
// instead of turning the incident into an account failure / 502.
|
||||
if !connectionResetRetryUsed && !openAIUpstreamRequestMayHaveReachedUpstreamViaPlugin(err) && openAIUpstreamResetRetryAllowed(
|
||||
c, upstreamReq, ctx, attemptOutputSizeBefore, isOpenAIUpstreamConnectionResetError(err),
|
||||
) {
|
||||
connectionResetRetryUsed = true
|
||||
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Retrying once on the same account after upstream connection reset before any client output (account: %s): %v", account.Name, err)
|
||||
continue
|
||||
}
|
||||
// Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to
|
||||
// a failover so the handler switches to a healthy account, and temporarily
|
||||
// unschedule the account on durable faults (e.g. rejected proxy credentials).
|
||||
@@ -1251,6 +1270,21 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
if reqStream {
|
||||
streamResult, err := s.handleStreamingResponseWithReasoning(ctx, resp, c, account, startTime, originalModel, upstreamModel, reasoningEffortValue)
|
||||
if err != nil {
|
||||
// #8933: the upstream stream was reset after the connection was
|
||||
// established but before any byte reached the client. Replay once on
|
||||
// the same account; the reset is a transport incident, not an account
|
||||
// failure, so no failover/health bookkeeping is involved.
|
||||
var resetFailoverErr *UpstreamFailoverError
|
||||
if !connectionResetRetryUsed && errors.As(err, &resetFailoverErr) && openAIUpstreamResetRetryAllowed(
|
||||
c, upstreamReq, ctx, attemptOutputSizeBefore, resetFailoverErr.ConnectionResetBeforeOutput,
|
||||
) {
|
||||
connectionResetRetryUsed = true
|
||||
if resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Retrying once on the same account after upstream stream connection reset before any client output (account: %s): %v", account.Name, err)
|
||||
continue
|
||||
}
|
||||
if signal, ok := asOpenAICompactFallbackSignal(err); ok {
|
||||
if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry(
|
||||
c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried,
|
||||
|
||||
@@ -474,7 +474,12 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
|
||||
if errText := strings.TrimSpace(scanErr.Error()); errText != "" {
|
||||
msg += ": " + errText
|
||||
}
|
||||
return resultWithUsage(), s.newOpenAIStreamFailoverError(c, account, false, upstreamRequestID, nil, msg), true
|
||||
failoverErr := s.newOpenAIStreamFailoverError(c, account, false, upstreamRequestID, nil, msg)
|
||||
// A reset/EOF before the first client byte is the shared-connection
|
||||
// incident from #8933, not an account failure: Forward replays it once
|
||||
// on the same account instead of switching accounts.
|
||||
failoverErr.ConnectionResetBeforeOutput = isOpenAIUpstreamConnectionResetError(scanErr)
|
||||
return resultWithUsage(), failoverErr, true
|
||||
}
|
||||
// 客户端已断开时,上游出错仅影响体验,不影响计费;返回已收集 usage
|
||||
if clientDisconnected {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// earliestOpenAIResetCreditID picks the credit a manual reset consumes: the
|
||||
// available codex_rate_limits credit that expires first, the same order the
|
||||
// automatic reset follows (selectOpenAIAutoResetCandidate). A consume request
|
||||
// without credit_id lets upstream choose, which can spend a later credit and
|
||||
// leave the one closest to expiry to lapse.
|
||||
//
|
||||
// It returns "" whenever the details cannot name that credit with certainty
|
||||
// (query failed, an available credit has no expiry or id, an expiry does not
|
||||
// parse), and the caller then keeps the untargeted request.
|
||||
func earliestOpenAIResetCreditID(details *openAIRateLimitResetCreditDetails) string {
|
||||
if details == nil || len(details.AutoResetCandidates) == 0 {
|
||||
return ""
|
||||
}
|
||||
candidates := details.AutoResetCandidates
|
||||
if len(candidates) < details.AvailableCreditCount {
|
||||
return ""
|
||||
}
|
||||
if details.AvailableCount != nil && len(candidates) < *details.AvailableCount {
|
||||
return ""
|
||||
}
|
||||
earliest := -1
|
||||
var earliestAt time.Time
|
||||
for i, candidate := range candidates {
|
||||
expiresAt, err := time.Parse(time.RFC3339, candidate.ExpiresAt)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if earliest < 0 || expiresAt.Before(earliestAt) {
|
||||
earliest, earliestAt = i, expiresAt
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(candidates[earliest].ID)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
manualResetCreditsPath = "/backend-api/wham/rate-limit-reset-credits"
|
||||
manualResetConsumePath = "/backend-api/wham/rate-limit-reset-credits/consume"
|
||||
)
|
||||
|
||||
type manualResetUpstream struct {
|
||||
paths []string
|
||||
consumeBody map[string]string
|
||||
}
|
||||
|
||||
// runManualReset serves creditsStatus/creditsBody on the credit list endpoint,
|
||||
// accepts the consume call, and runs the admin (untargeted) ResetCredit.
|
||||
func runManualReset(t *testing.T, accountID int64, creditsStatus int, creditsBody string) *manualResetUpstream {
|
||||
t.Helper()
|
||||
account := &Account{
|
||||
ID: accountID, Platform: PlatformOpenAI, Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{"chatgpt_account_id": "account-manual-reset"},
|
||||
}
|
||||
repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}}
|
||||
tokenCache := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(account): "fake-token"}}
|
||||
upstream := &manualResetUpstream{}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
upstream.paths = append(upstream.paths, r.Method+" "+r.URL.Path)
|
||||
w.Header().Set("content-type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case manualResetCreditsPath:
|
||||
w.WriteHeader(creditsStatus)
|
||||
_, _ = w.Write([]byte(creditsBody))
|
||||
case manualResetConsumePath:
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&upstream.consumeBody))
|
||||
_, _ = w.Write([]byte(`{"code":"ok","windows_reset":1}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
svc := NewOpenAIQuotaService(repo, nil, NewOpenAITokenProvider(repo, tokenCache, nil), newQuotaRedirectingFactory(srv), nil)
|
||||
result, err := svc.ResetCredit(context.Background(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "ok", result.Code)
|
||||
return upstream
|
||||
}
|
||||
|
||||
func TestResetCreditConsumesEarliestExpiringCredit(t *testing.T) {
|
||||
// Listed out of order, with a spent credit that expires even earlier.
|
||||
upstream := runManualReset(t, 230, http.StatusOK, `{"available_count":3,"credits":[
|
||||
{"id":"credit-dec-26","expires_at":"2026-12-26T00:00:00Z","status":"available"},
|
||||
{"id":"credit-spent","expires_at":"2026-12-01T00:00:00Z","status":"used"},
|
||||
{"id":"credit-dec-03","expires_at":"2026-12-03T00:00:00Z","status":"available"},
|
||||
{"id":"credit-dec-13","expires_at":"2026-12-13T00:00:00Z","status":"available"}]}`)
|
||||
|
||||
require.Equal(t, []string{"GET " + manualResetCreditsPath, "POST " + manualResetConsumePath}, upstream.paths)
|
||||
require.Equal(t, "credit-dec-03", upstream.consumeBody["credit_id"])
|
||||
require.NotEmpty(t, upstream.consumeBody["redeem_request_id"])
|
||||
}
|
||||
|
||||
func TestResetCreditLetsUpstreamChooseWhenEarliestCreditIsUnknown(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"credit list unavailable", http.StatusInternalServerError, `{"error":"boom"}`},
|
||||
{"earliest credit has no id", http.StatusOK, `{"credits":[
|
||||
{"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"},
|
||||
{"expires_at":"2026-12-03T00:00:00Z"}]}`},
|
||||
{"an available credit has no expiry", http.StatusOK, `{"credits":[
|
||||
{"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"},
|
||||
{"id":"credit-unknown"}]}`},
|
||||
{"fewer credits listed than available", http.StatusOK, `{"available_count":2,"credits":[
|
||||
{"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"}]}`},
|
||||
{"expiry does not parse", http.StatusOK, `{"credits":[
|
||||
{"id":"credit-late","expires_at":"2026-12-26T00:00:00Z"},
|
||||
{"id":"credit-odd","expires_at":"next week"}]}`},
|
||||
}
|
||||
for i, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
upstream := runManualReset(t, int64(240+i), tc.status, tc.body)
|
||||
|
||||
require.Equal(t, []string{"GET " + manualResetCreditsPath, "POST " + manualResetConsumePath}, upstream.paths)
|
||||
require.NotContains(t, upstream.consumeBody, "credit_id")
|
||||
require.NotEmpty(t, upstream.consumeBody["redeem_request_id"])
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -346,8 +346,10 @@ func (s *OpenAIQuotaService) queryResetCreditDetails(ctx context.Context, client
|
||||
}
|
||||
|
||||
// ResetCredit consumes one rate_limit_reset_credit for the given OpenAI account.
|
||||
// The redeem_request_id is auto-generated (uuid-like) — upstream uses it for
|
||||
// idempotency. Returns the consumed credit metadata so the UI can refresh.
|
||||
// It targets the credit that expires first when the credit details name it,
|
||||
// and otherwise lets upstream choose. The redeem_request_id is auto-generated
|
||||
// (uuid-like) — upstream uses it for idempotency. Returns the consumed credit
|
||||
// metadata so the UI can refresh.
|
||||
func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) (*OpenAIQuotaResetResult, error) {
|
||||
redeemRequestID, err := generateRedeemRequestID()
|
||||
if err != nil {
|
||||
@@ -403,6 +405,10 @@ func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, c
|
||||
callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout)
|
||||
defer cancel()
|
||||
agentIdentity := s.isAgentIdentityAccount(ctx, accountID)
|
||||
if !targeted {
|
||||
// A manual reset spends the credit that expires first, like the automatic reset.
|
||||
creditID = earliestOpenAIResetCreditID(s.queryResetCreditDetails(callCtx, client, accessToken, chatGPTAccountID, fedRAMP, accountID))
|
||||
}
|
||||
|
||||
var payload OpenAIQuotaResetResult
|
||||
for recovered := false; ; {
|
||||
@@ -412,7 +418,7 @@ func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, c
|
||||
}
|
||||
headers["content-type"] = "application/json"
|
||||
body := map[string]string{"redeem_request_id": redeemRequestID}
|
||||
if targeted {
|
||||
if creditID != "" {
|
||||
body["credit_id"] = creditID
|
||||
}
|
||||
resp, err := client.R().
|
||||
|
||||
@@ -245,6 +245,10 @@ func TestResetCreditAgentIdentityUsesAssertionAndRecoversInvalidTaskOnce(t *test
|
||||
_, _ = w.Write([]byte(`{"task_id":"task-reset-new"}`))
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/backend-api/wham/rate-limit-reset-credits" {
|
||||
http.NotFound(w, r) // no credit details: the reset stays untargeted
|
||||
return
|
||||
}
|
||||
resetCalls++
|
||||
assertions = append(assertions, r.Header.Get("authorization"))
|
||||
require.Equal(t, "account-reset-recovery", r.Header.Get("chatgpt-account-id"))
|
||||
@@ -306,6 +310,10 @@ func TestResetCreditAgentIdentityReusesConcurrentlyRecoveredTask(t *testing.T) {
|
||||
_, _ = w.Write([]byte(`{"task_id":"task-reset-unexpected"}`))
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/backend-api/wham/rate-limit-reset-credits" {
|
||||
http.NotFound(w, r) // no credit details: the reset stays untargeted
|
||||
return
|
||||
}
|
||||
resetCalls++
|
||||
assertions = append(assertions, r.Header.Get("authorization"))
|
||||
if resetCalls == 1 {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Issue #8933: a CDN in front of the upstream can reset one HTTP/2 TCP
|
||||
// connection, failing every request multiplexed on it. The upstream keeps
|
||||
// reading the body and bills the request in full, while the gateway never
|
||||
// receives the stream (or its usage). When the connection dies after it was
|
||||
// established but before any byte reached the client, replaying the request
|
||||
// once on the same account recovers the request without blaming the account:
|
||||
// the shared connection failed, not the credential.
|
||||
|
||||
// openAIUpstreamConnectionResetMarkers are transport error texts that mean the
|
||||
// established connection or one of its streams was torn down, as opposed to a
|
||||
// dial/proxy/timeout failure where replaying would only repeat the failure.
|
||||
var openAIUpstreamConnectionResetMarkers = []string{
|
||||
"connection reset by peer",
|
||||
"connection was forcibly closed",
|
||||
"unexpected eof",
|
||||
"broken pipe",
|
||||
"http2: client connection lost",
|
||||
"server sent goaway",
|
||||
"stream error: stream id",
|
||||
}
|
||||
|
||||
// openAIUpstreamNonResetMarkers veto a replay even when the wrapped error text
|
||||
// also carries a reset signature. Dial, DNS and deadline failures need
|
||||
// different handling and must keep their existing classification.
|
||||
var openAIUpstreamNonResetMarkers = []string{
|
||||
"connection refused",
|
||||
"no route to host",
|
||||
"network is unreachable",
|
||||
"no such host",
|
||||
"dial tcp",
|
||||
"proxyconnect",
|
||||
"timeout",
|
||||
"deadline exceeded",
|
||||
"context canceled",
|
||||
}
|
||||
|
||||
// isOpenAIUpstreamConnectionResetError reports whether err is a reset/EOF that
|
||||
// happened on an already-established upstream connection. Timeouts, context
|
||||
// cancellation and dialing failures are explicitly excluded: they are not the
|
||||
// shared-connection incident this retry is meant to absorb.
|
||||
func isOpenAIUpstreamConnectionResetError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return false
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
return false
|
||||
}
|
||||
// A reset during the TCP/TLS handshake belongs to dialing, not to an
|
||||
// established connection: nothing was sent upstream yet, so the normal
|
||||
// reachability handling must own it.
|
||||
var opErr *net.OpError
|
||||
if errors.As(err, &opErr) && opErr.Op == "dial" {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, syscall.ECONNRESET) ||
|
||||
errors.Is(err, syscall.ECONNABORTED) ||
|
||||
errors.Is(err, syscall.EPIPE) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, io.EOF) {
|
||||
return true
|
||||
}
|
||||
lower := strings.ToLower(strings.TrimSpace(err.Error()))
|
||||
for _, marker := range openAIUpstreamNonResetMarkers {
|
||||
if strings.Contains(lower, marker) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, marker := range openAIUpstreamConnectionResetMarkers {
|
||||
if strings.Contains(lower, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// openAIUpstreamRequestMayHaveReachedUpstreamViaPlugin reports a plugin hand-off
|
||||
// that may already have executed upstream. Replaying it could duplicate side
|
||||
// effects (and billing), so the reset retry is skipped — the same guard
|
||||
// handleOpenAIUpstreamTransportError applies before failing over.
|
||||
func openAIUpstreamRequestMayHaveReachedUpstreamViaPlugin(err error) bool {
|
||||
var pluginErr *PluginTransportError
|
||||
return errors.As(err, &pluginErr) && pluginErr != nil && pluginErr.RequestSent
|
||||
}
|
||||
|
||||
// openAIUpstreamResetRetryAllowed reports whether the attempt that just failed
|
||||
// may be replayed once on the same account. The window is deliberately narrow:
|
||||
// - the failure is a connection reset/EOF (see the classifier above);
|
||||
// - the client is still connected, so the replay has a reader;
|
||||
// - the request body can be re-created;
|
||||
// - no byte reached the client for this attempt. Non-semantic keepalive
|
||||
// comments are excluded, matching the existing first-output failover
|
||||
// accounting: they carry no model output, so replaying cannot duplicate
|
||||
// content the client already consumed.
|
||||
func openAIUpstreamResetRetryAllowed(
|
||||
c *gin.Context,
|
||||
req *http.Request,
|
||||
clientCtx context.Context,
|
||||
outputSizeBefore int,
|
||||
connectionReset bool,
|
||||
) bool {
|
||||
if !connectionReset {
|
||||
return false
|
||||
}
|
||||
if c == nil || c.Writer == nil || req == nil || req.GetBody == nil {
|
||||
// Without GetBody the consumed request body cannot be replayed; replaying
|
||||
// would send an empty/partial payload and bill a second broken attempt.
|
||||
return false
|
||||
}
|
||||
if clientCtx != nil && clientCtx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
if IsResponseCommitted(c) {
|
||||
return false
|
||||
}
|
||||
return OpenAICompactKeepaliveAdjustedWrittenSize(c) == outputSizeBefore
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Issue #8933: a CDN reset of one upstream HTTP/2 connection fails every stream
|
||||
// multiplexed on it. When the reset lands after the connection was established
|
||||
// but before any byte reaches the client, Forward must replay the request once on
|
||||
// the same account instead of failing the account over. These tests pin the
|
||||
// retry window: pre-output reset retried once, post-output reset not retried,
|
||||
// timeout/cancel not retried, and a non-replayable body not retried.
|
||||
|
||||
const openAIResetRetryCompletedStream = "event: response.created\n" +
|
||||
`data: {"type":"response.created","response":{"id":"resp_reset_retry","status":"in_progress"}}` + "\n\n" +
|
||||
"event: response.output_text.delta\n" +
|
||||
`data: {"type":"response.output_text.delta","delta":"recovered","output_index":0}` + "\n\n" +
|
||||
"event: response.completed\n" +
|
||||
`data: {"type":"response.completed","response":{"id":"resp_reset_retry","status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"recovered"}]}],"usage":{"input_tokens":5,"output_tokens":2}}}` + "\n\n"
|
||||
|
||||
// openAIResetRetryUpstream scripts one upstream outcome per attempt and records
|
||||
// the request bodies so a replay can be compared with the original attempt.
|
||||
type openAIResetRetryUpstream struct {
|
||||
responses []*http.Response
|
||||
errors []error
|
||||
// clearGetBody simulates a one-shot request body: after the first send the
|
||||
// request can no longer be recreated from GetBody.
|
||||
clearGetBody bool
|
||||
|
||||
requests []*http.Request
|
||||
bodies [][]byte
|
||||
}
|
||||
|
||||
func (u *openAIResetRetryUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
attempt := len(u.requests)
|
||||
u.requests = append(u.requests, req)
|
||||
if req.Body != nil {
|
||||
body, readErr := io.ReadAll(req.Body)
|
||||
if readErr == nil {
|
||||
u.bodies = append(u.bodies, append([]byte(nil), body...))
|
||||
_ = req.Body.Close()
|
||||
req.Body = io.NopCloser(bytes.NewReader(body))
|
||||
}
|
||||
}
|
||||
if u.clearGetBody {
|
||||
req.GetBody = nil
|
||||
}
|
||||
if attempt < len(u.errors) && u.errors[attempt] != nil {
|
||||
return nil, u.errors[attempt]
|
||||
}
|
||||
if attempt < len(u.responses) {
|
||||
return u.responses[attempt], nil
|
||||
}
|
||||
return nil, errors.New("unexpected upstream attempt")
|
||||
}
|
||||
|
||||
func (u *openAIResetRetryUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, accountConcurrency)
|
||||
}
|
||||
|
||||
func newOpenAIResetRetryForward(t *testing.T, upstream HTTPUpstream, ctx context.Context) (*gin.Context, *httptest.ResponseRecorder, []byte, *OpenAIGatewayService) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"model":"gpt-5.5","stream":true,"input":[{"type":"message","role":"user","content":"hi"}]}`)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
return c, rec, body, &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
|
||||
}
|
||||
|
||||
func newOpenAIResetRetryAccount() *Account {
|
||||
return &Account{
|
||||
ID: 8933,
|
||||
Name: "openai-oauth",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
}
|
||||
|
||||
func openAIResetRetryStreamResponse(requestID string, body io.ReadCloser) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{requestID}},
|
||||
Body: body,
|
||||
}
|
||||
}
|
||||
|
||||
// 首字节前连接被重置:同账号重放一次后成功,客户端拿到完整响应。
|
||||
func TestOpenAIForwardRetriesConnectionResetBeforeOutputOnSameAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &openAIResetRetryUpstream{
|
||||
responses: []*http.Response{
|
||||
openAIResetRetryStreamResponse("rid-reset-before-output", &openAIStreamReadThenErrorCloser{
|
||||
reader: strings.NewReader(""),
|
||||
err: syscall.ECONNRESET,
|
||||
}),
|
||||
openAIResetRetryStreamResponse("rid-retry-ok", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))),
|
||||
},
|
||||
}
|
||||
c, rec, body, svc := newOpenAIResetRetryForward(t, upstream, nil)
|
||||
|
||||
result, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Len(t, upstream.requests, 2, "reset before any client byte must be replayed exactly once")
|
||||
require.Equal(t, upstream.requests[0].URL.String(), upstream.requests[1].URL.String(),
|
||||
"the replay must stay on the same upstream endpoint/account")
|
||||
require.Len(t, upstream.bodies, 2)
|
||||
require.Equal(t, upstream.bodies[0], upstream.bodies[1], "the replay must resend the original request body")
|
||||
require.Equal(t, 5, result.Usage.InputTokens)
|
||||
require.Contains(t, rec.Body.String(), "response.completed")
|
||||
require.NotContains(t, rec.Body.String(), "upstream_stream_read_error")
|
||||
}
|
||||
|
||||
// 响应头到达前 TCP 连接被重置(issue 中 146/147 的形态):同账号重放一次后成功。
|
||||
func TestOpenAIForwardRetriesTransportConnectionResetBeforeResponseHeaders(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &openAIResetRetryUpstream{
|
||||
errors: []error{syscall.ECONNRESET, nil},
|
||||
responses: []*http.Response{
|
||||
nil,
|
||||
openAIResetRetryStreamResponse("rid-retry-after-header-reset", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))),
|
||||
},
|
||||
}
|
||||
c, rec, body, svc := newOpenAIResetRetryForward(t, upstream, nil)
|
||||
|
||||
result, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Len(t, upstream.requests, 2, "a reset before response headers must be replayed exactly once")
|
||||
require.Len(t, upstream.bodies, 2)
|
||||
require.Equal(t, upstream.bodies[0], upstream.bodies[1], "the replay must resend the original request body")
|
||||
require.Equal(t, 5, result.Usage.InputTokens)
|
||||
require.Contains(t, rec.Body.String(), "response.completed")
|
||||
}
|
||||
|
||||
// 重放本身再次被重置:整个请求只多试一次,随后按原错误返回 failover。
|
||||
func TestOpenAIForwardRetriesConnectionResetOnlyOnce(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
newResetResponse := func(requestID string) *http.Response {
|
||||
return openAIResetRetryStreamResponse(requestID, &openAIStreamReadThenErrorCloser{
|
||||
reader: strings.NewReader(""),
|
||||
err: syscall.ECONNRESET,
|
||||
})
|
||||
}
|
||||
upstream := &openAIResetRetryUpstream{responses: []*http.Response{
|
||||
newResetResponse("rid-reset-first"),
|
||||
newResetResponse("rid-reset-second"),
|
||||
}}
|
||||
c, _, body, svc := newOpenAIResetRetryForward(t, upstream, nil)
|
||||
|
||||
_, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body)
|
||||
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode)
|
||||
require.Len(t, upstream.requests, 2, "a second reset must not start a third attempt")
|
||||
}
|
||||
|
||||
// 已经向客户端写出字节后再重置:SSE 无法续传,不得重放(回归)。
|
||||
func TestOpenAIForwardDoesNotRetryConnectionResetAfterClientOutput(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &openAIResetRetryUpstream{
|
||||
responses: []*http.Response{
|
||||
openAIResetRetryStreamResponse("rid-reset-after-output", &openAIStreamReadThenErrorCloser{
|
||||
reader: strings.NewReader("event: response.output_text.delta\n" +
|
||||
`data: {"type":"response.output_text.delta","delta":"partial","output_index":0}` + "\n\n"),
|
||||
err: syscall.ECONNRESET,
|
||||
}),
|
||||
},
|
||||
}
|
||||
c, rec, body, svc := newOpenAIResetRetryForward(t, upstream, nil)
|
||||
|
||||
_, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body)
|
||||
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "stream read error")
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.False(t, errors.As(err, &failoverErr), "a post-output reset cannot be replayed")
|
||||
require.Len(t, upstream.requests, 1, "no replay once bytes reached the client")
|
||||
require.Contains(t, rec.Body.String(), "partial")
|
||||
}
|
||||
|
||||
// 超时 / 客户端取消不是共享连接被重置,不得重放。
|
||||
func TestOpenAIForwardDoesNotRetryConnectionResetOnTimeoutOrCancel(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
timeoutErr := &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: &net.OpError{
|
||||
Op: "read", Net: "tcp", Err: openAIResetRetryTimeoutError{},
|
||||
}}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
ctx context.Context
|
||||
}{
|
||||
{name: "deadline_exceeded", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: context.DeadlineExceeded}},
|
||||
{name: "network_timeout", err: timeoutErr},
|
||||
{name: "client_canceled", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: syscall.ECONNRESET}, ctx: canceledOpenAIResetRetryContext()},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
upstream := &openAIResetRetryUpstream{
|
||||
errors: []error{tc.err},
|
||||
responses: []*http.Response{
|
||||
openAIResetRetryStreamResponse("rid-unused", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))),
|
||||
},
|
||||
}
|
||||
c, _, body, svc := newOpenAIResetRetryForward(t, upstream, tc.ctx)
|
||||
|
||||
_, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body)
|
||||
|
||||
require.Error(t, err)
|
||||
require.Len(t, upstream.requests, 1, "timeout/cancel must not be replayed")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// body 不可重放(GetBody 为空)时放弃重放,返回原错误。
|
||||
func TestOpenAIForwardDoesNotRetryConnectionResetWhenBodyIsNotReplayable(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &openAIResetRetryUpstream{
|
||||
clearGetBody: true,
|
||||
errors: []error{syscall.ECONNRESET},
|
||||
responses: []*http.Response{
|
||||
openAIResetRetryStreamResponse("rid-unused", io.NopCloser(strings.NewReader(openAIResetRetryCompletedStream))),
|
||||
},
|
||||
}
|
||||
c, _, body, svc := newOpenAIResetRetryForward(t, upstream, nil)
|
||||
|
||||
_, err := svc.Forward(c.Request.Context(), c, newOpenAIResetRetryAccount(), body)
|
||||
|
||||
require.Error(t, err)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode)
|
||||
require.Len(t, upstream.requests, 1, "a body that cannot be recreated must not be replayed")
|
||||
}
|
||||
|
||||
func TestOpenAIUpstreamConnectionResetClassifier(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{name: "nil", err: nil, want: false},
|
||||
{name: "econnreset", err: syscall.ECONNRESET, want: true},
|
||||
{name: "wrapped_econnreset", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: &net.OpError{
|
||||
Op: "read", Net: "tcp", Err: syscall.ECONNRESET,
|
||||
}}, want: true},
|
||||
{name: "unexpected_eof", err: io.ErrUnexpectedEOF, want: true},
|
||||
{name: "http2_connection_lost", err: errors.New("http2: client connection lost"), want: true},
|
||||
{name: "http2_goaway", err: errors.New("http2: server sent GOAWAY and closed the connection; LastStreamID=3"), want: true},
|
||||
{name: "http2_stream_error", err: errors.New("stream error: stream ID 5; INTERNAL_ERROR"), want: true},
|
||||
{name: "context_canceled", err: context.Canceled, want: false},
|
||||
{name: "deadline_exceeded", err: context.DeadlineExceeded, want: false},
|
||||
{name: "timeout_text", err: errors.New("http2: timeout awaiting response headers"), want: false},
|
||||
{name: "connection_refused", err: errors.New("dial tcp 192.0.2.1:443: connect: connection refused"), want: false},
|
||||
{name: "dial_reset", err: &url.Error{Op: "Post", URL: "https://upstream.example/v1/responses", Err: &net.OpError{
|
||||
Op: "dial", Net: "tcp", Err: syscall.ECONNRESET,
|
||||
}}, want: false},
|
||||
{name: "dns", err: errors.New(`lookup upstream.example: no such host`), want: false},
|
||||
{name: "unrelated", err: errors.New("boom"), want: false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, isOpenAIUpstreamConnectionResetError(tc.err))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type openAIResetRetryTimeoutError struct{}
|
||||
|
||||
func (openAIResetRetryTimeoutError) Error() string { return "i/o timeout" }
|
||||
func (openAIResetRetryTimeoutError) Timeout() bool { return true }
|
||||
func (openAIResetRetryTimeoutError) Temporary() bool { return true }
|
||||
|
||||
func canceledOpenAIResetRetryContext() context.Context {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
return ctx
|
||||
}
|
||||
|
||||
// 流式读错误在首字节前才标记为可由 Forward 重放;其他读错误保持原有 failover 语义。
|
||||
func TestOpenAIStreamReadErrorMarksConnectionResetOnlyBeforeOutput(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
payload string
|
||||
err error
|
||||
wantReset bool
|
||||
}{
|
||||
{name: "reset_before_output", payload: "", err: syscall.ECONNRESET, wantReset: true},
|
||||
{name: "unexpected_eof_before_output", payload: "", err: io.ErrUnexpectedEOF, wantReset: true},
|
||||
{name: "other_read_error", payload: "", err: errors.New("boom"), wantReset: false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}}
|
||||
resp := openAIResetRetryStreamResponse("rid-stream-reset", &openAIStreamReadThenErrorCloser{
|
||||
reader: strings.NewReader(tc.payload),
|
||||
err: tc.err,
|
||||
})
|
||||
|
||||
_, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, newOpenAIResetRetryAccount(), time.Now(), "gpt-5.5", "gpt-5.5")
|
||||
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.Equal(t, tc.wantReset, failoverErr.ConnectionResetBeforeOutput)
|
||||
require.False(t, c.Writer.Written(), "no client-visible byte before the first output")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -975,7 +975,20 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
}
|
||||
turnStart := time.Now()
|
||||
wroteDownstream := false
|
||||
if err := lease.WriteJSONWithContextTimeout(ctx, json.RawMessage(payload), s.openAIWSWriteTimeout()); err != nil {
|
||||
upstreamPayload := payload
|
||||
if account.UsesOpenAICodexProtocol() {
|
||||
// 与 HTTP 路径 applyCodexOAuthTransform 对齐:codex 后端只收列表形式的 input,
|
||||
// 字符串会被以 "Input must be a list" 拒绝。只改发往原生上游 WS 的副本,
|
||||
// 会话内保存的客户端载荷(跨轮前缀比对、http_bridge 路径)保持原样。
|
||||
listPayload, converted, inputErr := normalizeOpenAIWSCodexStringInput(payload)
|
||||
if inputErr != nil {
|
||||
return nil, wrapOpenAIWSIngressTurnError("normalize_input", inputErr, false)
|
||||
}
|
||||
if converted {
|
||||
upstreamPayload = listPayload
|
||||
}
|
||||
}
|
||||
if err := lease.WriteJSONWithContextTimeout(ctx, json.RawMessage(upstreamPayload), s.openAIWSWriteTimeout()); err != nil {
|
||||
return nil, wrapOpenAIWSIngressTurnError(
|
||||
"write_upstream",
|
||||
fmt.Errorf("write upstream websocket request: %w", err),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// normalizeOpenAIWSCodexStringInput 把 WS response.create 里字符串形式的 input
|
||||
// 转成 ChatGPT codex 后端要求的 message 列表。
|
||||
//
|
||||
// 标准 Responses API 允许 input 为字符串,但 chatgpt.com/backend-api/codex 只接受
|
||||
// 列表,字符串会被上游以 "Input must be a list" 拒绝。HTTP 路径已在
|
||||
// applyCodexOAuthTransform 中做同样的转换;WS 入口此前缺这一步,导致同一请求走 HTTP
|
||||
// 成功、走 WS 失败(客户端随之把整个 provider 降级回 HTTP)。转换规则与 HTTP 路径
|
||||
// 保持逐字一致:非空字符串 -> 单条 user message(content 为原字符串),空白 -> []。
|
||||
func normalizeOpenAIWSCodexStringInput(payload []byte) ([]byte, bool, error) {
|
||||
input := gjson.GetBytes(payload, "input")
|
||||
if !input.Exists() || input.Type != gjson.String {
|
||||
return payload, false, nil
|
||||
}
|
||||
text := input.String()
|
||||
var value any = []any{}
|
||||
if strings.TrimSpace(text) != "" {
|
||||
value = []any{map[string]any{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": text,
|
||||
}}
|
||||
}
|
||||
next, err := sjson.SetBytes(payload, "input", value)
|
||||
if err != nil {
|
||||
return payload, false, err
|
||||
}
|
||||
return next, true, nil
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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 TestNormalizeOpenAIWSCodexStringInput(t *testing.T) {
|
||||
t.Run("non-empty string becomes a single user message", func(t *testing.T) {
|
||||
in := []byte(`{"type":"response.create","model":"gpt-5.6-terra","input":"Say OK.","generate":false}`)
|
||||
out, changed, err := normalizeOpenAIWSCodexStringInput(in)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
input := gjson.GetBytes(out, "input")
|
||||
require.True(t, input.IsArray())
|
||||
require.Len(t, input.Array(), 1)
|
||||
require.Equal(t, "message", input.Get("0.type").String())
|
||||
require.Equal(t, "user", input.Get("0.role").String())
|
||||
require.Equal(t, "Say OK.", input.Get("0.content").String())
|
||||
// 其他字段原样保留
|
||||
require.Equal(t, "gpt-5.6-terra", gjson.GetBytes(out, "model").String())
|
||||
require.False(t, gjson.GetBytes(out, "generate").Bool())
|
||||
require.True(t, gjson.GetBytes(out, "generate").Exists())
|
||||
})
|
||||
|
||||
t.Run("blank string becomes empty list", func(t *testing.T) {
|
||||
out, changed, err := normalizeOpenAIWSCodexStringInput([]byte(`{"type":"response.create","input":" "}`))
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "[]", gjson.GetBytes(out, "input").Raw)
|
||||
})
|
||||
|
||||
t.Run("special characters survive", func(t *testing.T) {
|
||||
out, changed, err := normalizeOpenAIWSCodexStringInput([]byte(`{"input":"引号\"与\\反斜杠\n换行"}`))
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "引号\"与\\反斜杠\n换行", gjson.GetBytes(out, "input.0.content").String())
|
||||
})
|
||||
|
||||
t.Run("list input untouched", func(t *testing.T) {
|
||||
in := []byte(`{"input":[{"type":"message","role":"user","content":"hi"}]}`)
|
||||
out, changed, err := normalizeOpenAIWSCodexStringInput(in)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, string(in), string(out))
|
||||
})
|
||||
|
||||
t.Run("missing input untouched", func(t *testing.T) {
|
||||
in := []byte(`{"type":"response.create","previous_response_id":"resp_1"}`)
|
||||
out, changed, err := normalizeOpenAIWSCodexStringInput(in)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, string(in), string(out))
|
||||
})
|
||||
}
|
||||
|
||||
// 与 HTTP 路径 applyCodexOAuthTransform 的转换结果保持一致,避免两条传输的上游请求分叉。
|
||||
func TestNormalizeOpenAIWSCodexStringInputMatchesHTTPTransform(t *testing.T) {
|
||||
for _, text := range []string{"Say OK.", " ", "多行\n输入"} {
|
||||
reqBody := map[string]any{"model": "gpt-5.6-terra", "input": text}
|
||||
applyCodexOAuthTransform(reqBody, false, false)
|
||||
httpInput, ok := reqBody["input"].([]any)
|
||||
require.True(t, ok)
|
||||
|
||||
out, _, err := normalizeOpenAIWSCodexStringInput([]byte(`{"model":"gpt-5.6-terra","input":` + wsTestJSONString(t, text) + `}`))
|
||||
require.NoError(t, err)
|
||||
wsInput := gjson.GetBytes(out, "input").Array()
|
||||
require.Len(t, wsInput, len(httpInput))
|
||||
for i, item := range httpInput {
|
||||
m, ok := item.(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, m["type"], wsInput[i].Get("type").String())
|
||||
require.Equal(t, m["role"], wsInput[i].Get("role").String())
|
||||
require.Equal(t, m["content"], wsInput[i].Get("content").String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func wsTestJSONString(t *testing.T, s string) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(s)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// 生产复现:Magpie 等客户端的首个 WS 预热帧带字符串 input,OAuth 号直连 codex 后端时
|
||||
// 被以 "Input must be a list" 拒绝。这里走真实 ingress 管线,断言上游收到的是列表。
|
||||
func TestWSIngress_OAuthStringInputConvertedBeforeUpstream(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.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1
|
||||
cfg.Gateway.OpenAIWS.MinIdlePerAccount = 0
|
||||
cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 1
|
||||
cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8
|
||||
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
|
||||
captureConn := &openAIWSCaptureConn{
|
||||
events: [][]byte{
|
||||
[]byte(`{"type":"response.completed","response":{"id":"resp_ws_str_1","model":"gpt-5.6-terra","usage":{"input_tokens":1,"output_tokens":1}}}`),
|
||||
},
|
||||
}
|
||||
pool := newOpenAIWSConnPool(cfg)
|
||||
pool.setClientDialerForTest(&openAIWSCaptureDialer{conn: captureConn})
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: cfg,
|
||||
httpUpstream: &httpUpstreamRecorder{},
|
||||
cache: &stubGatewayCache{},
|
||||
openaiWSResolver: NewOpenAIWSProtocolResolver(cfg),
|
||||
toolCorrector: NewCodexToolCorrector(),
|
||||
openaiWSPool: pool,
|
||||
}
|
||||
account := &Account{
|
||||
ID: 902,
|
||||
Name: "openai-ws-oauth-string-input",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"access_token": "oauth-token-1"},
|
||||
Extra: map[string]any{"openai_oauth_responses_websockets_v2_enabled": true},
|
||||
}
|
||||
require.True(t, account.UsesOpenAICodexProtocol())
|
||||
|
||||
serverErrCh := make(chan error, 1)
|
||||
wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
serverErrCh <- err
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
rec := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(rec)
|
||||
req := r.Clone(r.Context())
|
||||
req.Header = req.Header.Clone()
|
||||
req.Header.Set("User-Agent", "unit-test-agent/1.0")
|
||||
ginCtx.Request = req
|
||||
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, "sk-test", firstMessage, nil)
|
||||
}))
|
||||
defer wsServer.Close()
|
||||
|
||||
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil)
|
||||
cancelDial()
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = clientConn.CloseNow() }()
|
||||
|
||||
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
require.NoError(t, clientConn.Write(writeCtx, coderws.MessageText,
|
||||
[]byte(`{"type":"response.create","model":"gpt-5.6-terra","stream":true,"store":false,"generate":false,"input":"warmup"}`)))
|
||||
cancelWrite()
|
||||
|
||||
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_, event, readErr := clientConn.Read(readCtx)
|
||||
cancelRead()
|
||||
require.NoError(t, readErr)
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
|
||||
require.NoError(t, clientConn.Close(coderws.StatusNormalClosure, "done"))
|
||||
|
||||
select {
|
||||
case serverErr := <-serverErrCh:
|
||||
require.NoError(t, serverErr)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("等待 ingress websocket 结束超时")
|
||||
}
|
||||
|
||||
require.Len(t, captureConn.writes, 1)
|
||||
input, ok := captureConn.writes[0]["input"].([]any)
|
||||
require.True(t, ok, "上游收到的 input 必须是列表, got %T", captureConn.writes[0]["input"])
|
||||
require.Len(t, input, 1)
|
||||
msg, ok := input[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "message", msg["type"])
|
||||
require.Equal(t, "user", msg["role"])
|
||||
require.Equal(t, "warmup", msg["content"])
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
|
||||
@@ -1861,18 +1862,24 @@ func (s *PricingService) getHashFilePath() string {
|
||||
return filepath.Join(s.cfg.Pricing.DataDir, "model_pricing.sha256")
|
||||
}
|
||||
|
||||
// ListModelNamesByProvider returns all model names in the catalog whose
|
||||
// LiteLLMProvider matches the given provider string (case-insensitive).
|
||||
// The returned slice is sorted alphabetically.
|
||||
func (s *PricingService) ListModelNamesByProvider(provider string) []string {
|
||||
// ListModelNamesForPlatform returns sorted catalog names for channel pricing sync.
|
||||
func (s *PricingService) ListModelNamesForPlatform(platform domain.PlatformSpec) []string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
provider = strings.ToLower(strings.TrimSpace(provider))
|
||||
provider := strings.TrimSpace(platform.LiteLLMProvider)
|
||||
names := make([]string, 0)
|
||||
for name, p := range s.pricingData {
|
||||
if strings.ToLower(p.LiteLLMProvider) == provider {
|
||||
if strings.EqualFold(p.LiteLLMProvider, provider) {
|
||||
names = append(names, name)
|
||||
continue
|
||||
}
|
||||
// Antigravity also routes Gemini models. Their catalog entries can
|
||||
// carry different provider labels (e.g. Gemini or Vertex AI).
|
||||
if platform.ID == domain.PlatformAntigravity && strings.HasPrefix(name, "gemini-") {
|
||||
if _, supported := domain.DefaultAntigravityModelMapping[name]; supported {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -733,7 +734,7 @@ func TestDefaultPricingIncludesGemini36FlashRates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPricingService_Gemini4ArgonThinkingTiersUseBasePricing(t *testing.T) {
|
||||
basePricing := &LiteLLMModelPricing{InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6, CacheReadInputTokenCost: 0.1e-6}
|
||||
basePricing := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6, CacheReadInputTokenCost: 0.2e-6}
|
||||
cyberPricing := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6, CacheReadInputTokenCost: 0.2e-6}
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
|
||||
"gemini-4-argon": basePricing,
|
||||
@@ -763,11 +764,11 @@ func TestBillingService_Gemini4ArgonFallbacksAreBillable(t *testing.T) {
|
||||
model string
|
||||
input, output, read float64
|
||||
}{
|
||||
{"gemini-4-argon", 2, 10, 0.1},
|
||||
{"gemini-4-argon-high", 2, 10, 0.1},
|
||||
{"gemini-4-argon-low", 2, 10, 0.1},
|
||||
{"gemini-4-argon-medium", 2, 10, 0.1},
|
||||
{"models/gemini-4-argon", 2, 10, 0.1},
|
||||
{"gemini-4-argon", 4, 20, 0.2},
|
||||
{"gemini-4-argon-high", 4, 20, 0.2},
|
||||
{"gemini-4-argon-low", 4, 20, 0.2},
|
||||
{"gemini-4-argon-medium", 4, 20, 0.2},
|
||||
{"models/gemini-4-argon", 4, 20, 0.2},
|
||||
{"gemini-4-argon-cyber-permissive", 4, 20, 0.2},
|
||||
{"gemini-4-argon-cyber", 4, 20, 0.2},
|
||||
{"publishers/google/models/gemini-4-argon-cyber-permissive", 4, 20, 0.2},
|
||||
@@ -779,6 +780,9 @@ func TestBillingService_Gemini4ArgonFallbacksAreBillable(t *testing.T) {
|
||||
require.InDelta(t, tc.output, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, tc.read, cost.CacheReadCost, 1e-12)
|
||||
require.InDelta(t, tc.input+tc.output+tc.read, cost.TotalCost, 1e-12)
|
||||
priority, err := svc.CalculateCostWithServiceTier(tc.model, tokens, 1, "priority")
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, (tc.input+tc.output+tc.read)*1.8, priority.TotalCost, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -797,8 +801,8 @@ func TestDefaultPricingIncludesGemini4ArgonRates(t *testing.T) {
|
||||
provider string
|
||||
input, output, read float64
|
||||
}{
|
||||
{"gemini-4-argon", "gemini", 2e-6, 10e-6, 0.1e-6},
|
||||
{"gemini-4-argon-high", "gemini", 2e-6, 10e-6, 0.1e-6},
|
||||
{"gemini-4-argon", "gemini", 4e-6, 20e-6, 0.2e-6},
|
||||
{"gemini-4-argon-high", "gemini", 4e-6, 20e-6, 0.2e-6},
|
||||
{"gemini-4-argon-cyber-permissive", "vertex_ai-language-models", 4e-6, 20e-6, 0.2e-6},
|
||||
} {
|
||||
t.Run(tc.model, func(t *testing.T) {
|
||||
@@ -816,7 +820,7 @@ func TestDefaultPricingIncludesGemini4ArgonRates(t *testing.T) {
|
||||
require.Zero(t, pricing.CacheStorageCostPerTokenPerHour)
|
||||
})
|
||||
}
|
||||
require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-argon")
|
||||
require.Contains(t, pricingSvc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "gemini"}), "gemini-4-argon")
|
||||
}
|
||||
|
||||
func TestBillingService_Gemini4HydrogenFallbackIsBillable(t *testing.T) {
|
||||
@@ -865,7 +869,7 @@ func TestDefaultPricingIncludesGemini4HydrogenRates(t *testing.T) {
|
||||
require.InDelta(t, 0.135e-6, pricing.CacheReadInputTokenCostPriority, 1e-15)
|
||||
require.Zero(t, pricing.LongContextInputTokenThreshold)
|
||||
require.Zero(t, pricing.CacheStorageCostPerTokenPerHour)
|
||||
require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-hydrogen")
|
||||
require.Contains(t, pricingSvc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "gemini"}), "gemini-4-hydrogen")
|
||||
}
|
||||
|
||||
func TestDefaultPricingIncludesGrok47FastRates(t *testing.T) {
|
||||
@@ -1038,10 +1042,10 @@ func TestParsePricingData_PreservesServiceTierPriorityFields(t *testing.T) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ListModelNamesByProvider
|
||||
// ListModelNamesForPlatform
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestListModelNamesByProvider_ReturnsMatchingModels(t *testing.T) {
|
||||
func TestListModelNamesForPlatform_ReturnsMatchingModels(t *testing.T) {
|
||||
svc := &PricingService{
|
||||
pricingData: map[string]*LiteLLMModelPricing{
|
||||
"claude-opus-4-5-20251101": {LiteLLMProvider: "anthropic", InputCostPerToken: 1.5e-5},
|
||||
@@ -1051,45 +1055,60 @@ func TestListModelNamesByProvider_ReturnsMatchingModels(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
got := svc.ListModelNamesByProvider("anthropic")
|
||||
got := svc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "anthropic"})
|
||||
require.ElementsMatch(t, []string{"claude-opus-4-5-20251101", "claude-sonnet-4-5"}, got)
|
||||
// Must be sorted
|
||||
require.Equal(t, "claude-opus-4-5-20251101", got[0])
|
||||
require.Equal(t, "claude-sonnet-4-5", got[1])
|
||||
}
|
||||
|
||||
func TestListModelNamesByProvider_CaseInsensitive(t *testing.T) {
|
||||
func TestListModelNamesForPlatform_AntigravityIncludesCatalogedGeminiMappings(t *testing.T) {
|
||||
svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
|
||||
"claude-sonnet-4-6": {LiteLLMProvider: "anthropic"},
|
||||
"gemini-2.5-pro": {LiteLLMProvider: "vertex_ai-language-models"},
|
||||
"gemini-4-carbon": {LiteLLMProvider: "gemini"},
|
||||
"gemini-embedding-001": {LiteLLMProvider: "vertex_ai-embedding-models"},
|
||||
}}
|
||||
platform, ok := domain.LookupPlatform(domain.PlatformAntigravity)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []string{"claude-sonnet-4-6", "gemini-2.5-pro", "gemini-4-carbon"}, svc.ListModelNamesForPlatform(platform))
|
||||
platform, ok = domain.LookupPlatform(domain.PlatformAnthropic)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []string{"claude-sonnet-4-6"}, svc.ListModelNamesForPlatform(platform))
|
||||
}
|
||||
|
||||
func TestListModelNamesForPlatform_CaseInsensitive(t *testing.T) {
|
||||
svc := &PricingService{
|
||||
pricingData: map[string]*LiteLLMModelPricing{
|
||||
"gpt-4o": {LiteLLMProvider: "OpenAI", InputCostPerToken: 5e-6},
|
||||
},
|
||||
}
|
||||
|
||||
got := svc.ListModelNamesByProvider("openai")
|
||||
got := svc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "openai"})
|
||||
require.Equal(t, []string{"gpt-4o"}, got)
|
||||
|
||||
got2 := svc.ListModelNamesByProvider("OPENAI")
|
||||
got2 := svc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "OPENAI"})
|
||||
require.Equal(t, []string{"gpt-4o"}, got2)
|
||||
}
|
||||
|
||||
func TestListModelNamesByProvider_NoMatch(t *testing.T) {
|
||||
func TestListModelNamesForPlatform_NoMatch(t *testing.T) {
|
||||
svc := &PricingService{
|
||||
pricingData: map[string]*LiteLLMModelPricing{
|
||||
"gpt-4o": {LiteLLMProvider: "openai", InputCostPerToken: 5e-6},
|
||||
},
|
||||
}
|
||||
|
||||
got := svc.ListModelNamesByProvider("anthropic")
|
||||
got := svc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "anthropic"})
|
||||
require.NotNil(t, got)
|
||||
require.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestListModelNamesByProvider_EmptyCatalog(t *testing.T) {
|
||||
func TestListModelNamesForPlatform_EmptyCatalog(t *testing.T) {
|
||||
svc := &PricingService{
|
||||
pricingData: map[string]*LiteLLMModelPricing{},
|
||||
}
|
||||
|
||||
got := svc.ListModelNamesByProvider("openai")
|
||||
got := svc.ListModelNamesForPlatform(domain.PlatformSpec{LiteLLMProvider: "openai"})
|
||||
require.NotNil(t, got)
|
||||
require.Empty(t, got)
|
||||
}
|
||||
|
||||
@@ -2870,34 +2870,34 @@
|
||||
"supports_service_tier": true
|
||||
},
|
||||
"gemini-4-argon": {
|
||||
"cache_read_input_token_cost": 1e-07,
|
||||
"cache_read_input_token_cost_priority": 1.8e-07,
|
||||
"input_cost_per_token": 2e-06,
|
||||
"input_cost_per_token_priority": 3.6e-06,
|
||||
"cache_read_input_token_cost": 2e-07,
|
||||
"cache_read_input_token_cost_priority": 3.6e-07,
|
||||
"input_cost_per_token": 4e-06,
|
||||
"input_cost_per_token_priority": 7.2e-06,
|
||||
"litellm_provider": "gemini",
|
||||
"max_input_tokens": 1048576,
|
||||
"max_output_tokens": 65536,
|
||||
"max_tokens": 65536,
|
||||
"mode": "chat",
|
||||
"output_cost_per_token": 1e-05,
|
||||
"output_cost_per_token_priority": 1.8e-05,
|
||||
"output_cost_per_token": 2e-05,
|
||||
"output_cost_per_token_priority": 3.6e-05,
|
||||
"source": "https://ai.google.dev/gemini-api/docs/pricing",
|
||||
"supports_prompt_caching": true,
|
||||
"supports_reasoning": true,
|
||||
"supports_service_tier": true
|
||||
},
|
||||
"gemini-4-carbon": {
|
||||
"cache_read_input_token_cost": 1e-07,
|
||||
"cache_read_input_token_cost_priority": 1.8e-07,
|
||||
"input_cost_per_token": 2e-06,
|
||||
"input_cost_per_token_priority": 3.6e-06,
|
||||
"cache_read_input_token_cost": 2e-07,
|
||||
"cache_read_input_token_cost_priority": 3.6e-07,
|
||||
"input_cost_per_token": 4e-06,
|
||||
"input_cost_per_token_priority": 7.2e-06,
|
||||
"litellm_provider": "gemini",
|
||||
"max_input_tokens": 1048576,
|
||||
"max_output_tokens": 65536,
|
||||
"max_tokens": 65536,
|
||||
"mode": "chat",
|
||||
"output_cost_per_token": 1e-05,
|
||||
"output_cost_per_token_priority": 1.8e-05,
|
||||
"output_cost_per_token": 2e-05,
|
||||
"output_cost_per_token_priority": 3.6e-05,
|
||||
"source": "https://aistudio.google.com/docs/pricing#gemini-4-carbon",
|
||||
"supports_prompt_caching": true,
|
||||
"supports_reasoning": true,
|
||||
|
||||
@@ -279,6 +279,24 @@ TOTP_ENCRYPTION_KEY=
|
||||
# Antigravity User-Agent 版本号(后台设置 antigravity_user_agent_version 优先;留空使用内置默认 1.23.2)
|
||||
# ANTIGRAVITY_USER_AGENT_VERSION=
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Antigravity Upstream (Optional)
|
||||
# Antigravity 上游(可选,留空保持内置行为)
|
||||
# -----------------------------------------------------------------------------
|
||||
# Generation endpoint. Empty: accounts whose plan_type is a paid tier use the
|
||||
# daily endpoint (daily-cloudcode-pa.googleapis.com) and every other account uses
|
||||
# production (cloudcode-pa.googleapis.com). daily / sandbox: always daily.
|
||||
# Any other value (e.g. prod): always production.
|
||||
# 生成请求的上游域名。留空:plan_type 为付费档的账号走 daily,其余账号走生产域名;
|
||||
# daily / sandbox:一律走 daily;其他值(如 prod):一律走生产域名。
|
||||
GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL=
|
||||
# Cooldown in seconds after an Antigravity 429 that carries no reset time
|
||||
# (e.g. a bare RESOURCE_EXHAUSTED). Empty or non-positive falls back to
|
||||
# gateway.antigravity_fallback_cooldown_minutes (default 1 minute).
|
||||
# 上游 429 未带重置时间(如裸 RESOURCE_EXHAUSTED)时的冷却秒数;
|
||||
# 留空或非正数时使用 gateway.antigravity_fallback_cooldown_minutes(默认 1 分钟)。
|
||||
GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS=
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Rate Limiting (Optional)
|
||||
# 速率限制(可选)
|
||||
|
||||
@@ -528,6 +528,10 @@ gateway:
|
||||
# 让上游决定是否返回思考摘要。长时间没有数据的思考阶段可能触发流超时。
|
||||
# Env: GATEWAY_ANTIGRAVITY_GEMINI_OMIT_INCLUDE_THOUGHTS
|
||||
antigravity_gemini_omit_include_thoughts: false
|
||||
# Antigravity cooldown (minutes) after a 429 that carries no reset time.
|
||||
# GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS, when set to a positive value, overrides it in seconds.
|
||||
# Antigravity 上游 429 未带重置时间时的冷却分钟数;环境变量 GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS 为正数时按秒覆盖。
|
||||
antigravity_fallback_cooldown_minutes: 1
|
||||
# Stream data interval timeout (seconds), 0=disable
|
||||
# 流数据间隔超时(秒),0=禁用
|
||||
stream_data_interval_timeout: 180
|
||||
|
||||
@@ -59,6 +59,8 @@ services:
|
||||
# Gateway values come from Compose .env or the shell.
|
||||
# Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior.
|
||||
- GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false}
|
||||
- GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL=${GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL:-}
|
||||
- GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS=${GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS:-}
|
||||
- GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5}
|
||||
- SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna}
|
||||
- GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0}
|
||||
|
||||
@@ -141,6 +141,9 @@ services:
|
||||
- GEMINI_CLI_OAUTH_CLIENT_SECRET=${GEMINI_CLI_OAUTH_CLIENT_SECRET:-}
|
||||
- ANTIGRAVITY_OAUTH_CLIENT_SECRET=${ANTIGRAVITY_OAUTH_CLIENT_SECRET:-}
|
||||
- ANTIGRAVITY_USER_AGENT_VERSION=${ANTIGRAVITY_USER_AGENT_VERSION:-}
|
||||
# Antigravity upstream overrides; empty keeps the built-in behavior.
|
||||
- GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL=${GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL:-}
|
||||
- GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS=${GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS:-}
|
||||
|
||||
# =======================================================================
|
||||
# Security Configuration (URL Allowlist)
|
||||
|
||||
@@ -107,6 +107,9 @@ services:
|
||||
- GEMINI_CLI_OAUTH_CLIENT_SECRET=${GEMINI_CLI_OAUTH_CLIENT_SECRET:-}
|
||||
- ANTIGRAVITY_OAUTH_CLIENT_SECRET=${ANTIGRAVITY_OAUTH_CLIENT_SECRET:-}
|
||||
- ANTIGRAVITY_USER_AGENT_VERSION=${ANTIGRAVITY_USER_AGENT_VERSION:-}
|
||||
# Antigravity upstream overrides; empty keeps the built-in behavior.
|
||||
- GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL=${GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL:-}
|
||||
- GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS=${GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS:-}
|
||||
|
||||
# =======================================================================
|
||||
# Gateway Upstream, Scheduling & Image Configuration
|
||||
|
||||
@@ -138,6 +138,9 @@ services:
|
||||
- GEMINI_CLI_OAUTH_CLIENT_SECRET=${GEMINI_CLI_OAUTH_CLIENT_SECRET:-}
|
||||
- ANTIGRAVITY_OAUTH_CLIENT_SECRET=${ANTIGRAVITY_OAUTH_CLIENT_SECRET:-}
|
||||
- ANTIGRAVITY_USER_AGENT_VERSION=${ANTIGRAVITY_USER_AGENT_VERSION:-}
|
||||
# Antigravity upstream overrides; empty keeps the built-in behavior.
|
||||
- GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL=${GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL:-}
|
||||
- GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS=${GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS:-}
|
||||
|
||||
# =======================================================================
|
||||
# Security Configuration (URL Allowlist)
|
||||
|
||||
@@ -7128,14 +7128,13 @@ const handleAntigravityValidateRT = async (refreshTokenInput: string) => {
|
||||
// Generate account name with index for batch
|
||||
const accountName = refreshTokens.length > 1 ? `${form.name} #${i + 1}` : form.name
|
||||
|
||||
// Note: Antigravity doesn't have buildExtraInfo, so we pass empty extra or rely on credentials
|
||||
const createPayload = withAntigravityConfirmFlag({
|
||||
name: accountName,
|
||||
notes: form.notes,
|
||||
platform: 'antigravity',
|
||||
type: 'oauth',
|
||||
credentials,
|
||||
extra: withUpstreamRequestIdHeader({}),
|
||||
extra: withUpstreamRequestIdHeader(buildAntigravityExtra()),
|
||||
proxy_id: form.proxy_id,
|
||||
concurrency: form.concurrency,
|
||||
load_factor: form.load_factor ?? undefined,
|
||||
|
||||
@@ -54,6 +54,9 @@ vi.mock('@/api/admin', () => ({
|
||||
importCodexSession: importCodexSessionMock,
|
||||
createOpenAICodexPAT: createOpenAICodexPATMock,
|
||||
},
|
||||
antigravity: {
|
||||
refreshAntigravityToken: vi.fn().mockResolvedValue({ access_token: 'test-access-token' }),
|
||||
},
|
||||
settings: {
|
||||
getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false, providers: [] }),
|
||||
getSettings: vi.fn().mockResolvedValue({}),
|
||||
@@ -94,7 +97,7 @@ const OAuthAuthorizationFlowStub = defineComponent({
|
||||
initialInputMethod: String,
|
||||
},
|
||||
data: () => ({ inputMethod: 'manual' }),
|
||||
emits: ['import-codex-session', 'import-codex-pat'],
|
||||
emits: ['import-codex-session', 'import-codex-pat', 'validate-refresh-token'],
|
||||
template: `
|
||||
<div>
|
||||
<button data-testid="import-codex-session" @click="$emit('import-codex-session', 'session-json')">session</button>
|
||||
@@ -900,6 +903,32 @@ describe('CreateAccountModal OpenAI long-context billing', () => {
|
||||
expect(createAccountMock.mock.calls[0]?.[0]?.upstream_billing_probe_enabled).toBe(false)
|
||||
})
|
||||
|
||||
it('preserves Antigravity account options for every refresh token imported', async () => {
|
||||
const wrapper = mountModal()
|
||||
await selectButtonByText(wrapper, 'Antigravity')
|
||||
await wrapper.get('[data-tour="account-form-name"]').setValue('Antigravity import')
|
||||
for (const option of ['mixedScheduling', 'allowOverages']) {
|
||||
const label = wrapper.findAll('label').find(label => label.text() === `admin.accounts.${option}`)
|
||||
if (!label) throw new Error(`Missing ${option} checkbox`)
|
||||
await label.get('input').setValue(true)
|
||||
}
|
||||
await wrapper.get('[data-testid="upstream-request-id-header"]').setValue('x-trace-id')
|
||||
await wrapper.get('#create-account-form').trigger('submit.prevent')
|
||||
await flushPromises()
|
||||
wrapper.getComponent(OAuthAuthorizationFlowStub).vm.$emit('validate-refresh-token', 'test-one\ntest-two')
|
||||
await flushPromises()
|
||||
|
||||
expect(createAccountMock).toHaveBeenCalledTimes(2)
|
||||
for (const [payload] of createAccountMock.mock.calls) {
|
||||
expect(payload.extra).toEqual({
|
||||
mixed_scheduling: true,
|
||||
allow_overages: true,
|
||||
upstream_request_id_header: 'x-trace-id',
|
||||
})
|
||||
}
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('antigravity upstream 创建默认携带上游倍率探测开关', async () => {
|
||||
// antigravity upstream 走独立创建 helper,
|
||||
// 也必须与其余 API-key 平台一样默认开启探测并传递开关。
|
||||
|
||||
@@ -122,6 +122,24 @@
|
||||
<p v-else class="text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ t("admin.groups.codexModelsManifest.disabledHint") }}
|
||||
</p>
|
||||
|
||||
<!-- Independent of pinned accounts: also applies to scheduler discovery. -->
|
||||
<div class="mt-3 flex items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<label class="text-sm text-gray-700 dark:text-gray-300">
|
||||
{{ t("admin.groups.codexModelsManifest.keepHiddenAutoModes") }}
|
||||
</label>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ t("admin.groups.codexModelsManifest.keepHiddenAutoModesHint") }}
|
||||
</p>
|
||||
</div>
|
||||
<Toggle
|
||||
data-testid="codex-manifest-keep-hidden-auto-modes-toggle"
|
||||
:aria-label="t('admin.groups.codexModelsManifest.keepHiddenAutoModes')"
|
||||
:model-value="config.keep_hidden_auto_modes ?? false"
|
||||
@update:model-value="emitUpdate({ keep_hidden_auto_modes: $event })"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -102,6 +102,20 @@ describe("CodexManifestAccountsField", () => {
|
||||
expect(enabled.text()).toContain("admin.groups.codexModelsManifest.enabledHint");
|
||||
});
|
||||
|
||||
it("offers the hidden automatic modes switch independently of pinned accounts", async () => {
|
||||
const wrapper = mountField(disabledConfig());
|
||||
const toggle = wrapper.find('[data-testid="codex-manifest-keep-hidden-auto-modes-toggle"]');
|
||||
|
||||
expect(toggle.exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain("admin.groups.codexModelsManifest.keepHiddenAutoModes");
|
||||
|
||||
await toggle.trigger("click");
|
||||
|
||||
const emitted = wrapper.emitted("update:modelValue");
|
||||
expect(emitted).toHaveLength(1);
|
||||
expect(emitted?.[0]?.[0]).toEqual({ ...disabledConfig(), keep_hidden_auto_modes: true });
|
||||
});
|
||||
|
||||
it("selects accounts from search results and removes them via tags", async () => {
|
||||
vi.mocked(adminAPI.accounts.list).mockResolvedValue({
|
||||
items: [
|
||||
|
||||
@@ -1036,9 +1036,9 @@ function generateOpenAIFiles(baseUrl: string, apiKey: string): FileConfig[] {
|
||||
model = "${model}"
|
||||
review_model = "${model}"
|
||||
web_search = "live"
|
||||
${reasoningEffortLine}disable_response_storage = true
|
||||
${codexLocalCatalogToml.value}network_access = "enabled"
|
||||
windows_wsl_setup_acknowledged = true
|
||||
${reasoningEffortLine}${codexLocalCatalogToml.value}
|
||||
[sandbox_workspace_write]
|
||||
network_access = true
|
||||
|
||||
[model_providers.OpenAI]
|
||||
name = "OpenAI"
|
||||
@@ -1271,9 +1271,6 @@ ${codexLocalCatalogToml.value}# Optional:
|
||||
# review_model = "${model}"
|
||||
# model_reasoning_effort = "medium"
|
||||
# model_context_window = 500000
|
||||
# disable_response_storage = true
|
||||
# network_access = "enabled"
|
||||
# windows_wsl_setup_acknowledged = true
|
||||
|
||||
[model_providers.sub2api]
|
||||
name = "Sub2API Grok"
|
||||
@@ -1348,7 +1345,6 @@ function generateRoutedCodexFiles(
|
||||
model_provider = "sub2api"
|
||||
model = "${model}"
|
||||
review_model = "${model}"
|
||||
disable_response_storage = true
|
||||
${codexLocalCatalogToml.value}
|
||||
[model_providers.sub2api]
|
||||
name = "Sub2API ${label}"
|
||||
@@ -1383,9 +1379,9 @@ function generateOpenAIWsFiles(baseUrl: string, apiKey: string): FileConfig[] {
|
||||
model = "${model}"
|
||||
review_model = "${model}"
|
||||
web_search = "live"
|
||||
${reasoningEffortLine}disable_response_storage = true
|
||||
${codexLocalCatalogToml.value}network_access = "enabled"
|
||||
windows_wsl_setup_acknowledged = true
|
||||
${reasoningEffortLine}${codexLocalCatalogToml.value}
|
||||
[sandbox_workspace_write]
|
||||
network_access = true
|
||||
|
||||
[model_providers.OpenAI]
|
||||
name = "OpenAI"
|
||||
|
||||
@@ -1150,4 +1150,56 @@ describe('UseKeyModal', () => {
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Codex rejects these removed top-level keys, and network_access now only
|
||||
// exists as a boolean under [sandbox_workspace_write].
|
||||
it('generates only config keys supported by current Codex clients', async () => {
|
||||
const wrapper = mount(UseKeyModal, {
|
||||
props: {
|
||||
show: true,
|
||||
apiKey: 'sk-test',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
platform: 'openai'
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
BaseDialog: { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
Icon: { template: '<span />' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for (const transport of ['keys.useKeyModal.cliTabs.codexCli', 'keys.useKeyModal.cliTabs.codexCliWs']) {
|
||||
const transportTab = wrapper.findAll('button').find(
|
||||
(button) => button.text().trim() === transport
|
||||
)
|
||||
expect(transportTab).toBeDefined()
|
||||
await transportTab!.trigger('click')
|
||||
await nextTick()
|
||||
|
||||
const configToml = wrapper.findAll('pre code')
|
||||
.map((code) => code.text())
|
||||
.find((content) => content.includes('model_provider = "OpenAI"'))!
|
||||
expect(configToml).not.toContain('disable_response_storage')
|
||||
expect(configToml).not.toContain('windows_wsl_setup_acknowledged')
|
||||
expect(configToml).not.toMatch(/^network_access = "enabled"$/m)
|
||||
expect(configToml).toContain('[sandbox_workspace_write]\nnetwork_access = true')
|
||||
}
|
||||
|
||||
await wrapper.setProps({ platform: 'deepseek' })
|
||||
await nextTick()
|
||||
const codexTab = wrapper.findAll('button').find(
|
||||
(button) => button.text().includes('keys.useKeyModal.cliTabs.codexCli')
|
||||
)
|
||||
expect(codexTab).toBeDefined()
|
||||
await codexTab!.trigger('click')
|
||||
await nextTick()
|
||||
|
||||
const routedConfig = wrapper.findAll('pre code')
|
||||
.map((code) => code.text())
|
||||
.find((content) => content.includes('[model_providers.sub2api]'))!
|
||||
expect(routedConfig).not.toContain('disable_response_storage')
|
||||
expect(routedConfig).not.toContain('windows_wsl_setup_acknowledged')
|
||||
expect(routedConfig).not.toMatch(/^network_access = "enabled"$/m)
|
||||
})
|
||||
})
|
||||
@@ -1178,7 +1178,9 @@ export default {
|
||||
searchEmpty: 'No matching accounts',
|
||||
fallback: 'Fall back to the scheduler when all pinned accounts are unavailable',
|
||||
fallbackHint: 'Off: return 503 / the upstream error. On: fall back to the existing scheduler path.',
|
||||
selectAtLeastOne: 'Select at least one account after enabling pinned accounts'
|
||||
selectAtLeastOne: 'Select at least one account after enabling pinned accounts',
|
||||
keepHiddenAutoModes: 'Keep upstream-hidden Codex automatic modes',
|
||||
keepHiddenAutoModesHint: 'Keep automatic modes such as codex-auto-review that upstream already hides from the model picker instead of removing them. Codex then reviews approvals with its dedicated reviewer model, and an otherwise unchanged upstream manifest keeps its ETag. Off by default.'
|
||||
},
|
||||
compositeRoutes: {
|
||||
action: 'Routes',
|
||||
|
||||
@@ -451,6 +451,7 @@ export default {
|
||||
original: 'Original',
|
||||
billed: 'Billed',
|
||||
noRecords: 'No usage records found. Try adjusting your filters.',
|
||||
statsUnavailable: 'Usage statistics unavailable',
|
||||
failedToLoad: 'Failed to load usage logs',
|
||||
noDataToExport: 'No data to export',
|
||||
exportSuccess: 'Usage data exported successfully',
|
||||
|
||||
@@ -1175,7 +1175,9 @@ export default {
|
||||
searchEmpty: '未找到匹配账号',
|
||||
fallback: '选定账号全部不可用时回退调度器',
|
||||
fallbackHint: '关闭时返回 503 / 上游错误;开启时回退到现有调度器选账路径。',
|
||||
selectAtLeastOne: '开启固定账号后至少选择一个账号'
|
||||
selectAtLeastOne: '开启固定账号后至少选择一个账号',
|
||||
keepHiddenAutoModes: '保留上游隐藏的 Codex 自动模式',
|
||||
keepHiddenAutoModesHint: '保留 codex-auto-review 等上游已在模型选择器中隐藏的自动模式,不再移除。Codex 将使用专用审查模型完成自动审批;上游清单没有其他改动时可沿用上游 ETag。默认关闭。'
|
||||
},
|
||||
compositeRoutes: {
|
||||
action: '路由',
|
||||
|
||||
@@ -456,6 +456,7 @@ export default {
|
||||
original: '原始',
|
||||
billed: '计费',
|
||||
noRecords: '未找到使用记录,请尝试调整筛选条件。',
|
||||
statsUnavailable: '用量统计暂不可用',
|
||||
failedToLoad: '加载使用记录失败',
|
||||
noDataToExport: '没有可导出的数据',
|
||||
exportSuccess: '使用数据导出成功',
|
||||
|
||||
@@ -687,6 +687,8 @@ export interface CodexModelsManifestConfig {
|
||||
enabled: boolean
|
||||
account_ids: number[]
|
||||
fallback_to_scheduler: boolean
|
||||
// Keep upstream-hidden Codex automatic modes (codex-auto-*) in the manifest.
|
||||
keep_hidden_auto_modes?: boolean
|
||||
}
|
||||
|
||||
export type CompositeRouteMatchType = 'exact' | 'prefix'
|
||||
|
||||
@@ -4818,6 +4818,7 @@ const createCodexManifestDefaults = (): CodexModelsManifestConfig => ({
|
||||
enabled: false,
|
||||
account_ids: [],
|
||||
fallback_to_scheduler: false,
|
||||
keep_hidden_auto_modes: false,
|
||||
});
|
||||
const editCodexManifestConfig = ref<CodexModelsManifestConfig>(createCodexManifestDefaults());
|
||||
const editCodexManifestAccountNames = ref<Record<number, string>>({});
|
||||
@@ -6096,6 +6097,7 @@ const handleEdit = async (group: AdminGroup) => {
|
||||
enabled: savedCodexManifestConfig.enabled ?? false,
|
||||
account_ids: [...(savedCodexManifestConfig.account_ids ?? [])],
|
||||
fallback_to_scheduler: savedCodexManifestConfig.fallback_to_scheduler ?? false,
|
||||
keep_hidden_auto_modes: savedCodexManifestConfig.keep_hidden_auto_modes ?? false,
|
||||
};
|
||||
editCodexManifestAccountNames.value = {};
|
||||
for (const id of editCodexManifestConfig.value.account_ids) {
|
||||
@@ -6249,6 +6251,7 @@ const handleUpdateGroup = async () => {
|
||||
enabled: editCodexManifestConfig.value.enabled,
|
||||
account_ids: [...editCodexManifestConfig.value.account_ids],
|
||||
fallback_to_scheduler: editCodexManifestConfig.value.fallback_to_scheduler,
|
||||
keep_hidden_auto_modes: editCodexManifestConfig.value.keep_hidden_auto_modes ?? false,
|
||||
}
|
||||
: createCodexManifestDefaults(),
|
||||
supported_model_scopes: normalizeSupportedModelScopesForPlatform(
|
||||
|
||||
@@ -586,6 +586,7 @@ const exportToExcel = async () => {
|
||||
t('admin.usage.inputTokens'), t('admin.usage.outputTokens'),
|
||||
t('admin.usage.cacheReadTokens'), t('admin.usage.cacheCreationTokens'),
|
||||
t('admin.usage.inputCost'), t('admin.usage.outputCost'),
|
||||
t('usage.imageInputCost'), t('usage.imageOutputCost'),
|
||||
t('admin.usage.cacheReadCost'), t('admin.usage.cacheCreationCost'),
|
||||
t('usage.rate'), t('usage.accountMultiplier'), t('usage.original'), t('usage.userBilled'), t('usage.accountBilled'),
|
||||
t('usage.firstToken'), t('usage.duration'),
|
||||
@@ -603,8 +604,9 @@ const exportToExcel = async () => {
|
||||
log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.reasoning_effort), formatReasoningEffort(log.upstream_reasoning_effort || log.reasoning_effort), log.group?.name || '',
|
||||
log.inbound_endpoint || '', log.upstream_endpoint || '', getRequestTypeLabel(log),
|
||||
log.input_tokens, log.output_tokens, log.cache_read_tokens, log.cache_creation_tokens,
|
||||
log.input_cost?.toFixed(6) || '0.000000', log.output_cost?.toFixed(6) || '0.000000',
|
||||
log.cache_read_cost?.toFixed(6) || '0.000000', log.cache_creation_cost?.toFixed(6) || '0.000000',
|
||||
log.input_cost ?? 0, log.output_cost ?? 0,
|
||||
log.image_input_cost ?? 0, log.image_output_cost ?? 0,
|
||||
log.cache_read_cost ?? 0, log.cache_creation_cost ?? 0,
|
||||
log.rate_multiplier?.toPrecision(4) || '1.00', (log.account_rate_multiplier ?? 1).toPrecision(4),
|
||||
log.total_cost?.toFixed(6) || '0.000000', log.actual_cost?.toFixed(6) || '0.000000',
|
||||
((log.account_stats_cost ?? log.total_cost) * (log.account_rate_multiplier ?? 1)).toFixed(6), log.first_token_ms ?? '', log.duration_ms,
|
||||
|
||||
@@ -263,7 +263,10 @@ describe("GroupsView Codex manifest binding", () => {
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="codex-manifest-value"]').text()).toBe(
|
||||
JSON.stringify(sourceGroup.codex_models_manifest_config),
|
||||
JSON.stringify({
|
||||
...sourceGroup.codex_models_manifest_config,
|
||||
keep_hidden_auto_modes: false,
|
||||
}),
|
||||
);
|
||||
|
||||
await wrapper.get('[data-testid="codex-manifest-enable"]').trigger("click");
|
||||
@@ -281,6 +284,7 @@ describe("GroupsView Codex manifest binding", () => {
|
||||
enabled: true,
|
||||
account_ids: [17],
|
||||
fallback_to_scheduler: false,
|
||||
keep_hidden_auto_modes: false,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -434,7 +434,7 @@ describe('GroupsView duplicate action', () => {
|
||||
await flushPromises()
|
||||
expect(updateGroup).toHaveBeenCalledWith(42, expect.objectContaining({
|
||||
codex_models_manifest_config: {
|
||||
enabled: true, account_ids: [5], fallback_to_scheduler: true
|
||||
enabled: true, account_ids: [5], fallback_to_scheduler: true, keep_hidden_auto_modes: false
|
||||
}
|
||||
}))
|
||||
|
||||
|
||||
@@ -778,7 +778,7 @@ describe('admin UsageView ranking tab', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('admin UsageView model audit export', () => {
|
||||
describe('admin UsageView Excel export', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
list.mockReset().mockResolvedValue({ items: [], total: 0, pages: 0 })
|
||||
@@ -844,4 +844,27 @@ describe('admin UsageView model audit export', () => {
|
||||
expect(row.slice(5, 9)).toEqual(['gpt-5.6-sol', 'gpt-5.5', 'gpt-5.4', 'Yes'])
|
||||
expect(saveAs).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('exports numeric cost components for image and text-only requests', async () => {
|
||||
exportList.mockResolvedValueOnce({
|
||||
items: [
|
||||
{ input_cost: 0.001, image_input_cost: 0.020, image_output_cost: 0.120, total_cost: 0.141 },
|
||||
{ output_cost: 0.003, cache_read_cost: 0.002, cache_creation_cost: 0.004, total_cost: 0.009 },
|
||||
],
|
||||
total: 2,
|
||||
})
|
||||
const wrapper = mountRouteFilteredUsageView()
|
||||
await (wrapper.vm as any).exportToExcel()
|
||||
|
||||
const headers = aoaToSheet.mock.calls[0][0][0]
|
||||
const rows = sheetAddAoa.mock.calls[0][1]
|
||||
const costColumns = [
|
||||
'admin.usage.inputCost', 'admin.usage.outputCost', 'usage.imageInputCost',
|
||||
'usage.imageOutputCost', 'admin.usage.cacheReadCost', 'admin.usage.cacheCreationCost',
|
||||
].map(header => headers.indexOf(header))
|
||||
expect(rows.map(row => costColumns.map(column => row[column]))).toEqual([
|
||||
[0.001, 0, 0.020, 0.120, 0, 0],
|
||||
[0, 0.003, 0, 0, 0.002, 0.004],
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -213,23 +213,25 @@
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-gray-500 dark:text-gray-400">{{ t('keys.today') }}:</span>
|
||||
<span
|
||||
v-if="usageLoading && !usageStats[row.id]"
|
||||
v-if="usageLoading"
|
||||
data-test="usage-pending"
|
||||
class="inline-block h-3 w-14 animate-pulse rounded bg-gray-200 dark:bg-dark-600"
|
||||
/>
|
||||
<span v-else class="font-medium text-gray-900 dark:text-white">
|
||||
${{ (usageStats[row.id]?.today_actual_cost ?? 0).toFixed(4) }}
|
||||
<span v-else-if="usageStats[row.id]" class="font-medium text-gray-900 dark:text-white">
|
||||
${{ usageStats[row.id].today_actual_cost.toFixed(4) }}
|
||||
</span>
|
||||
<span v-else :title="t('usage.statsUnavailable')">—</span>
|
||||
</div>
|
||||
<div class="mt-0.5 flex items-center gap-1.5">
|
||||
<span class="text-gray-500 dark:text-gray-400">{{ t('keys.total') }}:</span>
|
||||
<span
|
||||
v-if="usageLoading && !usageStats[row.id]"
|
||||
v-if="usageLoading"
|
||||
class="inline-block h-3 w-14 animate-pulse rounded bg-gray-200 dark:bg-dark-600"
|
||||
/>
|
||||
<span v-else class="font-medium text-gray-900 dark:text-white">
|
||||
${{ (usageStats[row.id]?.total_actual_cost ?? 0).toFixed(4) }}
|
||||
<span v-else-if="usageStats[row.id]" class="font-medium text-gray-900 dark:text-white">
|
||||
${{ usageStats[row.id].total_actual_cost.toFixed(4) }}
|
||||
</span>
|
||||
<span v-else :title="t('usage.statsUnavailable')">—</span>
|
||||
</div>
|
||||
<!-- Quota progress (if quota is set) -->
|
||||
<div v-if="row.quota > 0" class="mt-1.5">
|
||||
@@ -1599,6 +1601,7 @@ const loadApiKeys = async () => {
|
||||
abortController = controller
|
||||
const { signal } = controller
|
||||
loading.value = true
|
||||
usageStats.value = {}
|
||||
usageLoading.value = false
|
||||
try {
|
||||
// Build filters
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
<template>
|
||||
<AppLayout>
|
||||
<div class="space-y-6">
|
||||
<UsageStatsCards :stats="usageStats" :show-account-cost="false" :strike-standard-cost="true" />
|
||||
<UsageStatsCards v-if="usageStats" :stats="usageStats" :show-account-cost="false" :strike-standard-cost="true" />
|
||||
|
||||
<p v-else class="card p-4 text-sm text-gray-500" role="status">
|
||||
{{ endpointStatsLoading ? t('common.loading') : t('usage.statsUnavailable') }}
|
||||
</p>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="card p-4">
|
||||
@@ -330,6 +334,7 @@ const applyErrorFilters = () => {
|
||||
let abortController: AbortController | null = null
|
||||
let chartReqSeq = 0
|
||||
let statsReqSeq = 0
|
||||
let errorReqSeq = 0
|
||||
let modelStatsReqSeq = 0
|
||||
|
||||
const formatLocalDate = (date: Date): string =>
|
||||
@@ -468,6 +473,7 @@ const loadLogs = async () => {
|
||||
|
||||
const loadStats = async () => {
|
||||
const seq = ++statsReqSeq
|
||||
usageStats.value = null
|
||||
endpointStatsLoading.value = true
|
||||
try {
|
||||
const stats = await usageAPI.getStats(normalizedFilters.value)
|
||||
@@ -866,12 +872,15 @@ const resetErrorRows = () => {
|
||||
if (activeTab.value === 'errors') {
|
||||
void loadErrors()
|
||||
} else {
|
||||
++errorReqSeq
|
||||
errorLoading.value = false
|
||||
errorRows.value = []
|
||||
errorTotal.value = 0
|
||||
}
|
||||
}
|
||||
|
||||
const loadErrors = async () => {
|
||||
const seq = ++errorReqSeq
|
||||
errorLoading.value = true
|
||||
try {
|
||||
const resp = await usageAPI.listMyErrorRequests({
|
||||
@@ -886,13 +895,17 @@ const loadErrors = async () => {
|
||||
sort_by: errorSortBy.value,
|
||||
sort_order: errorSortOrder.value,
|
||||
})
|
||||
if (seq !== errorReqSeq) return
|
||||
errorRows.value = resp.items
|
||||
errorTotal.value = resp.total
|
||||
} catch (error) {
|
||||
if (seq !== errorReqSeq) return
|
||||
errorRows.value = []
|
||||
errorTotal.value = 0
|
||||
console.error('[UsageView] loadErrors failed:', error)
|
||||
appStore.showError(t('usage.errors.failedToLoad'))
|
||||
} finally {
|
||||
errorLoading.value = false
|
||||
if (seq === errorReqSeq) errorLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -928,6 +941,7 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
++errorReqSeq
|
||||
abortController?.abort()
|
||||
document.removeEventListener('click', handleColumnClickOutside)
|
||||
})
|
||||
|
||||
@@ -683,7 +683,21 @@ describe('user KeysView column settings', () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.find('[data-test="usage-pending"]').exists()).toBe(false)
|
||||
expect(wrapper.get('[data-test="usage"]').text()).toContain('$0.0000')
|
||||
const usage = () => wrapper.get('[data-test="usage"]').text()
|
||||
expect(usage()).not.toContain('$')
|
||||
expect(usage()).toContain('—')
|
||||
|
||||
getDashboardApiKeysUsage.mockResolvedValueOnce({
|
||||
stats: { 1: { api_key_id: 1, today_actual_cost: 0, total_actual_cost: 12 } },
|
||||
})
|
||||
await wrapper.get('button[title="Refresh"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(usage()).toContain('$0.0000')
|
||||
expect(usage()).toContain('$12.0000')
|
||||
|
||||
await wrapper.get('button[title="Refresh"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(usage()).not.toContain('$')
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -159,9 +159,9 @@ function mountUsageView() {
|
||||
Select: true,
|
||||
DateRangePicker: true,
|
||||
Icon: true,
|
||||
UsageStatsCards: chartStub,
|
||||
UsageStatsCards: { name: 'UsageStatsCards', props: ['stats'], template: '<div />' },
|
||||
UsageTable: { ...chartStub, props: ['columns'] },
|
||||
UserErrorRequestsTable: chartStub,
|
||||
UserErrorRequestsTable: { name: 'UserErrorRequestsTable', props: ['rows', 'total', 'loading'], template: '<div />' },
|
||||
ModelDistributionChart: chartStub,
|
||||
GroupDistributionChart: chartStub,
|
||||
EndpointDistributionChart: chartStub,
|
||||
@@ -217,6 +217,59 @@ describe('user UsageView', () => {
|
||||
getAvailable.mockResolvedValue([{ id: 1, name: 'default' }])
|
||||
})
|
||||
|
||||
it('invalidates the summary when the key changes and recovers on refresh', async () => {
|
||||
const wrapper = mountUsageView()
|
||||
await flushPromises()
|
||||
const cards = () => wrapper.findComponent({ name: 'UsageStatsCards' })
|
||||
expect(cards().props('stats').total_actual_cost).toBe(0.08)
|
||||
|
||||
let rejectStats!: (error: Error) => void
|
||||
getStats.mockReturnValueOnce(new Promise((_, reject) => { rejectStats = reject }))
|
||||
const select = wrapper.findAllComponents(Select).find((item) =>
|
||||
item.props('options').some((option: SelectOption) => option.label === 'All API Keys')
|
||||
)!
|
||||
select.vm.$emit('update:modelValue', 1)
|
||||
select.vm.$emit('change', 1)
|
||||
await flushPromises()
|
||||
expect(cards().exists()).toBe(false)
|
||||
|
||||
rejectStats(new Error('timeout'))
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('usage.statsUnavailable')
|
||||
getStats.mockResolvedValueOnce({ total_actual_cost: 0 })
|
||||
await wrapper.findAll('button').find((button) => button.text() === 'Refresh')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(cards().props('stats').total_actual_cost).toBe(0)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('only accepts the current error page response and loading state', async () => {
|
||||
const wrapper = mountUsageView()
|
||||
await flushPromises()
|
||||
let resolveFirst!: (result: unknown) => void
|
||||
let rejectSecond!: (error: Error) => void
|
||||
let resolveLatest!: (result: unknown) => void
|
||||
listMyErrorRequests
|
||||
.mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve }))
|
||||
.mockReturnValueOnce(new Promise((_, reject) => { rejectSecond = reject }))
|
||||
.mockReturnValueOnce(new Promise((resolve) => { resolveLatest = resolve }))
|
||||
await wrapper.findAll('button').find((button) => button.text() === 'Error records')!.trigger('click')
|
||||
const table = wrapper.getComponent({ name: 'UserErrorRequestsTable' })
|
||||
table.vm.$emit('update:page', 2)
|
||||
table.vm.$emit('update:page', 3)
|
||||
rejectSecond(new Error('obsolete request'))
|
||||
await flushPromises()
|
||||
expect(table.props('loading')).toBe(true)
|
||||
expect(showError).not.toHaveBeenCalled()
|
||||
|
||||
resolveLatest({ items: [{ id: 3 }], total: 55 })
|
||||
await flushPromises()
|
||||
resolveFirst({ items: [{ id: 1 }], total: 10 })
|
||||
await flushPromises()
|
||||
expect(table.props()).toMatchObject({ rows: [{ id: 3 }], total: 55, loading: false })
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('loads logs, stats, model stats, and snapshot on first render', async () => {
|
||||
const wrapper = mountUsageView()
|
||||
await flushPromises()
|
||||
|
||||
Reference in new issue
Block a user