From 80ba2fca9a9095efb1f998c0694b9f08a714f511 Mon Sep 17 00:00:00 2001 From: li Date: Sat, 28 Nov 2026 14:41:57 +0800 Subject: [PATCH 01/25] fix(websearch): authenticate Tavily with a Bearer header Tavily's /search endpoint documents a single credential scheme, `Authorization: Bearer `, and its official Python/JS SDKs send only that header. The provider still put the key in an `api_key` body field and sent no Authorization header, so web search emulation through Tavily relied on an undocumented contract. Brave and Exa in the same package already send their keys as headers. Send the key as a Bearer token and drop it from the request body. The old unit test only marshalled the request struct and asserted the body `api_key`, so it locked in the stale contract without exercising Search(); replace it with a test that drives Search() through a recording transport and checks the outgoing headers and body. Refs #7201 --- backend/internal/pkg/websearch/tavily.go | 4 +- backend/internal/pkg/websearch/tavily_test.go | 51 +++++++++++++------ 2 files changed, 37 insertions(+), 18 deletions(-) diff --git a/backend/internal/pkg/websearch/tavily.go b/backend/internal/pkg/websearch/tavily.go index ac4928a6f8..1adf96abb9 100644 --- a/backend/internal/pkg/websearch/tavily.go +++ b/backend/internal/pkg/websearch/tavily.go @@ -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"` diff --git a/backend/internal/pkg/websearch/tavily_test.go b/backend/internal/pkg/websearch/tavily_test.go index e1b6819a6b..99406d166b 100644 --- a/backend/internal/pkg/websearch/tavily_test.go +++ b/backend/internal/pkg/websearch/tavily_test.go @@ -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) { From 1e8f5f3c393580e8df2eac6f2b3d9f80549ee46f Mon Sep 17 00:00:00 2001 From: li Date: Sat, 28 Nov 2026 14:45:25 +0800 Subject: [PATCH 02/25] fix(websearch): show why the admin web search test failed The admin "Test" button for web search emulation always showed "internal error". Manager.TestSearch dropped every provider's error with a bare `continue` and returned "no available provider", and the handler passed that plain error to response.ErrorFrom, which maps it to a 500 with the generic message. A wrong key, an exhausted plan, a proxy failure and an unsaved config all looked the same. Keep each provider's error in TestSearch and join them when every provider fails, and return the cause from the handler as a 400, the same way the SMTP connection test already does. TestSearch is admin only; the production SearchWithBestProvider path is unchanged. Refs #7201 --- .../handler/admin/setting_handler_runtime.go | 3 +- ...etting_handler_websearch_emulation_test.go | 37 +++++++++ backend/internal/pkg/websearch/manager.go | 8 +- .../pkg/websearch/manager_testsearch_test.go | 78 +++++++++++++++++++ 4 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 backend/internal/handler/admin/setting_handler_websearch_emulation_test.go create mode 100644 backend/internal/pkg/websearch/manager_testsearch_test.go diff --git a/backend/internal/handler/admin/setting_handler_runtime.go b/backend/internal/handler/admin/setting_handler_runtime.go index 3cc4ef4b60..cfcbea3167 100644 --- a/backend/internal/handler/admin/setting_handler_runtime.go +++ b/backend/internal/handler/admin/setting_handler_runtime.go @@ -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) diff --git a/backend/internal/handler/admin/setting_handler_websearch_emulation_test.go b/backend/internal/handler/admin/setting_handler_websearch_emulation_test.go new file mode 100644 index 0000000000..0bc1ca7391 --- /dev/null +++ b/backend/internal/handler/admin/setting_handler_websearch_emulation_test.go @@ -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") +} diff --git a/backend/internal/pkg/websearch/manager.go b/backend/internal/pkg/websearch/manager.go index 938d142825..b8a85e348f 100644 --- a/backend/internal/pkg/websearch/manager.go +++ b/backend/internal/pkg/websearch/manager.go @@ -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") } diff --git a/backend/internal/pkg/websearch/manager_testsearch_test.go b/backend/internal/pkg/websearch/manager_testsearch_test.go new file mode 100644 index 0000000000..ee858694f0 --- /dev/null +++ b/backend/internal/pkg/websearch/manager_testsearch_test.go @@ -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") +} From e40a84edacbb10ad9eebe09ff40863aee29db33f Mon Sep 17 00:00:00 2001 From: li Date: Sat, 28 Nov 2026 15:25:28 +0800 Subject: [PATCH 03/25] fix(apicompat): keep max_tokens above the Responses thinking budget ResponsesToAnthropicRequest defaults max_tokens to 8192 when the Responses request has no max_output_tokens, and turns any effort above low into thinking.type=enabled with an effort-derived budget: 10240 for high, 32768 for xhigh/max. Anthropic requires max_tokens to be greater than budget_tokens, so every effort above medium was rejected with "budget_tokens must be less than max_tokens". Codex never sends max_output_tokens, so its users could not work around it. After the conversion, raise max_tokens to budget_tokens + 1000 when an enabled budget does not fit, the same rule and padding the Antigravity transformer applies in ensureMaxTokensGreaterThanBudget. Requests that already fit, adaptive thinking, and requests without thinking are unchanged. Fixes #6569 --- .../responses_to_anthropic_request.go | 20 +++++ ...onses_to_anthropic_thinking_budget_test.go | 75 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 backend/internal/pkg/apicompat/responses_to_anthropic_thinking_budget_test.go diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go index 5f8c5664fc..3679d66a06 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go @@ -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 { diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_thinking_budget_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_thinking_budget_test.go new file mode 100644 index 0000000000..62f611edd3 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_thinking_budget_test.go @@ -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) +} From cd73d7975e1f672dafc46525620e974edcc4a01d Mon Sep 17 00:00:00 2001 From: r266-tech Date: Sun, 29 Nov 2026 13:32:29 +0900 Subject: [PATCH 04/25] fix(accounts): preserve Antigravity options on refresh token import --- .../components/account/CreateAccountModal.vue | 3 +- .../__tests__/CreateAccountModal.spec.ts | 31 ++++++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 026c00df43..b63642fcbe 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -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, diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index 0e30886822..0b8f26954e 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -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: `
@@ -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 平台一样默认开启探测并传递开关。 From bc1a71708343184213c8a8ffb493296be0200966 Mon Sep 17 00:00:00 2001 From: pangxin12345 <4714571+pangxin12345@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:39:24 +0800 Subject: [PATCH 05/25] fix(openai): normalize standalone browser tabs context The Codex desktop in-app browser sends the open tabs as an agent-namespace function_call_output named browser_tabs without a call_id. It is not on the untrusted-context allowlist, so HTTP Responses requests are rejected with "function_call_output requires call_id". Add it next to browser_info and terminal_info so it is rewritten into a user message like the others. --- .../internal/handler/openai_page_context.go | 4 +- .../handler/openai_page_context_test.go | 52 ++++++++++++++++++- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index 4ce0dba35a..e8856a38fc 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -16,7 +16,7 @@ var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_( 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", + "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan", ) || !hasUniqueJSONMembers(body) { return body, false } @@ -89,7 +89,7 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { 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. diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index fb59bac2a0..e7ac8ae2b3 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -54,7 +54,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"}]}`) @@ -373,3 +373,53 @@ 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 := "\nTab 1 (active): https://example.com/\nTab 2: https://example.org/\n" + 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, ""+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"}, + {"name prefix", "name", "browser_tabs_extra"}, + {"name case", "name", "Browser_tabs"}, + {"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) + }) + } +} From ef3649aafe8b7caf293621f0dae366d3a82b34fc Mon Sep 17 00:00:00 2001 From: r266-tech Date: Mon, 30 Nov 2026 03:36:50 +0900 Subject: [PATCH 06/25] fix(frontend): keep usage displays tied to the current request --- frontend/src/i18n/locales/en/dashboard.ts | 1 + frontend/src/i18n/locales/zh/dashboard.ts | 1 + frontend/src/views/user/KeysView.vue | 15 +++-- frontend/src/views/user/UsageView.vue | 18 +++++- .../src/views/user/__tests__/KeysView.spec.ts | 16 +++++- .../views/user/__tests__/UsageView.spec.ts | 57 ++++++++++++++++++- 6 files changed, 97 insertions(+), 11 deletions(-) diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 02e1df3489..a2fa1a165b 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -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', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 535da0dd46..3a2d43ab66 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -456,6 +456,7 @@ export default { original: '原始', billed: '计费', noRecords: '未找到使用记录,请尝试调整筛选条件。', + statsUnavailable: '用量统计暂不可用', failedToLoad: '加载使用记录失败', noDataToExport: '没有可导出的数据', exportSuccess: '使用数据导出成功', diff --git a/frontend/src/views/user/KeysView.vue b/frontend/src/views/user/KeysView.vue index df56222ca2..8f5e0f70c5 100644 --- a/frontend/src/views/user/KeysView.vue +++ b/frontend/src/views/user/KeysView.vue @@ -213,23 +213,25 @@
{{ t('keys.today') }}: - - ${{ (usageStats[row.id]?.today_actual_cost ?? 0).toFixed(4) }} + + ${{ usageStats[row.id].today_actual_cost.toFixed(4) }} + —
{{ t('keys.total') }}: - - ${{ (usageStats[row.id]?.total_actual_cost ?? 0).toFixed(4) }} + + ${{ usageStats[row.id].total_actual_cost.toFixed(4) }} + —
@@ -1599,6 +1601,7 @@ const loadApiKeys = async () => { abortController = controller const { signal } = controller loading.value = true + usageStats.value = {} usageLoading.value = false try { // Build filters diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index 688bc19817..0d17f36607 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -1,7 +1,11 @@ diff --git a/frontend/src/components/admin/group/__tests__/CodexManifestAccountsField.spec.ts b/frontend/src/components/admin/group/__tests__/CodexManifestAccountsField.spec.ts index fdaacc23e4..77a322f340 100644 --- a/frontend/src/components/admin/group/__tests__/CodexManifestAccountsField.spec.ts +++ b/frontend/src/components/admin/group/__tests__/CodexManifestAccountsField.spec.ts @@ -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: [ diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts index 250c911632..80fe950b6c 100644 --- a/frontend/src/i18n/locales/en/admin/overview.ts +++ b/frontend/src/i18n/locales/en/admin/overview.ts @@ -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', diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts index 5386e7c5a7..95026ff78f 100644 --- a/frontend/src/i18n/locales/zh/admin/overview.ts +++ b/frontend/src/i18n/locales/zh/admin/overview.ts @@ -1175,7 +1175,9 @@ export default { searchEmpty: '未找到匹配账号', fallback: '选定账号全部不可用时回退调度器', fallbackHint: '关闭时返回 503 / 上游错误;开启时回退到现有调度器选账路径。', - selectAtLeastOne: '开启固定账号后至少选择一个账号' + selectAtLeastOne: '开启固定账号后至少选择一个账号', + keepHiddenAutoModes: '保留上游隐藏的 Codex 自动模式', + keepHiddenAutoModesHint: '保留 codex-auto-review 等上游已在模型选择器中隐藏的自动模式,不再移除。Codex 将使用专用审查模型完成自动审批;上游清单没有其他改动时可沿用上游 ETag。默认关闭。' }, compositeRoutes: { action: '路由', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index b1cc2e27cd..ab84337746 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -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' diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue index 9cf0bed13c..bac760dc3c 100644 --- a/frontend/src/views/admin/GroupsView.vue +++ b/frontend/src/views/admin/GroupsView.vue @@ -4818,6 +4818,7 @@ const createCodexManifestDefaults = (): CodexModelsManifestConfig => ({ enabled: false, account_ids: [], fallback_to_scheduler: false, + keep_hidden_auto_modes: false, }); const editCodexManifestConfig = ref(createCodexManifestDefaults()); const editCodexManifestAccountNames = ref>({}); @@ -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( diff --git a/frontend/src/views/admin/__tests__/GroupsView.codexManifest.spec.ts b/frontend/src/views/admin/__tests__/GroupsView.codexManifest.spec.ts index 574f7269b0..f618a8febb 100644 --- a/frontend/src/views/admin/__tests__/GroupsView.codexManifest.spec.ts +++ b/frontend/src/views/admin/__tests__/GroupsView.codexManifest.spec.ts @@ -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, }), ); diff --git a/frontend/src/views/admin/__tests__/GroupsView.duplicate.spec.ts b/frontend/src/views/admin/__tests__/GroupsView.duplicate.spec.ts index d125725228..a98cb00e51 100644 --- a/frontend/src/views/admin/__tests__/GroupsView.duplicate.spec.ts +++ b/frontend/src/views/admin/__tests__/GroupsView.duplicate.spec.ts @@ -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 } })) From 799aee99fd7a77585c0a3d82d391081904d55bde Mon Sep 17 00:00:00 2001 From: Ikhdev1 <60190988+Ikhdev1@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:24:11 +0300 Subject: [PATCH 22/25] fix(deps): update golang.org/x/image to v0.45.0 --- backend/go.mod | 2 +- backend/go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/go.mod b/backend/go.mod index a2c9dc0a5e..8c7c85294b 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -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 diff --git a/backend/go.sum b/backend/go.sum index 1a1a2ad4d1..855dc993aa 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -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= From f84d1d3eb2e2cc26ec10d88b5e911d3fc504c715 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 09:47:40 +0800 Subject: [PATCH 23/25] fix(codex): keep browser_tabs tag and name unknown agent context Rebasing onto #9152 made browser_tabs a known context name; add it to the known list so it keeps its tag and empty-output check instead of falling to the generic branch. Render unknown agent context names the way Codex renders context it does not send as a tool output, , when the name has the shape Codex derives names in ([A-Za-z0-9_]{1,128}). Other names still use the generic tag, so a client supplied name is never embedded unchecked. --- .../internal/handler/openai_page_context.go | 20 ++++++++--- .../handler/openai_page_context_test.go | 34 +++++++++++++++---- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index 784a93b97e..3aa1556943 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -13,6 +13,10 @@ import ( 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. @@ -101,12 +105,18 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { // 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 uses a -// generic tag instead of failing the request; the name is client supplied and -// must not be interpolated into the tag unchecked. +// 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: . 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) { - return "" + output + "", true + tag := "agent_context" + if codexContextTagName.MatchString(name) { + tag = name + } + return "" + output + "", true } if !validCodexUntrustedContext(name, output) { return "", false @@ -120,7 +130,7 @@ func codexUntrustedContextText(name, output string) (string, bool) { func knownCodexUntrustedContextName(name string) bool { switch name { - case "codex_apps_open_page", "browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan": + 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) diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index af5fbcd870..c5372f1e1e 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -3,6 +3,7 @@ package handler import ( "encoding/json" "net/http/httptest" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/service" @@ -140,11 +141,15 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) { 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"+output+"", item.Get("content.0.text").String()) + require.Equal(t, ""+want.output+"", 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.4.content").String()) + require.Equal(t, "hello", gjson.GetBytes(got, "input.7.content").String()) again, changed := normalizeCodexUntrustedContext(got) require.False(t, changed) require.Equal(t, got, again) @@ -181,7 +194,7 @@ func TestNormalizeCodexAgentContextEscapedAndBlankCallID(t *testing.T) { } { got, changed := normalizeCodexUntrustedContext([]byte(body)) require.True(t, changed) - require.Equal(t, "tabs", gjson.GetBytes(got, "input.0.content.0.text").String()) + require.Equal(t, "tabs", gjson.GetBytes(got, "input.0.content.0.text").String()) } } @@ -488,8 +501,6 @@ func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) { }{ {"real call id", "call_id", "call_real"}, {"other namespace", "namespace", "browser"}, - {"name prefix", "name", "browser_tabs_extra"}, - {"name case", "name", "Browser_tabs"}, {"empty output", "output", ""}, {"blank output", "output", " \n\t"}, {"object output", "output", map[string]any{"tabs": 2}}, @@ -504,3 +515,14 @@ func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) { }) } } + +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, "Tab 1: https://example.com/", gjson.GetBytes(got, "input.0.content.0.text").String()) + }) + } +} From 9f6e0f76ba294b7d0f5c4c839943933f89affc59 Mon Sep 17 00:00:00 2001 From: li Date: Wed, 2 Dec 2026 10:03:41 +0800 Subject: [PATCH 24/25] fix(deploy): pass Antigravity endpoint and 429 cooldown env through Compose GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL and GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS are read with os.Getenv, but the Compose files only interpolate an explicit list of variables. Setting either one in deploy/.env therefore never reached the container. Register both in .env.example (empty, so the built-in behavior is unchanged), pass them through every Compose file, and document the gateway.antigravity_fallback_cooldown_minutes key they fall back to. The existing docker-compose gateway env test now covers both variables. --- deploy/.env.example | 18 ++++++++++++++++++ deploy/config.example.yaml | 4 ++++ deploy/docker-compose.dev.yml | 2 ++ deploy/docker-compose.local.yml | 3 +++ deploy/docker-compose.standalone.yml | 3 +++ deploy/docker-compose.yml | 3 +++ 6 files changed, 33 insertions(+) diff --git a/deploy/.env.example b/deploy/.env.example index f16e3483d0..8ca473fe62 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -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) # 速率限制(可选) diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 66cac12786..7eb78aa80e 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -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 diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml index fd13301f69..29ce20e68f 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -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} diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index ea2827da5a..41690717db 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -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) diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index 0c544bd9ca..cca65afa0e 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -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 diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 4d94afb1ab..16dca74752 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -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) From 7613baf97c310ca676af5e06c62cf11e33720232 Mon Sep 17 00:00:00 2001 From: li Date: Wed, 2 Dec 2026 10:19:35 +0800 Subject: [PATCH 25/25] fix(openai): spend the earliest-expiring reset credit on manual reset The automatic reset sorts the available credits by expiry and consumes the first one by id, but the admin reset button sent no credit_id and let upstream pick. Upstream can then spend a later credit and leave the one closest to expiry to lapse, while the account list shows that earliest expiry next to the button. ResetCredit now reads the credit list first and targets the credit that expires first. When the list cannot name it (request failed, a credit without expiry or id, fewer credits listed than available, unparsable expiry) the request stays untargeted as before. --- .../service/openai_quota_manual_reset.go | 40 ++++++++ .../service/openai_quota_manual_reset_test.go | 98 +++++++++++++++++++ .../internal/service/openai_quota_service.go | 12 ++- .../service/openai_quota_spark_window_test.go | 8 ++ 4 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/openai_quota_manual_reset.go create mode 100644 backend/internal/service/openai_quota_manual_reset_test.go diff --git a/backend/internal/service/openai_quota_manual_reset.go b/backend/internal/service/openai_quota_manual_reset.go new file mode 100644 index 0000000000..a85f65fbe1 --- /dev/null +++ b/backend/internal/service/openai_quota_manual_reset.go @@ -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) +} diff --git a/backend/internal/service/openai_quota_manual_reset_test.go b/backend/internal/service/openai_quota_manual_reset_test.go new file mode 100644 index 0000000000..aaa727a5bc --- /dev/null +++ b/backend/internal/service/openai_quota_manual_reset_test.go @@ -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"]) + }) + } +} diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 5fd986a18c..ea3836ef54 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -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(). diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index 8bda444bf9..59d5287fc7 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -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 {