From f34df0e313b1a5e3ae8a929aaeca237c9062ee21 Mon Sep 17 00:00:00 2001 From: ninedrunk Date: Sat, 28 Nov 2026 12:52:13 +0800 Subject: [PATCH 01/45] =?UTF-8?q?feat(accounts):=20=E8=AE=A9=E6=89=80?= =?UTF-8?q?=E6=9C=89=E5=8F=97=E6=94=AF=E6=8C=81=E5=B9=B3=E5=8F=B0=E9=83=BD?= =?UTF-8?q?=E8=83=BD=E9=85=8D=E7=BD=AE=E8=B4=A6=E5=8F=B7=E7=BA=A7=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=81=9C=E8=B0=83=E9=98=88=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端已对 AllowedSchedulingThresholdPlatforms 中所有平台支持账号级 account_scheduling_threshold 覆盖,系统设置页也通过 SCHEDULING_THRESHOLD_PLATFORMS 展示了完整清单。 但账号编辑弹窗把 override 支持平台硬编码为 openai / anthropic / grok, 导致 Kimi / Zhipu GLM / MiniMax / OpenCode Go / Command Code 账号 即使后端完全支持,也没有 UI 可以配置账号级阈值。 创建账号弹窗则完全没有该选项。 改动: - 编辑弹窗改为从 SCHEDULING_THRESHOLD_PLATFORMS 派生支持平台, 消除前后端清单漂移; - 创建账号弹窗新增同样的账号级阈值覆盖入口; - 沿用 credentials.account_scheduling_threshold 键及原有语义。 不改动后端逻辑,不影响现有平台行为。 --- .../components/account/CreateAccountModal.vue | 54 +++++ .../components/account/EditAccountModal.vue | 6 +- ...itAccountModal.schedulingThreshold.spec.ts | 189 ++++++++++++++++++ .../src/i18n/locales/en/admin/accounts.ts | 1 + .../src/i18n/locales/zh/admin/accounts.ts | 1 + 5 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 24ba7aed1c..8478f2056c 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -581,6 +581,40 @@ + +
+
+
+ +

+ {{ t('admin.accounts.cnProviders.schedulingThresholdCreateHint') }} +

+
+ +
+
+ + +

{{ t('admin.accounts.accountSchedulingThresholdOverrideDisabledHint') }}

+
+
+
@@ -4164,6 +4198,7 @@ import { isValidWildcardPattern } from '@/composables/useModelWhitelist' import { adminAPI } from '@/api/admin' +import { SCHEDULING_THRESHOLD_PLATFORMS } from '@/api/admin/settings' import { useQuotaNotifyState } from '@/composables/useQuotaNotifyState' import { useAccountOAuth, @@ -4479,6 +4514,14 @@ const isGenericMultiProtocolPlatform = computed( const extraMultiProtocolPlatforms = computed(() => listPlatforms().filter(spec => !!spec.multi_protocol && !isCNProviderPlatform(spec.id) && spec.id !== 'opencode_go') ) +// 账号级自动停调阈值覆盖(创建时可选):写入 credentials.account_scheduling_threshold。 +// 仅对后端白名单平台显示;关闭/留空 = 跟随系统平台阈值。 +const ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY = 'account_scheduling_threshold' +const createSchedulingThresholdOverrideEnabled = ref(false) +const createSchedulingThresholdOverrideValue = ref(100) +const supportsCreateSchedulingThresholdOverride = computed(() => + (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) +) const genericAccountModes = computed(() => providerAccountModes(form.platform)) // 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。 const routesByModel = computed(() => providerRoutesByModel(form.platform)) @@ -6241,6 +6284,17 @@ const handleSubmit = async () => { } } + // 账号级自动停调阈值覆盖:仅白名单平台、勾选且值在 1..99 时写入 + // (100 = 禁用当前账号自动停调,不写则跟随系统平台阈值)。 + if ( + supportsCreateSchedulingThresholdOverride.value && + createSchedulingThresholdOverrideEnabled.value + ) { + const numeric = Math.trunc(Number(createSchedulingThresholdOverrideValue.value) || 100) + const clamped = Math.min(100, Math.max(1, numeric)) + credentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] = clamped + } + // Add model mapping if configured(OpenAI 开启自动透传时不应用) if (!isOpenAIModelRestrictionDisabled.value) { const modelMapping = buildModelMappingObject(modelRestrictionMode.value, allowedModels.value, modelMappings.value) diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index e1e50ec52a..15a1836ef0 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -3422,6 +3422,7 @@ import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' import { adminAPI } from '@/api/admin' +import { SCHEDULING_THRESHOLD_PLATFORMS } from '@/api/admin/settings' import { useQuotaNotifyState } from '@/composables/useQuotaNotifyState' import type { Account, @@ -5353,7 +5354,10 @@ const applyTempUnschedConfig = (credentials: Record) => { function supportsAccountSchedulingThresholdOverridePlatform(platform: Account['platform'] | undefined) { - return platform === 'openai' || platform === 'anthropic' || platform === 'grok' + // 与后端 AllowedSchedulingThresholdPlatforms 共用同一清单(系统设置页也用这份), + // 避免前端入口与后端白名单再次漂移。 + if (!platform) return false + return (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(platform) } function normalizeAccountSchedulingThresholdOverride(value: unknown): number | null { diff --git a/frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts new file mode 100644 index 0000000000..db6052eaa5 --- /dev/null +++ b/frontend/src/components/account/__tests__/EditAccountModal.schedulingThreshold.spec.ts @@ -0,0 +1,189 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent } from 'vue' +import { flushPromises, mount } from '@vue/test-utils' + +// 账号级自动停调阈值覆盖:GLM / MiniMax / OpenCode / Command Code 等 +// 套餐平台现在都能在账号编辑页设置该覆盖(此前仅 openai/anthropic/grok)。 + +const { updateAccountMock, checkMixedChannelRiskMock, authIsSimpleMode } = vi.hoisted(() => ({ + updateAccountMock: vi.fn(), + checkMixedChannelRiskMock: vi.fn(), + authIsSimpleMode: { value: true } +})) + +vi.mock('@/stores/app', () => ({ + useAppStore: () => ({ + showError: vi.fn(), + showSuccess: vi.fn(), + showInfo: vi.fn() + }) +})) + +vi.mock('@/stores/auth', () => ({ + useAuthStore: () => ({ + get isSimpleMode() { + return authIsSimpleMode.value + } + }) +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + accounts: { + update: updateAccountMock, + checkMixedChannelRisk: checkMixedChannelRiskMock, + previewUpstreamGroup: vi.fn() + }, + settings: { + getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false, providers: [] }), + getSettings: vi.fn().mockResolvedValue({}) + }, + tlsFingerprintProfiles: { + list: vi.fn().mockResolvedValue([]) + } + } +})) + +vi.mock('@/api/admin/accounts', () => ({ + getAntigravityDefaultModelMapping: vi.fn() +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ t: (key: string) => key }) + } +}) + +import EditAccountModal from '../EditAccountModal.vue' + +const BaseDialogStub = defineComponent({ + name: 'BaseDialog', + props: { show: { type: Boolean, default: false } }, + template: '
' +}) + +const GroupSelectorStub = defineComponent({ + name: 'GroupSelector', + props: { modelValue: { type: Array, default: () => [] } }, + emits: ['update:modelValue'], + template: '
' +}) + +const ModelWhitelistSelectorStub = defineComponent({ + name: 'ModelWhitelistSelector', + props: { modelMappings: { type: Array, default: () => [] }, modelValue: { type: Array, default: () => [] } }, + emits: ['update:modelValue'], + template: '
' +}) + +const SelectStub = defineComponent({ + name: 'SelectStub', + props: { + modelValue: { type: [String, Number, Boolean, null], default: '' }, + options: { type: Array, default: () => [] } + }, + emits: ['update:modelValue'], + template: ` + + ` +}) + +function buildAccount(platform: string, credentials: Record = {}) { + return { + id: 1, + name: `account-${platform}`, + notes: '', + platform, + type: 'apikey', + credentials: { api_key: 'key-test', base_url: '', ...credentials }, + extra: {}, + proxy_id: null, + concurrency: 1, + priority: 1, + rate_multiplier: 1, + status: 'active', + group_ids: [], + expires_at: null, + auto_pause_on_expired: false + } as any +} + +function mountModal(account: any) { + return mount(EditAccountModal, { + props: { show: true, account, proxies: [], groups: [] }, + global: { + stubs: { + BaseDialog: BaseDialogStub, + Select: SelectStub, + Icon: true, + ProxySelector: true, + GroupSelector: GroupSelectorStub, + ModelWhitelistSelector: ModelWhitelistSelectorStub + } + } + }) +} + +describe('EditAccountModal 账号自动停调阈值覆盖(套餐平台)', () => { + beforeEach(() => { + authIsSimpleMode.value = true + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + }) + + it.each(['zhipu', 'minimax', 'opencode_go', 'command_code'])( + '%s 账号显示阈值覆盖区块并能提交 account_scheduling_threshold', + async (platform) => { + const account = buildAccount(platform, { + account_mode: platform === 'zhipu' ? 'coding' : 'payg' + }) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + expect(wrapper.find('[data-testid="account-scheduling-threshold-section"]').exists()).toBe(true) + + await wrapper.get('[data-testid="account-scheduling-threshold-override-enabled"]').setValue(true) + await wrapper.get('[data-testid="account-scheduling-threshold-override-value"]').setValue('50') + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + await flushPromises() + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.credentials?.account_scheduling_threshold).toBe(50) + wrapper.unmount() + } + ) + + it('deepseek(余额型)不显示阈值覆盖区块', async () => { + const account = buildAccount('deepseek', { account_mode: 'payg' }) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + expect(wrapper.find('[data-testid="account-scheduling-threshold-section"]').exists()).toBe(false) + wrapper.unmount() + }) + + it('关闭覆盖后把 account_scheduling_threshold 置空(回退系统阈值)', async () => { + const account = buildAccount('zhipu', { + account_mode: 'coding', + account_scheduling_threshold: 50 + }) + updateAccountMock.mockResolvedValue(account) + const wrapper = mountModal(account) + + const enabled = wrapper.get('[data-testid="account-scheduling-threshold-override-enabled"]') + expect(enabled.element.checked).toBe(true) + const value = wrapper.get('[data-testid="account-scheduling-threshold-override-value"]') + expect(value.element.value).toBe('50') + + await enabled.setValue(false) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + await flushPromises() + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.credentials?.account_scheduling_threshold).toBeNull() + wrapper.unmount() + }) +}) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index bfdfec7f55..6da92454f7 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -154,6 +154,7 @@ export default { example: 'Example: …/organization/org-0610bE2D…/projects/proj_0798F20…/api_keys → org-0610bE2D… goes into "Organization ID", proj_0798F20… into "Project ID"', }, }, + schedulingThresholdCreateHint: 'Optional: override the platform auto-pause threshold for this account (upstream usage-window percent). Leave unchecked to follow the system setting.', balance: 'Balance --', window5h: '5h', windowWeekly: '7d', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 0d35c23776..4cb68a4bb7 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -367,6 +367,7 @@ export default { example: '示例:…/organization/org-0610bE2D…/projects/proj_0798F20…/api_keys → org-0610bE2D… 填「组织 ID」,proj_0798F20… 填「项目 ID」', }, }, + schedulingThresholdCreateHint: '可选:为该账号覆盖平台级自动停调阈值(按上游原生窗口百分比)。不勾选则跟随系统设置。', balance: '余额 --', window5h: '5h', windowWeekly: '7d', From 80ba2fca9a9095efb1f998c0694b9f08a714f511 Mon Sep 17 00:00:00 2001 From: li Date: Sat, 28 Nov 2026 14:41:57 +0800 Subject: [PATCH 02/45] 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 03/45] 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 04/45] 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 a622eca4f935329962ec85d1f240abbee58299e7 Mon Sep 17 00:00:00 2001 From: Erywim <59912860+erywim@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:19:19 +0800 Subject: [PATCH 05/45] fix(openai): strip safety review details from client-visible failed events --- ...enai_gateway_failed_event_sanitize_test.go | 40 +++++++++++++++++++ .../openai_gateway_response_handling.go | 13 ++++++ 2 files changed, 53 insertions(+) create mode 100644 backend/internal/service/openai_gateway_failed_event_sanitize_test.go diff --git a/backend/internal/service/openai_gateway_failed_event_sanitize_test.go b/backend/internal/service/openai_gateway_failed_event_sanitize_test.go new file mode 100644 index 0000000000..31f8fb55a1 --- /dev/null +++ b/backend/internal/service/openai_gateway_failed_event_sanitize_test.go @@ -0,0 +1,40 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestSanitizeOpenAIResponseFailedEventStripsSafetyReviewDetails(t *testing.T) { + payload := []byte(`{"type":"response.failed","sequence_number":3,"response":{"id":"resp_1","status":"failed","error":{"type":"invalid_request_error","code":"misalignment_policy_violation","message":"This request was blocked by our safety systems.","misalignment":{"detailed_explanation":"another user's private project summary","steer":{"message":"another user's private instruction"}}}}}`) + + out, changed := sanitizeOpenAIResponseFailedEventForClient(payload, "response.failed", false) + require.True(t, changed) + require.False(t, gjson.GetBytes(out, "response.error.misalignment").Exists()) + require.Equal(t, "misalignment_policy_violation", gjson.GetBytes(out, "response.error.code").String()) + require.Equal(t, "This request was blocked by our safety systems.", gjson.GetBytes(out, "response.error.message").String()) + require.NotContains(t, string(out), "another user's private") +} + +func TestSanitizeOpenAIErrorEventStripsSafetyReviewDetails(t *testing.T) { + payload := []byte(`{"type":"error","sequence_number":3,"error":{"type":"invalid_request_error","code":"misalignment_policy_violation","message":"This request was blocked by our safety systems.","misalignment":{"detailed_explanation":"another user's private project summary"}}}`) + + out, changed := sanitizeOpenAIResponseFailedEventForClient(payload, "error", false) + require.True(t, changed) + require.False(t, gjson.GetBytes(out, "error.misalignment").Exists()) + require.Equal(t, "misalignment_policy_violation", gjson.GetBytes(out, "error.code").String()) + require.Equal(t, "This request was blocked by our safety systems.", gjson.GetBytes(out, "error.message").String()) + require.NotContains(t, string(out), "another user's private") +} + +func TestSanitizeOpenAIFailedEventWithoutReviewDetailsIsUnchanged(t *testing.T) { + payload := []byte(`{"type":"response.failed","response":{"status":"failed","error":{"type":"server_error","code":"upstream_error","message":"Upstream response failed"}}}`) + + out, changed := sanitizeOpenAIResponseFailedEventForClient(payload, "response.failed", false) + require.False(t, changed) + require.JSONEq(t, string(payload), string(out)) +} diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 72a0d4df69..3555dd2887 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -2022,6 +2022,19 @@ func sanitizeOpenAIResponseFailedEventForClient(payload []byte, eventType string if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(updated); changed { updated = rewritten } + // A shared OAuth account can return a safety-review explanation that + // belongs to another downstream user's session. Keep the stable status, + // code and message, but never forward the review body. + for _, path := range []string{"response.error.misalignment", "error.misalignment"} { + if !gjson.GetBytes(updated, path).Exists() { + continue + } + next, err := sjson.DeleteBytes(updated, path) + if err != nil { + return payload, false + } + updated = next + } if !isFailedEvent { return updated, !bytes.Equal(updated, payload) } From df3c428142fcf6874dbafe2e9ec7d91aea3fac9c Mon Sep 17 00:00:00 2001 From: r266-tech Date: Sun, 29 Nov 2026 11:24:35 +0900 Subject: [PATCH 06/45] fix(openai): fail over standalone alpha search on API-key upstream 400 Some OpenAI-compatible relays reject the standalone Codex search endpoint with HTTP 400 while serving /v1/responses normally. The 400 was passed straight to the client, so search failed even when another account in the group could serve it. For API-key accounts, a 400 from /v1/alpha/search now fails over to the next eligible account without account-health side effects or same-account retries. When failover is exhausted the last upstream status and body are returned unchanged. Co-Authored-By: Claude Opus 5.5 --- .../internal/handler/openai_alpha_search.go | 4 +- .../handler/openai_alpha_search_test.go | 107 ++++++++++++++++++ .../handler/openai_gateway_handler.go | 4 + .../internal/service/openai_alpha_search.go | 29 ++++- .../service/openai_alpha_search_test.go | 22 ++-- 5 files changed, 152 insertions(+), 14 deletions(-) create mode 100644 backend/internal/handler/openai_alpha_search_test.go diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 8a76f6b23c..f7322b398c 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -220,7 +220,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err) + if failoverErr.Reason != service.OpenAIAlphaSearchRejectedReason { + h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err) + } if c.Writer.Size() != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return diff --git a/backend/internal/handler/openai_alpha_search_test.go b/backend/internal/handler/openai_alpha_search_test.go new file mode 100644 index 0000000000..394447e4f3 --- /dev/null +++ b/backend/internal/handler/openai_alpha_search_test.go @@ -0,0 +1,107 @@ +package handler + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type alphaSearchUpstream struct { + service.HTTPUpstream + successAccount int64 + calls []int64 +} + +const alphaSearchSuccess = `{"output":"search result"}` + +func alphaSearchRejection(accountID int64) string { + return fmt.Sprintf(`{ "error": {"message": "rejected by %d"} }`+"\n", accountID) +} + +func (u *alphaSearchUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.calls = append(u.calls, accountID) + status, contentType, body := http.StatusBadRequest, "application/problem+json", alphaSearchRejection(accountID) + if accountID == u.successAccount { + status, contentType, body = http.StatusOK, "application/json", alphaSearchSuccess + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": {contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + }, nil +} + +func TestAlphaSearchBadRequestFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + accountCount int + successAccount int64 + maxSwitches int + firstType string + wantCalls []int64 + wantStatus int + wantBody string + }{ + {"next account succeeds", 2, 2, 2, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusOK, alphaSearchSuccess}, + {"single account", 1, 0, 2, service.AccountTypeAPIKey, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)}, + {"all accounts reject", 2, 0, 3, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)}, + {"switch limit", 3, 3, 1, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)}, + {"oauth passes through", 2, 2, 2, service.AccountTypeOAuth, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &openAIWSFailoverHandlerAccountRepoStub{} + for i := 1; i <= tc.accountCount; i++ { + account := newPinnedCodexAccount(int64(i), service.StatusActive, true, false) + account.Concurrency = 0 + account.Credentials["pool_mode"] = true + account.Credentials["pool_mode_retry_status_codes"] = []any{400} + repo.accounts = append(repo.accounts, account) + } + if tc.firstType == service.AccountTypeOAuth { + repo.accounts[0].Type = tc.firstType + repo.accounts[0].Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"} + } + cfg := &config.Config{RunMode: config.RunModeSimple} + upstream := &alphaSearchUpstream{successAccount: tc.successAccount} + usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 4)} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + gateway := service.NewOpenAIGatewayService(repo, usage, nil, nil, nil, nil, nil, cfg, + nil, nil, service.NewBillingService(cfg, nil), service.NewRateLimitService(repo, nil, cfg, nil, nil), billing, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil) + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, &service.APIKeyService{}, nil, nil, nil, nil, cfg) + h.maxAccountSwitches = tc.maxSwitches + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", strings.NewReader(`{"model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`)) + group := &service.Group{ID: 42, Platform: service.PlatformOpenAI} + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &group.ID, Group: group, User: &service.User{ID: 2}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 2}) + + h.AlphaSearch(c) + + require.Equal(t, tc.wantCalls, upstream.calls) + require.Equal(t, tc.wantStatus, rec.Code) + require.Equal(t, tc.wantBody, rec.Body.String()) + require.Empty(t, repo.rateLimitedIDs) + if tc.wantStatus == http.StatusOK { + require.Len(t, usage.created, 1) + require.Equal(t, tc.successAccount, (<-usage.created).AccountID) + require.Equal(t, "application/json", rec.Header().Get("Content-Type")) + } else { + require.Empty(t, usage.created) + require.Equal(t, "application/problem+json", rec.Header().Get("Content-Type")) + } + }) + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0e8c94b9f4..20132b0ea8 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3640,6 +3640,10 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted) return } + if failoverErr.Reason == service.OpenAIAlphaSearchRejectedReason && !streamStarted { + h.gatewayService.WriteAlphaSearchResponse(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody) + return + } if failoverErr.Reason == service.OpenAIResponsesToolsUnsupportedReason { // No upstream request was sent for this local capability mismatch. Keep // the original client error without attributing it to upstream health. diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index e52183ab22..1b1b3e7834 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -18,6 +18,8 @@ import ( const ( chatgptCodexAlphaSearchURL = "https://chatgpt.com/backend-api/codex/alpha/search" openAIPlatformAlphaSearchURL = "https://api.openai.com/v1/alpha/search" + + OpenAIAlphaSearchRejectedReason GatewayFailureReason = "openai_alpha_search_rejected" ) // ForwardAlphaSearch proxies Codex standalone web search without binding the @@ -89,6 +91,16 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co return nil, fmt.Errorf("read alpha search response: %w", err) } + // API key 中转可能只拒绝独立搜索端点。直接换号,不重试同一账号, + // 也不把这次 400 计入账号健康;耗尽时仍透传最后一次上游响应。 + if account.Type == AccountTypeAPIKey && resp.StatusCode == http.StatusBadRequest { + return nil, &UpstreamFailoverError{ + StatusCode: resp.StatusCode, + ResponseBody: respBody, + ResponseHeaders: resp.Header, + Reason: OpenAIAlphaSearchRejectedReason, + } + } if resp.StatusCode >= http.StatusBadRequest { upstreamMessage := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))) if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMessage, respBody) || @@ -117,12 +129,7 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co if !account.IsShadow() { s.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, resp.Header) } - writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) - contentType := resp.Header.Get("Content-Type") - if contentType == "" { - contentType = "application/json" - } - c.Data(resp.StatusCode, contentType, respBody) + s.WriteAlphaSearchResponse(c, resp.StatusCode, resp.Header, respBody) if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { // 非 2xx(错误/重定向)已原样透传给客户端:不是一次成功的搜索,不计费。 return nil, nil @@ -137,6 +144,16 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co }, nil } +// WriteAlphaSearchResponse forwards the selected standalone search response, including an exhausted upstream 400. +func (s *OpenAIGatewayService) WriteAlphaSearchResponse(c *gin.Context, status int, headers http.Header, body []byte) { + writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), headers, s.responseHeaderFilter) + contentType := headers.Get("Content-Type") + if contentType == "" { + contentType = "application/json" + } + c.Data(status, contentType, body) +} + func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch( ctx context.Context, c *gin.Context, diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 0de2fe3394..64199e617b 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -244,7 +244,7 @@ func TestForwardAlphaSearchPATBackfillsMissingChatGPTAccountMetadata(t *testing. require.Equal(t, OpenAIAuthModePersonalAccessToken, account.Credentials["auth_mode"]) } -func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) { +func TestForwardAlphaSearchAPIKeyMapsModelAndFailsOverOnBadRequest(t *testing.T) { gin.SetMode(gin.TestMode) body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`) recorder := httptest.NewRecorder() @@ -252,13 +252,18 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) { c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) c.Request.Header.Set("Content-Type", "application/json") - upstreamBody := `{"error":{"type":"invalid_request_error","message":"bad search"}}` + upstreamBody := `{"error":{"type":"invalid_request_error","message":"organization has been disabled"}}` upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(upstreamBody)), }} - service := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + service := &OpenAIGatewayService{ + cfg: cfg, httpUpstream: upstream, accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } account := &Account{ ID: 7, Platform: PlatformOpenAI, @@ -274,11 +279,14 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndPassesThroughError(t *testing.T) { result, err := service.ForwardAlphaSearch(context.Background(), c, account, body) - require.NoError(t, err) - // 上游错误透传不是一次成功的搜索:不返回 result、不产生按次计费。 + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) require.Nil(t, result) - require.Equal(t, http.StatusBadRequest, recorder.Code) - require.JSONEq(t, upstreamBody, recorder.Body.String()) + require.Equal(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason) + require.Equal(t, http.StatusBadRequest, failoverErr.StatusCode) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.False(t, c.Writer.Written()) + require.Zero(t, repo.setErrorCalls) require.Equal(t, "https://compat.example/v4/alpha/search", upstream.lastReq.URL.String()) require.Equal(t, "Bearer sk-test", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "upstream-5.6", gjson.GetBytes(upstream.lastBody, "model").String()) From cd73d7975e1f672dafc46525620e974edcc4a01d Mon Sep 17 00:00:00 2001 From: r266-tech Date: Sun, 29 Nov 2026 13:32:29 +0900 Subject: [PATCH 07/45] 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 08/45] 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 09/45] 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 28/45] 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 c5b12503bbd3991a853c40815102a3b42687eb01 Mon Sep 17 00:00:00 2001 From: HuntercodeT <61233559+HuntercodeT@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:28:53 +0800 Subject: [PATCH 29/45] fix(openai): bound WebSocket HTTP bridge replay history --- .../handler/openai_gateway_handler.go | 3 +- .../service/grok_upstream_errors_test.go | 1 + .../service/openai_gateway_grok_test.go | 3 + .../openai_responses_created_at_test.go | 3 +- .../internal/service/openai_ws_forwarder.go | 1 + .../service/openai_ws_forwarder_ingress.go | 112 ++++++++---- .../internal/service/openai_ws_http_bridge.go | 95 +++++++--- .../service/openai_ws_http_bridge_history.go | 149 ++++++++++++++++ .../openai_ws_http_bridge_history_test.go | 164 ++++++++++++++++++ .../openai_ws_http_bridge_resume_test.go | 2 + .../service/openai_ws_http_bridge_test.go | 30 +++- 11 files changed, 492 insertions(+), 71 deletions(-) create mode 100644 backend/internal/service/openai_ws_http_bridge_history.go create mode 100644 backend/internal/service/openai_ws_http_bridge_history_test.go diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0e8c94b9f4..58ebfa6ef9 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -81,7 +81,8 @@ func newOpenAIWSUnsupportedModelSwitchError(model string) error { } func shouldReportOpenAIWSProxyAccountFailure(err error) bool { - return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && !service.IsOpenAIWSSessionPreemptedError(err) + return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && + !errors.Is(err, service.ErrResponsesWSBridgeHistoryLimit) && !service.IsOpenAIWSSessionPreemptedError(err) } // openAIWSIngressEndedByClient reports whether a finished ingress WebSocket turn diff --git a/backend/internal/service/grok_upstream_errors_test.go b/backend/internal/service/grok_upstream_errors_test.go index 3bd5ad3e73..799c1a7c95 100644 --- a/backend/internal/service/grok_upstream_errors_test.go +++ b/backend/internal/service/grok_upstream_errors_test.go @@ -279,6 +279,7 @@ func TestGrokContentPolicySSEErrorDoesNotMutateOrFailover(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok-4.5", "", "", "", "cache-id", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 3abfa7eefb..1382139fbb 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -3606,6 +3606,7 @@ func TestOpenAIWSHTTPBridgeGrok429PersistsRateLimit(t *testing.T) { context.Background(), nil, account, "token", []byte(`{"type":"response.create","model":"grok-4.3","input":"hi"}`), 64, "grok-4.3", "", "", "", "cache-id", 1, + nil, func([]byte) error { return nil }, ) @@ -3649,6 +3650,7 @@ func TestOpenAIWSHTTPBridgeSSEErrorSideEffectsRunOncePerPlatform(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func([]byte) error { writes++ return nil @@ -3680,6 +3682,7 @@ func TestOpenAIWSHTTPBridgeGrokExhaustedSuccessPersistsRateLimit(t *testing.T) { context.Background(), nil, account, "token", []byte(`{"type":"response.create","model":"grok-4.3","input":"hi"}`), 64, "grok-4.3", "", "", "", "cache-id", 1, + nil, func([]byte) error { return nil }, ) diff --git a/backend/internal/service/openai_responses_created_at_test.go b/backend/internal/service/openai_responses_created_at_test.go index b4aaac3dff..7aa37cffdc 100644 --- a/backend/internal/service/openai_responses_created_at_test.go +++ b/backend/internal/service/openai_responses_created_at_test.go @@ -264,6 +264,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_GrokStampsMissingCreatedAt(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok-4.5", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -292,7 +293,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_BareErrorSynthesizedFailedCarriesCreatedAt( payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - _, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + _, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) diff --git a/backend/internal/service/openai_ws_forwarder.go b/backend/internal/service/openai_ws_forwarder.go index b5a466949f..0aa12e035e 100644 --- a/backend/internal/service/openai_ws_forwarder.go +++ b/backend/internal/service/openai_ws_forwarder.go @@ -243,6 +243,7 @@ func (e *OpenAIWSClientCloseError) Reason() string { // OpenAIWSIngressHooks 定义入站 WS 每个 turn 的生命周期回调。 type OpenAIWSIngressHooks struct { + BridgeHistory *ResponsesWSBridgeHistory // ClientLifecycleContext is the request context before an ingress lease // adds its independent cancellation signal. Downstream writes bind to it // so shutdown and disconnect cancellation remain direct during lease loss. diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index e97faa44ed..267cb40b48 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -587,6 +587,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // is resolved again for each turn below so an in-connection model switch // cannot reuse another model's upstream cache identity. grokCacheSeedPayload := firstPayload.payloadRaw + history := openAIWSLegacyBridgeHistory{budget: &ResponsesWSBridgeHistory{}} + if hooks != nil && hooks.BridgeHistory != nil { + history.budget = hooks.BridgeHistory + } + defer history.close() + historyLost := false var bridgeReplayInput []json.RawMessage bridgeReplayInputExists := false var bridgeAccountFailoverInput []json.RawMessage @@ -630,27 +636,46 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( toolOutputCoverage := AnalyzeToolCallOutputContextCoverageBytes(currentBridgePayload.payloadRaw) needsBridgeReplay := currentBridgePayload.previousResponseID != "" || (toolOutputCoverage.HasFunctionCallOutput && !toolOutputCoverage.ContextCoversAllCallIDs) - // 一次解析当前 input,正常 replay 与 account-failover 两份序列共享同一批正文。 - bridgeCurrentItems, bridgeCurrentItemsExist, extractErr := openAIWSExtractNormalizedInputSequence( - currentBridgePayload.payloadRaw, - ) - if extractErr != nil { - return fmt.Errorf("build websocket http bridge replay input: %w", extractErr) + if needsBridgeReplay && historyLost { + return NewResponsesWSBridgeHistoryCloseError() + } + if !needsBridgeReplay { + // A self-contained request replaces the previous replay chain. + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + history.resize(0) + } + var turnReplayInput, turnAccountFailoverInput []json.RawMessage + var turnReplayInputExists, turnAccountFailoverInputExists bool + cacheTurn := ResponsesWSBridgeReplayInputFits(currentBridgePayload.payloadRaw, ResponsesWSBridgeHistoryLimit) + if cacheTurn { + items, exists, extractErr := openAIWSExtractNormalizedInputSequence(currentBridgePayload.payloadRaw) + if extractErr != nil { + return fmt.Errorf("build websocket http bridge replay input: %w", extractErr) + } + cacheTurn = history.reserve(ResponsesWSBridgeReplayItemsBytes(items)) + if cacheTurn { + items = CloneResponsesWSBridgeReplayItems(items) + turnReplayInput, turnReplayInputExists = buildOpenAIWSReplayInputSequenceFromItems( + bridgeReplayInput, bridgeReplayInputExists, items, exists, needsBridgeReplay, + ) + turnAccountFailoverInput, turnAccountFailoverInputExists = buildOpenAIWSReplayInputSequenceFromItems( + bridgeAccountFailoverInput, bridgeAccountFailoverInputExists, items, exists, needsBridgeReplay, + ) + turnBytes := ResponsesWSBridgeReplayItemsBytes(turnReplayInput) + ResponsesWSBridgeReplayItemsBytes(turnAccountFailoverInput) + cacheTurn = history.resize(turnBytes) + } + } else { + history.budget.LogLimit(openAIWSLegacyBridgeHistoryPath, "connection") + } + if !cacheTurn { + if needsBridgeReplay { + return NewResponsesWSBridgeHistoryCloseError() + } + turnReplayInput, turnAccountFailoverInput = nil, nil + turnReplayInputExists, turnAccountFailoverInputExists = false, false + history.resize(0) } - turnReplayInput, turnReplayInputExists := buildOpenAIWSReplayInputSequenceFromItems( - bridgeReplayInput, - bridgeReplayInputExists, - bridgeCurrentItems, - bridgeCurrentItemsExist, - needsBridgeReplay, - ) - turnAccountFailoverInput, turnAccountFailoverInputExists := buildOpenAIWSReplayInputSequenceFromItems( - bridgeAccountFailoverInput, - bridgeAccountFailoverInputExists, - bridgeCurrentItems, - bridgeCurrentItemsExist, - needsBridgeReplay, - ) if needsBridgeReplay && turnReplayInputExists { updatedPayload, setInputErr := setOpenAIWSPayloadInputSequence( currentBridgePayload.payloadRaw, @@ -684,6 +709,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return fmt.Errorf("resolve Grok websocket cache identity: %w", err) } } + collector := &openAIWSToolCallReplayCollector{ + all: openAIWSReplayOutput{reserve: history.reserve}, + reserve: history.reserve, + disabled: !cacheTurn, + } result, bridgeErr := s.proxyOpenAIWSHTTPBridgeTurn( ctx, c, @@ -697,6 +727,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentBridgePayload.imageInputSize, grokCacheIdentity, turn, + collector, writeClientMessage, ) if bridgeErr != nil && isOpenAIWSSessionPreempted(ctx) { @@ -731,23 +762,32 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if result == nil { return errors.New("websocket http bridge turn result is nil") } - // turnReplayInput/turnAccountFailoverInput 可能共享同一头数组(转移自 - // bridgeCurrentItems),保存历史必须经 combine 新建头,禁止就地 append。 - bridgeReplayInput = turnReplayInput - bridgeReplayInputExists = turnReplayInputExists - if result.wsReplayInputExists { - bridgeReplayInput = combineOpenAIWSReplayItems(bridgeReplayInput, result.wsReplayInput) - bridgeReplayInputExists = true - } - bridgeAccountFailoverInput = turnAccountFailoverInput - bridgeAccountFailoverInputExists = turnAccountFailoverInputExists - if len(result.wsAccountFailoverReplayInput) > 0 { - bridgeAccountFailoverInput = combineOpenAIWSReplayItems( - bridgeAccountFailoverInput, - result.wsAccountFailoverReplayInput, - ) - bridgeAccountFailoverInputExists = true + historyLost = !cacheTurn || collector.overflow + if historyLost { + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + history.resize(0) + } else { + // turnReplayInput/turnAccountFailoverInput 可能共享同一头数组(转移自 + // bridgeCurrentItems),保存历史必须经 combine 新建头,禁止就地 append。 + bridgeReplayInput = turnReplayInput + bridgeReplayInputExists = turnReplayInputExists + if result.wsReplayInputExists { + bridgeReplayInput = combineOpenAIWSReplayItems(bridgeReplayInput, result.wsReplayInput) + bridgeReplayInputExists = true + } + bridgeAccountFailoverInput = turnAccountFailoverInput + bridgeAccountFailoverInputExists = turnAccountFailoverInputExists + if len(result.wsAccountFailoverReplayInput) > 0 { + bridgeAccountFailoverInput = combineOpenAIWSReplayItems( + bridgeAccountFailoverInput, + result.wsAccountFailoverReplayInput, + ) + bridgeAccountFailoverInputExists = true + } + history.resize(ResponsesWSBridgeReplayItemsBytes(bridgeReplayInput) + ResponsesWSBridgeReplayItemsBytes(bridgeAccountFailoverInput)) } + history.budget.LogSize(openAIWSLegacyBridgeHistoryPath) if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { // Follow-up turns on this bridge retain their own upstream state; // publishing it by session hash would leak it to independent bridges. diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index ce7a7dfaec..efdb281763 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -261,40 +261,65 @@ func prepareOpenAIWSHTTPBridgeBody(account *Account, payload []byte) ([]byte, er type openAIWSToolCallReplayCollector struct { items []json.RawMessage seen map[string]struct{} - allItems []json.RawMessage - allSeen map[string]struct{} + all openAIWSReplayOutput + reserve func(int) bool + disabled bool + overflow bool } func (c *openAIWSToolCallReplayCollector) AddEvent(eventType string, message []byte) { + if c.disabled || c.overflow { + return + } + forEachOpenAIWSReplayOutputItem(eventType, message, func(item gjson.Result) bool { + c.all.addItem(item) + if !c.all.overflow { + c.addItem(item) + } + c.overflow = c.overflow || c.all.overflow + if c.overflow { + c.all = openAIWSReplayOutput{} + c.items, c.seen = nil, nil + } + return !c.overflow + }) +} + +func forEachOpenAIWSReplayOutputItem(eventType string, message []byte, add func(gjson.Result) bool) { + body := openAIWSPayloadStringView(message) switch strings.TrimSpace(eventType) { case "response.output_item.done": - item := gjson.GetBytes(message, "item") - c.addAllItem(item) - c.addItem(item) + add(gjson.Get(body, "item")) case "response.completed", "response.done": - output := gjson.GetBytes(message, "response.output") - if !output.IsArray() { - return - } - for _, item := range output.Array() { - c.addAllItem(item) - c.addItem(item) + output := gjson.Get(body, "response.output") + if output.IsArray() { + output.ForEach(func(_, item gjson.Result) bool { + return add(item) + }) } } } -// Items/AllItems 返回浅拷贝头数组;正文由 collector 独立分配且此后不可变, -// 调用方按 replay 所有权不变式共享持有。 +// Items and AllItems return independent slice headers with immutable item bytes. func (c *openAIWSToolCallReplayCollector) Items() []json.RawMessage { return slices.Clone(c.items) } func (c *openAIWSToolCallReplayCollector) AllItems() []json.RawMessage { - return slices.Clone(c.allItems) + return slices.Clone(c.all.items) } -func (c *openAIWSToolCallReplayCollector) addAllItem(item gjson.Result) { - if !item.Exists() || item.Type != gjson.JSON { +// openAIWSReplayOutput collects completed output items once, even when both +// output_item.done and the terminal response carry the same item. +type openAIWSReplayOutput struct { + items []json.RawMessage + seen map[string]struct{} + overflow bool + reserve func(int) bool +} + +func (c *openAIWSReplayOutput) addItem(item gjson.Result) { + if c.overflow || !item.Exists() || item.Type != gjson.JSON { return } raw := strings.TrimSpace(item.Raw) @@ -308,14 +333,21 @@ func (c *openAIWSToolCallReplayCollector) addAllItem(item gjson.Result) { if key == "" { key = raw } - if c.allSeen == nil { - c.allSeen = make(map[string]struct{}) - } - if _, ok := c.allSeen[key]; ok { + if _, ok := c.seen[key]; ok { return } - c.allSeen[key] = struct{}{} - c.allItems = append(c.allItems, json.RawMessage(raw)) + if c.reserve != nil && !c.reserve(len(raw)+responsesWSBridgeHistoryItemOverhead+len(key)) { + c.overflow = true + c.items = nil + c.seen = nil + return + } + if c.seen == nil { + c.seen = make(map[string]struct{}) + } + // Event buffers can be reused by streaming writers. Own the item and key. + c.seen[strings.Clone(key)] = struct{}{} + c.items = append(c.items, json.RawMessage(raw)) } func (c *openAIWSToolCallReplayCollector) addItem(item gjson.Result) { @@ -336,13 +368,17 @@ func (c *openAIWSToolCallReplayCollector) addItem(item gjson.Result) { if key == "" { key = raw } - if c.seen == nil { - c.seen = make(map[string]struct{}) - } if _, ok := c.seen[key]; ok { return } - c.seen[key] = struct{}{} + if c.reserve != nil && !c.reserve(len(raw)+responsesWSBridgeHistoryItemOverhead+len(key)) { + c.overflow = true + return + } + if c.seen == nil { + c.seen = make(map[string]struct{}) + } + c.seen[strings.Clone(key)] = struct{}{} c.items = append(c.items, json.RawMessage(raw)) } @@ -429,6 +465,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( imageInputSize string, grokCacheIdentity string, turn int, + replayCollector *openAIWSToolCallReplayCollector, writeClientMessage func([]byte) error, ) (*OpenAIForwardResult, error) { if s == nil { @@ -659,7 +696,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( eventCount := 0 tokenEventCount := 0 terminalEventCount := 0 - replayCollector := &openAIWSToolCallReplayCollector{} + if replayCollector == nil { + replayCollector = &openAIWSToolCallReplayCollector{} + } firstEventType := "" lastEventType := "" upstreamTerminalEvent := "" diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go new file mode 100644 index 0000000000..23b791254e --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -0,0 +1,149 @@ +package service + +import ( + "bytes" + "encoding/json" + "errors" + "sync/atomic" + + coderws "github.com/coder/websocket" + "github.com/tidwall/gjson" +) + +const ( + ResponsesWSBridgeHistoryLimit = 64 << 20 + responsesWSBridgeProcessHistoryLimit = 512 << 20 + // Allow for a RawMessage slice entry, collection capacity and dedup bookkeeping. + responsesWSBridgeHistoryItemOverhead = 64 +) + +var ErrResponsesWSBridgeHistoryLimit = errors.New("responses websocket bridge replay history unavailable") + +func NewResponsesWSBridgeHistoryCloseError() error { + return NewOpenAIWSClientCloseError(coderws.StatusTryAgainLater, + "bridge replay history unavailable; reconnect and send full input", ErrResponsesWSBridgeHistoryLimit) +} + +type responsesWSBridgeProcessHistory struct { + bytes atomic.Int64 + overflows atomic.Uint64 +} + +var sharedResponsesWSBridgeHistory responsesWSBridgeProcessHistory + +// ResponsesWSBridgeHistory accounts for replay history on one client connection. +// Callers on a connection must serialize access. Reservations on other +// connections may run concurrently. +type ResponsesWSBridgeHistory struct { + bytes int +} + +// TryReserve accounts for additional retained replay bytes before copying them. +func (h *ResponsesWSBridgeHistory) TryReserve(size int) bool { + if size > ResponsesWSBridgeHistoryLimit-h.bytes { + return false + } + for { + current := sharedResponsesWSBridgeHistory.bytes.Load() + if int64(size) > responsesWSBridgeProcessHistoryLimit-current { + return false + } + if sharedResponsesWSBridgeHistory.bytes.CompareAndSwap(current, current+int64(size)) { + h.bytes += size + return true + } + } +} + +// Release returns bytes previously reserved by the caller. +func (h *ResponsesWSBridgeHistory) Release(size int) { + h.bytes -= size + sharedResponsesWSBridgeHistory.bytes.Add(-int64(size)) +} + +func (h *ResponsesWSBridgeHistory) LogSize(path string) { + logOpenAIWSModeDebug("bridge_history_bytes path=%s connection_bytes=%d process_bytes=%d", + path, h.bytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} + +// LogReservationFailure records an unsuccessful reservation after any eviction attempts. +func (h *ResponsesWSBridgeHistory) LogReservationFailure(path string, size int) { + reason := "process" + if size > ResponsesWSBridgeHistoryLimit-h.bytes { + reason = "connection" + } + h.LogLimit(path, reason) +} + +func (h *ResponsesWSBridgeHistory) LogLimit(path, reason string) { + total := sharedResponsesWSBridgeHistory.overflows.Add(1) + logOpenAIWSModeWarn("bridge_history_limit path=%s reason=%s connection_bytes=%d process_bytes=%d overflows_total=%d", + path, reason, h.bytes, sharedResponsesWSBridgeHistory.bytes.Load(), total) +} + +// ResponsesWSBridgeReplayInputFits cheaply bounds the size and number of items +// before allocating a replay slice. The normalized items are measured again +// after parsing, since string inputs can grow during conversion. +func ResponsesWSBridgeReplayInputFits(payload []byte, limit int) bool { + input := gjson.Get(openAIWSPayloadStringView(payload), "input") + if !input.IsArray() { + return !input.Exists() || len(input.Raw)+responsesWSBridgeHistoryItemOverhead <= limit + } + remaining := limit - len(input.Raw) + input.ForEach(func(_, _ gjson.Result) bool { + remaining -= responsesWSBridgeHistoryItemOverhead + return remaining >= 0 + }) + return remaining >= 0 +} + +func ResponsesWSBridgeReplayItemsBytes(items []json.RawMessage) int { + size := len(items) * responsesWSBridgeHistoryItemOverhead + for _, item := range items { + size += len(item) + } + return size +} + +// CloneResponsesWSBridgeReplayItems gives replay items their own backing bytes +// so retaining an item cannot keep an entire client frame alive. +func CloneResponsesWSBridgeReplayItems(items []json.RawMessage) []json.RawMessage { + if len(items) == 0 { + return nil + } + out := make([]json.RawMessage, len(items)) + for i, item := range items { + out[i] = bytes.Clone(item) + } + return out +} + +const openAIWSLegacyBridgeHistoryPath = "openai_grok" + +type openAIWSLegacyBridgeHistory struct { + budget *ResponsesWSBridgeHistory + held int +} + +func (h *openAIWSLegacyBridgeHistory) reserve(size int) bool { + if !h.budget.TryReserve(size) { + h.budget.LogReservationFailure(openAIWSLegacyBridgeHistoryPath, size) + return false + } + h.held += size + return true +} + +func (h *openAIWSLegacyBridgeHistory) resize(size int) bool { + if size > h.held { + return h.reserve(size - h.held) + } + h.budget.Release(h.held - size) + h.held = size + return true +} + +func (h *openAIWSLegacyBridgeHistory) close() { + h.resize(0) + h.budget.LogSize(openAIWSLegacyBridgeHistoryPath) +} diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go new file mode 100644 index 0000000000..5019751ff9 --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -0,0 +1,164 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestResponsesWSBridgeHistoryConcurrentProcessBudget(t *testing.T) { + const connections = 12 + reserved := make(chan *ResponsesWSBridgeHistory, connections) + var workers sync.WaitGroup + for range connections { + workers.Go(func() { + history := &ResponsesWSBridgeHistory{} + if history.TryReserve(ResponsesWSBridgeHistoryLimit) { + reserved <- history + } + }) + } + workers.Wait() + close(reserved) + require.Len(t, reserved, responsesWSBridgeProcessHistoryLimit/ResponsesWSBridgeHistoryLimit) + for history := range reserved { + history.Release(ResponsesWSBridgeHistoryLimit) + } + require.Zero(t, sharedResponsesWSBridgeHistory.bytes.Load()) + + probe := &ResponsesWSBridgeHistory{} + require.False(t, probe.TryReserve(ResponsesWSBridgeHistoryLimit+1)) + require.True(t, probe.TryReserve(ResponsesWSBridgeHistoryLimit)) + probe.Release(ResponsesWSBridgeHistoryLimit) +} + +func TestOpenAIWSHTTPBridgeHistoryOverLimitReconnectsWithFullInput(t *testing.T) { + for _, scope := range []string{"connection", "process"} { + t.Run(scope, func(t *testing.T) { + const free = 300 + firstConnectionHistory := &ResponsesWSBridgeHistory{} + switch scope { + case "connection": + require.True(t, firstConnectionHistory.TryReserve(ResponsesWSBridgeHistoryLimit-free)) + t.Cleanup(func() { firstConnectionHistory.Release(ResponsesWSBridgeHistoryLimit - free) }) + case "process": + for i := 0; i < responsesWSBridgeProcessHistoryLimit/ResponsesWSBridgeHistoryLimit; i++ { + history := &ResponsesWSBridgeHistory{} + size := ResponsesWSBridgeHistoryLimit + if i == 0 { + size -= free + } + require.True(t, history.TryReserve(size)) + t.Cleanup(func() { history.Release(size) }) + } + } + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + overflows := sharedResponsesWSBridgeHistory.overflows.Load() + + response := func(id, output string) *http.Response { + sse := fmt.Sprintf("data: {\"type\":\"response.completed\",\"response\":{\"id\":%q,\"output\":%s}}\n\n", id, output) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + } + } + // A plain assistant message belongs only to the account-failover + // sequence. Its size alone must invalidate the replay snapshot. + output := fmt.Sprintf(`[{"type":"message","id":"assistant","role":"assistant","content":[{"type":"output_text","text":%q}]}]`, + strings.Repeat("x", free)) + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + response("resp_first", output), + response("resp_retried", "[]"), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 71, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + + done := make(chan error, 2) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = conn.CloseNow() }() + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + hooks := &OpenAIWSIngressHooks{BridgeHistory: firstConnectionHistory} + if r.URL.Path == "/retry" { + hooks.BridgeHistory = nil + } + err = svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token", firstMessage, hooks) + var closeErr *OpenAIWSClientCloseError + if errors.As(err, &closeErr) { + _ = conn.Close(closeErr.StatusCode(), closeErr.Reason()) + } + done <- err + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + dial := func(path string) *coderws.Conn { + conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+path, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.CloseNow() }) + return conn + } + send := func(conn *coderws.Conn, frame string) { + require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(frame))) + } + readCompleted := func(conn *coderws.Conn, id string) { + _, frame, err := conn.Read(ctx) + require.NoError(t, err) + require.Equal(t, "response.completed", gjson.GetBytes(frame, "type").String()) + require.Equal(t, id, gjson.GetBytes(frame, "response.id").String()) + } + + first := dial("/") + send(first, `{"type":"response.create","model":"grok","input":"first"}`) + readCompleted(first, "resp_first") + send(first, `{"type":"response.create","model":"grok","previous_response_id":"resp_first","input":"second"}`) + _, _, err := first.Read(ctx) + require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err)) + require.ErrorIs(t, <-done, ErrResponsesWSBridgeHistoryLimit) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) + require.Equal(t, overflows+1, sharedResponsesWSBridgeHistory.overflows.Load()) + require.Len(t, upstream.requests, 1) + + retry := dial("/retry") + send(retry, `{"type":"response.create","model":"grok","input":[{"type":"message","role":"user","content":"first"},{"type":"message","role":"user","content":"second"}]}`) + readCompleted(retry, "resp_retried") + require.NoError(t, retry.Close(coderws.StatusNormalClosure, "")) + require.NoError(t, <-done) + require.Len(t, upstream.requests, 2) + require.Len(t, gjson.GetBytes(upstream.bodies[1], "input").Array(), 2) + require.False(t, gjson.GetBytes(upstream.bodies[1], "previous_response_id").Exists()) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) + }) + } +} diff --git a/backend/internal/service/openai_ws_http_bridge_resume_test.go b/backend/internal/service/openai_ws_http_bridge_resume_test.go index 1468892bbe..b18ac294e4 100644 --- a/backend/internal/service/openai_ws_http_bridge_resume_test.go +++ b/backend/internal/service/openai_ws_http_bridge_resume_test.go @@ -50,6 +50,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnLaterTurn429FailsOverBeforeClientWrite(t *te result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "gpt-5.6-sol", "", "", "", "", 281, + nil, func([]byte) error { writes++ return nil @@ -85,6 +86,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnLaterTurnDoesNotFailOverAfterDownstreamOutpu result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 281, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index dfa42702e5..4515b8c58f 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -90,6 +90,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_KeepsOutboundAndObservedServiceTiersSeparat result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5.5", "", "", "", "", 1, + nil, func([]byte) error { return nil }, ) @@ -128,6 +129,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_NormalizesFastWithoutLosingObservedDefault( result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5.5", "", "", "", "", 1, + nil, func([]byte) error { return nil }, ) @@ -177,6 +179,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnAPIKeyAdaptsClientTools(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5", "", "", "", "", 2, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -247,6 +250,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnAPIKeyRestoresClientToolsInResponseDone(t *t result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -311,6 +315,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnGrokPromotesDiscoveryAndRestoresNamespaceSSE result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok-4.5", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -360,7 +365,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnGrokInheritsToolSearchAndPromotesFollowupDis first := []byte(`{"type":"response.create","model":"grok-4.5","stream":true,"tools":[{"type":"tool_search"}],"input":"discover tools"}`) _, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", first, len(first), - "grok-4.5", "", "", "", "grok-ws-cache", 1, func([]byte) error { return nil }, + "grok-4.5", "", "", "", "grok-ws-cache", 1, nil, func([]byte) error { return nil }, ) require.NoError(t, err) @@ -374,6 +379,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnGrokInheritsToolSearchAndPromotesFollowupDis _, err = svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", second, len(second), "grok-4.5", "", "", "", "grok-ws-cache", 2, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -794,6 +800,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnTransportErrorFailoverSafety(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", tt.turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -852,6 +859,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnHTTPStatusFailoverSafety(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", tt.turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -902,6 +910,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnRetriesRejectedFieldBeforeClientOutput(t *te result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -941,6 +950,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnSSEErrorFailoverSafety(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -999,6 +1009,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnRewritesCapacityShedCodeForClient(t *testing _, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", tt.turn, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -1038,7 +1049,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorUsesAuthoritativeFailed(t *testing. payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) @@ -1110,7 +1121,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnMarksCyberPolicyForFailureShapes(t *testing. result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), - "gpt-5", "", "", "", "", 1, func([]byte) error { return nil }, + "gpt-5", "", "", "", "", 1, nil, func([]byte) error { return nil }, ) require.Equal(t, tt.wantResult, result != nil) @@ -1139,7 +1150,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorEOFSynthesizesFailed(t *testing.T) payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) @@ -1172,7 +1183,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnBareErrorFollowedByCompletedUsesCompleted(t payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) var writes [][]byte - result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil }) @@ -1238,6 +1249,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnStagesMetadataAndRelaysKeepaliveBeforeCapaci result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) if gjson.GetBytes(message, "type").String() == "keepalive" { @@ -1289,6 +1301,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnDoesNotReplayCapacityAfterSemanticOutput(t * result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -1345,6 +1358,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnKeepaliveWriteFailure(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return tc.writeErr @@ -1413,6 +1427,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnDisconnectedBeforeOutputDoesNotFailOver(t *t result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) if len(writes) == 1 { @@ -1480,6 +1495,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnRequiresTerminalEvent(t *testing.T) { result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 1, + nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil @@ -1579,6 +1595,7 @@ func TestOpenAIWSHTTPBridgeRelaysSSEFramesAsWebSocketMessages(t *testing.T) { "", "", 1, + nil, writeClient, ) resultCh <- bridgeResult{result: result, err: bridgeErr} @@ -1663,6 +1680,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnForGrokDefaultsEmptyModelTo45(t *testing.T) result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "", "", "", "", "", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -1723,6 +1741,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnPromotesCodexAdditionalToolsForMixedCache(t result, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "access-token", payload, len(payload), "grok", "", "", "", "isolated-ws-cache-id", 1, + nil, func(message []byte) error { events = append(events, append([]byte(nil), message...)) return nil @@ -2386,6 +2405,7 @@ func TestProxyOpenAIWSHTTPBridgeTurn_StagesCodexFingerprint(t *testing.T) { _, err := svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "test-token", payload, len(payload), "gpt-5.5", "", "", "", "", 1, + nil, func([]byte) error { return nil }, ) require.NoError(t, err) From f84d1d3eb2e2cc26ec10d88b5e911d3fc504c715 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 09:47:40 +0800 Subject: [PATCH 30/45] 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 31/45] 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 32/45] 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 { From 8aa5c2a4ba3627072f4b866d4dcabfa2d1588f2e Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:42:27 +0800 Subject: [PATCH 33/45] =?UTF-8?q?fix:=20omit=20Retry-After=20hint=20when?= =?UTF-8?q?=20any=20supporting=20account=20is=20not=20in=20persisted=20coo?= =?UTF-8?q?ldown=EF=BC=88audit=20follow-up=20for=20#9197=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/gateway_model_availability.go | 9 +++ .../gateway_model_availability_test.go | 65 +++++++++++++++++++ .../openai_gateway_model_availability.go | 9 +++ 3 files changed, 83 insertions(+) diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go index fbe727c886..71c36d6dc4 100644 --- a/backend/internal/service/gateway_model_availability.go +++ b/backend/internal/service/gateway_model_availability.go @@ -109,6 +109,10 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( diag := ModelAvailabilityDiagnosis{} var earliestRecovery time.Duration + // A supporting account with no persisted cooldown is waiting on a runtime + // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so + // the pool-level hint must be omitted rather than inflated by a cooling peer. + hasUncooledCandidate := false for i := range accounts { if useMixed && accounts[i].Platform == PlatformAntigravity && !accounts[i].IsMixedSchedulingEnabled() { continue @@ -120,9 +124,14 @@ func (s *GatewayService) DiagnoseModelAvailabilityForPlatform( if earliestRecovery == 0 || remaining < earliestRecovery { earliestRecovery = remaining } + } else { + hasUncooledCandidate = true } } } + if hasUncooledCandidate { + earliestRecovery = 0 + } diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) return diag } diff --git a/backend/internal/service/gateway_model_availability_test.go b/backend/internal/service/gateway_model_availability_test.go index ed32f620e8..bf5ba12fde 100644 --- a/backend/internal/service/gateway_model_availability_test.go +++ b/backend/internal/service/gateway_model_availability_test.go @@ -249,3 +249,68 @@ func TestDiagnoseModelAvailabilityForPlatform_WrongPlatformFiltersOut(t *testing require.False(t, diag.HasAccountsInPool, "OpenAI route must not see Anthropic accounts in pool") require.False(t, diag.HasModelSupport) } + +func retryAfterTestAccount(id int64, platform string, groupID int64, cooldown time.Duration) Account { + acc := Account{ + ID: id, + Platform: platform, + Status: StatusActive, + Schedulable: true, + AccountGroups: []AccountGroup{{GroupID: groupID}}, + Credentials: map[string]any{ + "model_mapping": map[string]any{"claude-opus-4-8": "claude-opus-4-8"}, + }, + } + if cooldown > 0 { + until := time.Now().Add(cooldown) + acc.RateLimitResetAt = &until + } + return acc +} + +func TestDiagnoseModelAvailability_RetryAfterHint(t *testing.T) { + groupID := int64(44) + tests := []struct { + name string + cooldowns []time.Duration + want func(t *testing.T, seconds int) + }{ + { + name: "mixed pool with runtime-filtered account omits hint", + cooldowns: []time.Duration{0, 2 * time.Hour}, + want: func(t *testing.T, s int) { require.Equal(t, 0, s) }, + }, + { + name: "all cooling picks earliest", + cooldowns: []time.Duration{90 * time.Second, 2 * time.Hour}, + want: func(t *testing.T, s int) { require.InDelta(t, 90, s, 2) }, + }, + { + name: "all cooling is capped at the default maximum", + cooldowns: []time.Duration{2 * time.Hour, 3 * time.Hour}, + want: func(t *testing.T, s int) { require.Equal(t, DownstreamRetryAfterMaxSeconds(nil), s) }, + }, + } + for _, tt := range tests { + t.Run("anthropic/"+tt.name, func(t *testing.T) { + repo := &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{}} + for i, c := range tt.cooldowns { + repo.accounts = append(repo.accounts, retryAfterTestAccount(int64(i+1), PlatformAnthropic, groupID, c)) + } + svc := &GatewayService{accountRepo: repo, cfg: testConfig(), schedulerSnapshot: &SchedulerSnapshotService{}} + diag := svc.DiagnoseModelAvailabilityForPlatform(context.Background(), &groupID, "claude-opus-4-8", PlatformAnthropic) + require.True(t, diag.HasModelSupport) + tt.want(t, diag.RetryAfterSeconds) + }) + t.Run("openai/"+tt.name, func(t *testing.T) { + repo := &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{}} + for i, c := range tt.cooldowns { + repo.accounts = append(repo.accounts, retryAfterTestAccount(int64(i+1), PlatformOpenAI, groupID, c)) + } + svc := &OpenAIGatewayService{accountRepo: repo, cfg: testConfig(), schedulerSnapshot: &SchedulerSnapshotService{}} + diag := svc.DiagnoseModelAvailabilityForPlatform(context.Background(), &groupID, "claude-opus-4-8", PlatformOpenAI) + require.True(t, diag.HasModelSupport) + tt.want(t, diag.RetryAfterSeconds) + }) + } +} diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go index b253ef1764..eec311d4af 100644 --- a/backend/internal/service/openai_gateway_model_availability.go +++ b/backend/internal/service/openai_gateway_model_availability.go @@ -56,6 +56,10 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( diag := ModelAvailabilityDiagnosis{} var earliestRecovery time.Duration + // A supporting account with no persisted cooldown is waiting on a runtime + // filter (quota, RPM, window cost, ...) whose recovery time is unknown, so + // the pool-level hint must be omitted rather than inflated by a cooling peer. + hasUncooledCandidate := false for i := range accounts { diag.HasAccountsInPool = true if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) { @@ -71,9 +75,14 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( if earliestRecovery == 0 || remaining < earliestRecovery { earliestRecovery = remaining } + } else { + hasUncooledCandidate = true } } } + if hasUncooledCandidate { + earliestRecovery = 0 + } diag.RetryAfterSeconds = ceilRetryAfterSeconds(earliestRecovery, DownstreamRetryAfterMaxSeconds(s.cfg)) return diag } From 385e07ca8568890aa5d27caa8558de62a8b8c59d Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:44:07 +0800 Subject: [PATCH 34/45] =?UTF-8?q?fix:=20shorten=20Codex=20models=20ETag=20?= =?UTF-8?q?mapping=20TTL=20and=20clear=20it=20for=20upstream-less=20manife?= =?UTF-8?q?sts=EF=BC=88audit=20follow-up=20for=20#9199=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_codex_models_etag.go | 33 ++++++++++++- .../service/openai_codex_models_etag_test.go | 49 +++++++++++++++++++ .../openai_codex_models_etag_ws_test.go | 19 +++++++ 3 files changed, 99 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_codex_models_etag.go b/backend/internal/service/openai_codex_models_etag.go index 550bdc2fb5..a068099398 100644 --- a/backend/internal/service/openai_codex_models_etag.go +++ b/backend/internal/service/openai_codex_models_etag.go @@ -29,7 +29,13 @@ const ( codexModelsETagHeader = "x-models-etag" codexModelsETagRegistryMaxEntries = 4096 - codexModelsETagRegistryTTL = 24 * time.Hour + // The Codex client caches the catalog for 300s and only renews that cache + // when the ETag is unchanged. The served manifest also depends on group + // configuration and schedulable accounts, none of which change the upstream + // ETag, so a recorded mapping can go stale. Ten minutes keeps the per-turn + // full download away (at most one refresh per window) while bounding how + // long a stale mapping can hide a changed catalog. + codexModelsETagRegistryTTL = 10 * time.Minute ) type codexModelsETagKey struct { @@ -92,6 +98,20 @@ func (r *codexModelsETagRegistry) record(groupID int64, upstreamETags []string, r.evictLocked(now) } +// clearGroup drops every mapping of a group. +func (r *codexModelsETagRegistry) clearGroup(groupID int64) { + if r == nil || groupID <= 0 { + return + } + r.mu.Lock() + defer r.mu.Unlock() + for key := range r.entries { + if key.groupID == groupID { + delete(r.entries, key) + } + } +} + func (r *codexModelsETagRegistry) lookup(groupID int64, upstream string, now time.Time) (string, bool) { upstream = normalizeCodexModelsETag(upstream) if r == nil || groupID <= 0 || upstream == "" { @@ -154,11 +174,20 @@ func (r *OpenAIModelsResponse) upstreamCatalogETags() []string { // was served with for every upstream catalog ETag it was derived from. The // mapping lets codex.response.metadata events carry an ETag the client // recognizes. Verbatim manifests are recorded too, so their ETag is kept. +// A manifest without any upstream ETag (for example one built from group +// configuration alone) invalidates the group's earlier mappings: they describe +// a catalog the group no longer serves, so later metadata events lose the +// header instead of reporting a stale ETag. func (s *OpenAIGatewayService) RecordCodexModelsManifestETag(groupID int64, manifest *OpenAIModelsResponse) { if manifest == nil { return } - codexModelsETags.record(groupID, manifest.upstreamCatalogETags(), manifest.ETag, time.Now()) + upstreamETags := manifest.upstreamCatalogETags() + if len(upstreamETags) == 0 { + codexModelsETags.clearGroup(groupID) + return + } + codexModelsETags.record(groupID, upstreamETags, manifest.ETag, time.Now()) } // rewriteCodexResponseMetadataModelsETag translates the x-models-etag header of diff --git a/backend/internal/service/openai_codex_models_etag_test.go b/backend/internal/service/openai_codex_models_etag_test.go index 1a918a2125..24d507647f 100644 --- a/backend/internal/service/openai_codex_models_etag_test.go +++ b/backend/internal/service/openai_codex_models_etag_test.go @@ -158,3 +158,52 @@ func TestRecordCodexModelsManifestETagUsesEveryUpstreamSource(t *testing.T) { local := &OpenAIModelsResponse{ETag: `W/"local-only"`} require.Empty(t, local.upstreamCatalogETags()) } + +func TestCodexModelsETagRegistryTTLIsShort(t *testing.T) { + t.Parallel() + + require.Equal(t, 10*time.Minute, codexModelsETagRegistryTTL) + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(16, codexModelsETagRegistryTTL) + registry.record(7, []string{`"u"`}, `"served"`, now) + _, ok := registry.lookup(7, `"u"`, now.Add(9*time.Minute)) + require.True(t, ok) + _, ok = registry.lookup(7, `"u"`, now.Add(11*time.Minute)) + require.False(t, ok, "mappings past the TTL must not be used") +} + +func TestCodexModelsETagRegistryClearGroup(t *testing.T) { + t.Parallel() + + now := time.Unix(1_800_000_000, 0) + registry := newCodexModelsETagRegistry(16, time.Hour) + registry.record(7, []string{`"a"`, `"b"`}, `"served-7"`, now) + registry.record(8, []string{`"a"`}, `"served-8"`, now) + registry.clearGroup(7) + registry.clearGroup(0) + (*codexModelsETagRegistry)(nil).clearGroup(7) + + _, ok := registry.lookup(7, `"a"`, now) + require.False(t, ok) + _, ok = registry.lookup(7, `"b"`, now) + require.False(t, ok) + served, ok := registry.lookup(8, `"a"`, now) + require.True(t, ok) + require.Equal(t, `"served-8"`, served) +} + +func TestRecordCodexModelsManifestETagWithoutUpstreamClearsGroup(t *testing.T) { + t.Parallel() + + const groupID int64 = 77_002 + svc := &OpenAIGatewayService{} + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ETag: `W/"scheduled"`, upstreamETag: `W/"up"`}) + _, ok := codexModelsETags.lookup(groupID, `W/"up"`, time.Now()) + require.True(t, ok) + + // Group switched to the configuration branch: no upstream ETag. + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ETag: `W/"configured"`}) + _, ok = codexModelsETags.lookup(groupID, `W/"up"`, time.Now()) + require.False(t, ok, "stale mapping must be dropped") +} diff --git a/backend/internal/service/openai_codex_models_etag_ws_test.go b/backend/internal/service/openai_codex_models_etag_ws_test.go index c1eaecaec9..c2d560ea11 100644 --- a/backend/internal/service/openai_codex_models_etag_ws_test.go +++ b/backend/internal/service/openai_codex_models_etag_ws_test.go @@ -177,3 +177,22 @@ func TestCodexResponseMetadataUnknownModelsETagIsRemovedOverWebSocket(t *testing }) } } + +func TestCodexResponseMetadataETagNotRewrittenAfterConfiguredManifestOverWebSocket(t *testing.T) { + const groupID int64 = 96_031 + svc := &OpenAIGatewayService{} + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ + ETag: `W/"scheduled-manifest"`, + upstreamETag: `W/"upstream-catalog"`, + }) + // The group is now served from its configuration: no upstream ETag. + svc.RecordCodexModelsManifestETag(groupID, &OpenAIModelsResponse{ETag: `W/"configured-manifest"`}) + + events := runCodexMetadataWSTurn(t, false, groupID, [][]byte{ + []byte(`{"type":"codex.response.metadata","headers":{"x-models-etag":"W/\"upstream-catalog\"","x-codex-other":"kept"}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_metadata_configured","model":"gpt-5.1","usage":{"input_tokens":1,"output_tokens":1}}}`), + }) + metadata := codexMetadataEvent(t, events) + require.False(t, gjson.GetBytes(metadata, "headers.x-models-etag").Exists()) + require.Equal(t, "kept", gjson.GetBytes(metadata, "headers.x-codex-other").String()) +} From 0dba88681bd983a64913e2452545743194d28f34 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:45:21 +0800 Subject: [PATCH 35/45] =?UTF-8?q?fix:=20hide=20create-account=20scheduling?= =?UTF-8?q?=20threshold=20unless=20submit=20writes=20it=20and=20reset=20it?= =?UTF-8?q?=20on=20close=EF=BC=88audit=20follow-up=20for=20#9135=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/account/CreateAccountModal.vue | 20 +++++++- .../__tests__/CreateAccountModal.spec.ts | 47 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 8478f2056c..f5ba3d6df8 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -4519,8 +4519,22 @@ const extraMultiProtocolPlatforms = computed(() => const ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY = 'account_scheduling_threshold' const createSchedulingThresholdOverrideEnabled = ref(false) const createSchedulingThresholdOverrideValue = ref(100) -const supportsCreateSchedulingThresholdOverride = computed(() => - (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) +// handleSubmit 中走到通用 apikey 创建分支的条件:其余分支(OAuth 流程、Bedrock、 +// Antigravity upstream、service_account)都会先行返回,不会写入阈值。 +const submitsViaGenericApiKeyPath = computed( + () => + !isOAuthFlow.value && + !(form.platform === 'anthropic' && accountCategory.value === 'bedrock') && + !(form.platform === 'antigravity' && antigravityAccountType.value === 'upstream') && + !( + (form.platform === 'gemini' || form.platform === 'anthropic') && + accountCategory.value === 'service_account' + ) +) +const supportsCreateSchedulingThresholdOverride = computed( + () => + (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) && + submitsViaGenericApiKeyPath.value ) const genericAccountModes = computed(() => providerAccountModes(form.platform)) // 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。 @@ -5748,6 +5762,8 @@ const resetForm = () => { upstreamRequestIdHeader.value = '' upstreamBillingAutoProbeEnabled.value = true upstreamGroupSyncEnabled.value = false + createSchedulingThresholdOverrideEnabled.value = false + createSchedulingThresholdOverrideValue.value = 100 editQuotaLimit.value = null editQuotaDailyLimit.value = null editQuotaWeeklyLimit.value = null diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index 0e30886822..9360bf518d 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -530,6 +530,53 @@ describe('CreateAccountModal OpenAI long-context billing', () => { expect(probeUpstreamBillingMock).not.toHaveBeenCalled() }) + describe('account scheduling threshold override', () => { + const toggleSelector = '[data-testid="create-account-scheduling-threshold"]' + const enabledSelector = '[data-testid="create-account-scheduling-threshold-enabled"]' + const valueSelector = '[data-testid="create-account-scheduling-threshold-value"]' + + it('is hidden for OAuth-based creation, which never writes the threshold', async () => { + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + expect(wrapper.find(toggleSelector).exists()).toBe(false) + + await selectButtonByText(wrapper, 'API Key') + expect(wrapper.find(toggleSelector).exists()).toBe(true) + }) + + it('writes the threshold into credentials for API key accounts', async () => { + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + await wrapper.get(enabledSelector).setValue(true) + await wrapper.get(valueSelector).setValue(80) + await wrapper.get('form#create-account-form input[type="text"]').setValue('threshold account') + await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key') + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + expect(createAccountMock.mock.calls[0]?.[0]?.credentials?.account_scheduling_threshold).toBe(80) + }) + + it('does not carry the previous value over to the next created account', async () => { + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + await wrapper.get(enabledSelector).setValue(true) + await wrapper.get(valueSelector).setValue(80) + + await wrapper.setProps({ show: false }) + await wrapper.setProps({ show: true }) + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + + expect((wrapper.get(enabledSelector).element as HTMLInputElement).checked).toBe(false) + await wrapper.get(enabledSelector).setValue(true) + expect((wrapper.get(valueSelector).element as HTMLInputElement).value).toBe('100') + }) + }) + it('submits OpenCode Zen default protocol rules with adaptive endpoints', async () => { const wrapper = mountModal() await selectButtonByText(wrapper, 'OpenCode') From d6f167622dd707bd4c4427ac2541b94e2d06652c Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:47:41 +0800 Subject: [PATCH 36/45] =?UTF-8?q?fix:=20=E5=9C=A8=20WS=20ingress/=E6=A1=A5?= =?UTF-8?q?=E6=8E=A5/passthrough/HTTP+WS=E4=B8=8A=E6=B8=B8=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E5=89=A5=E7=A6=BB=E5=AE=89=E5=85=A8=E5=AE=A1=E6=9F=A5?= =?UTF-8?q?=E8=AF=A6=E6=83=85=EF=BC=88audit=20follow-up=20for=20#9147?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...enai_gateway_failed_event_sanitize_test.go | 46 +++ .../openai_gateway_response_handling.go | 59 +++- ...enai_ws_failed_event_safety_review_test.go | 309 ++++++++++++++++++ .../service/openai_ws_forwarder_ingress.go | 3 + .../service/openai_ws_forwarder_v2.go | 5 +- .../internal/service/openai_ws_http_bridge.go | 3 + .../openai_ws_v2_passthrough_adapter.go | 3 + 7 files changed, 415 insertions(+), 13 deletions(-) create mode 100644 backend/internal/service/openai_ws_failed_event_safety_review_test.go diff --git a/backend/internal/service/openai_gateway_failed_event_sanitize_test.go b/backend/internal/service/openai_gateway_failed_event_sanitize_test.go index 31f8fb55a1..f5651ba7da 100644 --- a/backend/internal/service/openai_gateway_failed_event_sanitize_test.go +++ b/backend/internal/service/openai_gateway_failed_event_sanitize_test.go @@ -3,6 +3,7 @@ package service import ( + "strings" "testing" "github.com/stretchr/testify/require" @@ -38,3 +39,48 @@ func TestSanitizeOpenAIFailedEventWithoutReviewDetailsIsUnchanged(t *testing.T) require.False(t, changed) require.JSONEq(t, string(payload), string(out)) } + +const misalignmentFailedFrame = `{"type":"response.failed","sequence_number":3,"response":{"id":"resp_1","status":"failed","error":{"type":"invalid_request_error","code":"misalignment_policy_violation","message":"blocked","misalignment":{"detailed_explanation":"another user's private project summary"}}}}` +const misalignmentErrorFrame = `{"type":"error","error":{"type":"invalid_request_error","code":"misalignment_policy_violation","message":"blocked","misalignment":{"detailed_explanation":"another user's private project summary"}}}` + +func TestStripOpenAISafetyReviewDetailsForClient(t *testing.T) { + for _, tt := range []struct{ name, in, codePath string }{ + {"response_failed", misalignmentFailedFrame, "response.error.code"}, + {"error", misalignmentErrorFrame, "error.code"}, + } { + t.Run(tt.name, func(t *testing.T) { + out, ok := stripOpenAISafetyReviewDetailsForClient([]byte(tt.in)) + require.True(t, ok) + require.NotContains(t, string(out), "misalignment\":") + require.NotContains(t, string(out), "private project summary") + require.Equal(t, "misalignment_policy_violation", gjson.GetBytes(out, tt.codePath).String()) + require.Equal(t, "blocked", gjson.GetBytes(out, strings.Replace(tt.codePath, "code", "message", 1)).String()) + }) + } + + // Frames without the field, or of other event types, stay byte-identical. + for _, in := range []string{ + `{"type":"response.failed","response":{"status":"failed","error":{"code":"x","message":"m"}}}`, + `{"type":"response.output_text.delta","delta":"misalignment","error":{"misalignment":{"a":1}}}`, + `not json misalignment`, + } { + out, ok := stripOpenAISafetyReviewDetailsForClient([]byte(in)) + require.True(t, ok) + require.Equal(t, in, string(out)) + } +} + +func TestStripOpenAISafetyReviewDetailsFromFailedResponseForClient(t *testing.T) { + failed := `{"id":"resp_1","status":"failed","error":{"code":"c","message":"m","misalignment":{"x":1}}}` + out := stripOpenAISafetyReviewDetailsFromFailedResponseForClient([]byte(failed)) + require.False(t, gjson.GetBytes(out, "error.misalignment").Exists()) + require.Equal(t, "c", gjson.GetBytes(out, "error.code").String()) + require.Equal(t, "m", gjson.GetBytes(out, "error.message").String()) + + for _, in := range []string{ + `{"id":"resp_1","status":"failed","error":{"code":"c","message":"m"}}`, + `{"id":"resp_1","status":"completed","output":[{"text":"misalignment"}],"error":{"misalignment":1}}`, + } { + require.Equal(t, in, string(stripOpenAISafetyReviewDetailsFromFailedResponseForClient([]byte(in)))) + } +} diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 3555dd2887..a0ed1c00ee 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -2009,6 +2009,49 @@ func buildOpenAIResponseFailedSSE(responseID, model string, createdAt int64, sou return "event: response.failed\ndata: " + string(payload) + "\n\n" } +var openAISafetyReviewDetailPaths = []string{"response.error.misalignment", "error.misalignment"} + +// stripOpenAISafetyReviewDetailsForClient removes the upstream safety-review body +// from a client-visible response.failed / error event. A shared OAuth account can +// return an explanation that belongs to another downstream user's session; the +// stable status, code and message are kept. Other payloads are returned as-is +// without allocation. The bool is false only when the delete itself failed. +func stripOpenAISafetyReviewDetailsForClient(payload []byte) ([]byte, bool) { + if !bytes.Contains(payload, []byte("misalignment")) { + return payload, true + } + if t := gjson.GetBytes(payload, "type").String(); t != "response.failed" && t != "error" { + return payload, true + } + updated := payload + for _, path := range openAISafetyReviewDetailPaths { + if !gjson.GetBytes(updated, path).Exists() { + continue + } + next, err := sjson.DeleteBytes(updated, path) + if err != nil { + return payload, false + } + updated = next + } + return updated, true +} + +// stripOpenAISafetyReviewDetailsFromFailedResponseForClient is the non-streaming +// counterpart: payload is a bare Responses object, stripped only when failed. +func stripOpenAISafetyReviewDetailsFromFailedResponseForClient(payload []byte) []byte { + if !bytes.Contains(payload, []byte("misalignment")) || + gjson.GetBytes(payload, "status").String() != "failed" || + !gjson.GetBytes(payload, "error.misalignment").Exists() { + return payload + } + next, err := sjson.DeleteBytes(payload, "error.misalignment") + if err != nil { + return payload + } + return next +} + func sanitizeOpenAIResponseFailedEventForClient(payload []byte, eventType string, clientOutputStarted bool) ([]byte, bool) { eventType = strings.TrimSpace(eventType) isFailedEvent := eventType == "response.failed" @@ -2022,19 +2065,11 @@ func sanitizeOpenAIResponseFailedEventForClient(payload []byte, eventType string if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(updated); changed { updated = rewritten } - // A shared OAuth account can return a safety-review explanation that - // belongs to another downstream user's session. Keep the stable status, - // code and message, but never forward the review body. - for _, path := range []string{"response.error.misalignment", "error.misalignment"} { - if !gjson.GetBytes(updated, path).Exists() { - continue - } - next, err := sjson.DeleteBytes(updated, path) - if err != nil { - return payload, false - } - updated = next + next, ok := stripOpenAISafetyReviewDetailsForClient(updated) + if !ok { + return payload, false } + updated = next if !isFailedEvent { return updated, !bytes.Equal(updated, payload) } diff --git a/backend/internal/service/openai_ws_failed_event_safety_review_test.go b/backend/internal/service/openai_ws_failed_event_safety_review_test.go new file mode 100644 index 0000000000..4b7fde612f --- /dev/null +++ b/backend/internal/service/openai_ws_failed_event_safety_review_test.go @@ -0,0 +1,309 @@ +package service + +import ( + "context" + "io" + "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" +) + +const ( + safetyReviewFailedFrame = `{"type":"response.failed","sequence_number":3,"response":{"id":"resp_sr","status":"failed","error":{"type":"invalid_request_error","code":"workspace_suspended","message":"blocked","misalignment":{"detailed_explanation":"another user's private project summary"}}}}` + safetyReviewErrorFrame = `{"type":"error","error":{"type":"invalid_request_error","code":"workspace_suspended","message":"blocked","misalignment":{"detailed_explanation":"another user's private project summary"}}}` + cleanFailedFrame = `{"type":"response.failed","response":{"id":"resp_clean","created_at":1700000000,"status":"failed","error":{"code":"workspace_suspended","message":"blocked"}}}` +) + +func requireSafetyReviewStripped(t *testing.T, frame []byte) { + t.Helper() + require.NotContains(t, string(frame), "misalignment\"", string(frame)) + require.NotContains(t, string(frame), "private project summary") + errPath := "error" + if gjson.GetBytes(frame, "type").String() == "response.failed" { + errPath = "response.error" + } + require.Equal(t, "workspace_suspended", gjson.GetBytes(frame, errPath+".code").String()) + require.Equal(t, "blocked", gjson.GetBytes(frame, errPath+".message").String()) +} + +func TestProxyResponsesWebSocketFromClient_StripsSafetyReviewDetailsForClient(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + upstream []string + check func(t *testing.T, frames []string) + }{ + { + name: "misalignment_stripped", + upstream: []string{safetyReviewErrorFrame, safetyReviewFailedFrame}, + check: func(t *testing.T, frames []string) { + require.Len(t, frames, 2) + for _, f := range frames { + requireSafetyReviewStripped(t, []byte(f)) + } + }, + }, + { + name: "clean_frame_unchanged", + upstream: []string{cleanFailedFrame}, + check: func(t *testing.T, frames []string) { + require.Equal(t, []string{cleanFailedFrame}, frames) + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := newOpenAIWSV2TestConfig() + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = 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 + + events := make([][]byte, 0, len(tt.upstream)) + for _, e := range tt.upstream { + events = append(events, []byte(e)) + } + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(&openAIWSCaptureDialer{conn: &openAIWSCaptureConn{events: events}}) + account := Account{ + ID: 5411, Name: "openai-ingress-safety-review", Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}, + } + repo := &openAIWSIngressCapacityShedRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}} + svc := &OpenAIGatewayService{ + accountRepo: repo, rateLimitService: &RateLimitService{accountRepo: repo}, + httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, cfg: cfg, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), + openaiWSPool: pool, + } + + serverDone := make(chan struct{}) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(serverDone) + conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover}) + if err != nil { + 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 { + return + } + _ = 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.1","stream":false}`))) + cancelWrite() + + var frames []string + for len(frames) < len(tt.upstream) { + readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _, message, readErr := clientConn.Read(readCtx) + cancel() + if readErr != nil { + break + } + frames = append(frames, string(message)) + } + _ = clientConn.CloseNow() + tt.check(t, frames) + select { + case <-serverDone: + case <-time.After(5 * time.Second): + t.Fatal("waiting for ingress websocket shutdown timed out") + } + }) + } +} + +func TestProxyOpenAIWSHTTPBridgeTurnStripsSafetyReviewDetailsForClient(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + frame string + clean bool + }{ + {name: "error_frame", frame: safetyReviewErrorFrame}, + {name: "response_failed_frame", frame: safetyReviewFailedFrame}, + {name: "clean_frame_unchanged", frame: cleanFailedFrame, clean: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, Header: make(http.Header), + Body: io.NopCloser(strings.NewReader("data: " + tt.frame + "\n\n")), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ID: 12, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) + var writes [][]byte + + _, _ = svc.proxyOpenAIWSHTTPBridgeTurn( + context.Background(), c, account, "sk-test", payload, len(payload), + "gpt-5", "", "", "", "", 2, + func(message []byte) error { + writes = append(writes, append([]byte(nil), message...)) + return nil + }, + ) + require.Len(t, writes, 1) + if tt.clean { + require.Equal(t, tt.frame, string(writes[0])) + return + } + requireSafetyReviewStripped(t, writes[0]) + }) + } +} + +func TestOpenAIWSClientFrameConnWriteFrameStripsSafetyReviewDetails(t *testing.T) { + tests := []struct { + name string + frame string + clean bool + }{ + {name: "error", frame: safetyReviewErrorFrame}, + {name: "response_failed", frame: safetyReviewFailedFrame}, + {name: "clean_unchanged", frame: cleanFailedFrame, clean: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + serverErr := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + serverErr <- err + return + } + defer func() { _ = conn.CloseNow() }() + fc := &openAIWSClientFrameConn{conn: conn, interTurnStarted: make(chan struct{}, 1)} + serverErr <- fc.WriteFrame(r.Context(), coderws.MessageText, []byte(tt.frame)) + })) + 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() }() + + readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second) + _, got, err := clientConn.Read(readCtx) + cancelRead() + require.NoError(t, err) + require.NoError(t, <-serverErr) + if tt.clean { + require.Equal(t, tt.frame, string(got)) + return + } + requireSafetyReviewStripped(t, got) + }) + } +} + +func newSafetyReviewForwardV2Service(t *testing.T, events ...string) (*OpenAIGatewayService, *Account) { + t.Helper() + cfg := newOpenAIWSV2TestConfig() + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.OpenAIWS.MinIdlePerAccount = 0 + raw := make([][]byte, 0, len(events)) + for _, e := range events { + raw = append(raw, []byte(e)) + } + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(&openAIWSCaptureDialer{conn: &openAIWSCaptureConn{events: raw}}) + svc := &OpenAIGatewayService{ + cfg: cfg, httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), + openaiWSPool: pool, + } + account := &Account{ + ID: 5412, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, + Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}, + } + return svc, account +} + +func TestOpenAIGatewayService_Forward_WSv2_StripsSafetyReviewDetailsForHTTPClient(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + stream bool + frame string + clean bool + }{ + {name: "stream_response_failed", stream: true, frame: safetyReviewFailedFrame}, + {name: "stream_error", stream: true, frame: safetyReviewErrorFrame}, + {name: "stream_clean_unchanged", stream: true, frame: cleanFailedFrame, clean: true}, + {name: "nonstream_response_failed", stream: false, frame: safetyReviewFailedFrame}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc, account := newSafetyReviewForwardV2Service(t, tt.frame) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.98.0") + body := `{"model":"gpt-5.1","stream":` + map[bool]string{true: "true", false: "false"}[tt.stream] + `,"input":"hello"}` + + _, _ = svc.Forward(context.Background(), c, account, []byte(body)) + + out := rec.Body.String() + if tt.stream { + out = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(out), "data:")) + } + if tt.clean { + require.Equal(t, tt.frame, out) + return + } + require.NotContains(t, out, "misalignment\"", out) + require.NotContains(t, out, "private project summary") + if tt.stream { + requireSafetyReviewStripped(t, []byte(out)) + return + } + require.Equal(t, "workspace_suspended", gjson.Get(out, "error.code").String(), out) + require.Equal(t, "blocked", gjson.Get(out, "error.message").String(), out) + }) + } +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index e97faa44ed..56ba18a4d3 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1196,6 +1196,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(clientMessage); changed { clientMessage = rewritten } + if stripped, ok := stripOpenAISafetyReviewDetailsForClient(clientMessage); ok { + clientMessage = stripped + } } if err := writeClientMessage(clientMessage); err != nil { if isOpenAIWSClientDisconnectError(err) { diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index facff98ff9..2cf9ad55ea 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -476,6 +476,9 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( if clientDisconnected { return } + if stripped, ok := stripOpenAISafetyReviewDetailsForClient(message); ok { + message = stripped + } frame := make([]byte, 0, len(message)+8) frame = append(frame, "data: "...) frame = append(frame, message...) @@ -814,7 +817,7 @@ readLoop: responseID = strings.TrimSpace(gjson.GetBytes(finalResponse, "id").String()) } - c.Data(http.StatusOK, "application/json", finalResponse) + c.Data(http.StatusOK, "application/json", stripOpenAISafetyReviewDetailsFromFailedResponseForClient(finalResponse)) } else { flushStreamWriter(true) } diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index ce7a7dfaec..57a0117e41 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -911,6 +911,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(clientMessage); changed { clientMessage = rewritten } + if stripped, ok := stripOpenAISafetyReviewDetailsForClient(clientMessage); ok { + clientMessage = stripped + } } if !clientDisconnected && !suppressClientMessage { isKeepalive := eventType == "keepalive" diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index e4c4bac0a5..8df26010cd 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -645,6 +645,9 @@ func (c *openAIWSClientFrameConn) WriteFrame(ctx context.Context, msgType coderw if normalized, changed := normalizeCompletedImageGenerationStatus(payload); changed { payload = normalized } + if stripped, ok := stripOpenAISafetyReviewDetailsForClient(payload); ok { + payload = stripped + } if c.restoreResponseModel != nil { payload = c.restoreResponseModel(payload) } From 9e63d8b986d58e0d451c243b4c5a5e43572053cc Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:48:59 +0800 Subject: [PATCH 37/45] =?UTF-8?q?fix:=20=E9=9D=9E=E7=BB=AD=E6=8E=A5?= =?UTF-8?q?=E6=9C=AA=E7=BC=93=E5=AD=98=E8=BD=AE=E4=BF=9D=E7=95=99=20failov?= =?UTF-8?q?er=20=E8=BE=93=E5=85=A5=E5=B9=B6=E5=8E=BB=E9=87=8D=E5=85=B1?= =?UTF-8?q?=E4=BA=AB=E5=8E=86=E5=8F=B2=E5=AD=97=E8=8A=82=EF=BC=88audit=20f?= =?UTF-8?q?ollow-up=20for=20#9203=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_ws_forwarder_ingress.go | 20 ++- .../service/openai_ws_http_bridge_history.go | 25 +++ .../openai_ws_http_bridge_history_test.go | 168 ++++++++++++++++++ 3 files changed, 209 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 267cb40b48..b9e5c36055 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -647,12 +647,15 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } var turnReplayInput, turnAccountFailoverInput []json.RawMessage var turnReplayInputExists, turnAccountFailoverInputExists bool + var turnItems []json.RawMessage + var turnItemsExists, turnItemsParsed bool cacheTurn := ResponsesWSBridgeReplayInputFits(currentBridgePayload.payloadRaw, ResponsesWSBridgeHistoryLimit) if cacheTurn { items, exists, extractErr := openAIWSExtractNormalizedInputSequence(currentBridgePayload.payloadRaw) if extractErr != nil { return fmt.Errorf("build websocket http bridge replay input: %w", extractErr) } + turnItems, turnItemsExists, turnItemsParsed = items, exists, true cacheTurn = history.reserve(ResponsesWSBridgeReplayItemsBytes(items)) if cacheTurn { items = CloneResponsesWSBridgeReplayItems(items) @@ -662,7 +665,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( turnAccountFailoverInput, turnAccountFailoverInputExists = buildOpenAIWSReplayInputSequenceFromItems( bridgeAccountFailoverInput, bridgeAccountFailoverInputExists, items, exists, needsBridgeReplay, ) - turnBytes := ResponsesWSBridgeReplayItemsBytes(turnReplayInput) + ResponsesWSBridgeReplayItemsBytes(turnAccountFailoverInput) + turnBytes := ResponsesWSBridgeReplayUnionBytes(turnReplayInput, turnAccountFailoverInput) cacheTurn = history.resize(turnBytes) } } else { @@ -672,9 +675,18 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if needsBridgeReplay { return NewResponsesWSBridgeHistoryCloseError() } - turnReplayInput, turnAccountFailoverInput = nil, nil - turnReplayInputExists, turnAccountFailoverInputExists = false, false + turnReplayInput, turnReplayInputExists = nil, false history.resize(0) + // 本轮不进入历史,但独立请求仍须能跨账号重试:failover 输入仅在本轮 + // 生命周期内引用(回合结束即随 historyLost 丢弃),不占用历史预算。 + if !turnItemsParsed { + items, exists, extractErr := openAIWSExtractNormalizedInputSequence(currentBridgePayload.payloadRaw) + if extractErr != nil { + return fmt.Errorf("build websocket http bridge failover input: %w", extractErr) + } + turnItems, turnItemsExists = items, exists + } + turnAccountFailoverInput, turnAccountFailoverInputExists = turnItems, turnItemsExists } if needsBridgeReplay && turnReplayInputExists { updatedPayload, setInputErr := setOpenAIWSPayloadInputSequence( @@ -785,7 +797,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( ) bridgeAccountFailoverInputExists = true } - history.resize(ResponsesWSBridgeReplayItemsBytes(bridgeReplayInput) + ResponsesWSBridgeReplayItemsBytes(bridgeAccountFailoverInput)) + history.resize(ResponsesWSBridgeReplayUnionBytes(bridgeReplayInput, bridgeAccountFailoverInput)) } history.budget.LogSize(openAIWSLegacyBridgeHistoryPath) if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go index 23b791254e..7aceca5371 100644 --- a/backend/internal/service/openai_ws_http_bridge_history.go +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -105,6 +105,31 @@ func ResponsesWSBridgeReplayItemsBytes(items []json.RawMessage) int { return size } +// ResponsesWSBridgeReplayUnionBytes measures two replay sequences that may share +// item bodies. Identical sequences count once; otherwise each sequence pays for +// its own slice entries but a body referenced by both is counted once. +func ResponsesWSBridgeReplayUnionBytes(a, b []json.RawMessage) int { + if len(a) == len(b) && (len(a) == 0 || &a[0] == &b[0]) { + return ResponsesWSBridgeReplayItemsBytes(a) + } + seen := make(map[*byte]struct{}, len(a)) + for _, item := range a { + if len(item) > 0 { + seen[&item[0]] = struct{}{} + } + } + size := ResponsesWSBridgeReplayItemsBytes(a) + len(b)*responsesWSBridgeHistoryItemOverhead + for _, item := range b { + if len(item) == 0 { + continue + } + if _, shared := seen[&item[0]]; !shared { + size += len(item) + } + } + return size +} + // CloneResponsesWSBridgeReplayItems gives replay items their own backing bytes // so retaining an item cannot keep an entire client frame alive. func CloneResponsesWSBridgeReplayItems(items []json.RawMessage) []json.RawMessage { diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go index 5019751ff9..0376a8d710 100644 --- a/backend/internal/service/openai_ws_http_bridge_history_test.go +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -4,6 +4,7 @@ package service import ( "context" + "encoding/json" "errors" "fmt" "io" @@ -162,3 +163,170 @@ func TestOpenAIWSHTTPBridgeHistoryOverLimitReconnectsWithFullInput(t *testing.T) }) } } + +func bridgeHistoryTestResponse(status int, body string) *http.Response { + contentType := "text/event-stream" + if status != http.StatusOK { + contentType = "application/json" + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": {contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +func bridgeHistoryTestCompleted(id string) string { + return fmt.Sprintf("data: {\"type\":\"response.completed\",\"response\":{\"id\":%q,\"output\":[]}}\n\n", id) +} + +func TestResponsesWSBridgeReplayUnionBytes(t *testing.T) { + shared := []json.RawMessage{json.RawMessage(`{"a":1}`), json.RawMessage(`{"b":2}`)} + require.Equal(t, ResponsesWSBridgeReplayItemsBytes(shared), ResponsesWSBridgeReplayUnionBytes(shared, shared)) + require.Zero(t, ResponsesWSBridgeReplayUnionBytes(nil, nil)) + + extended := append(append([]json.RawMessage(nil), shared...), json.RawMessage(`{"c":3}`)) + want := ResponsesWSBridgeReplayItemsBytes(extended) + len(shared)*responsesWSBridgeHistoryItemOverhead + require.Equal(t, want, ResponsesWSBridgeReplayUnionBytes(extended, shared)) + + distinct := []json.RawMessage{json.RawMessage(`{"a":1}`)} + require.Equal(t, ResponsesWSBridgeReplayItemsBytes(shared)+ResponsesWSBridgeReplayItemsBytes(distinct), + ResponsesWSBridgeReplayUnionBytes(shared, distinct)) +} + +// An independent turn that is not retained in history must still be able to +// fail over to another account with the current turn's input. +func TestOpenAIWSHTTPBridgeUncachedIndependentTurnKeepsFailoverRetryPayload(t *testing.T) { + const free = 1000 + connHistory := &ResponsesWSBridgeHistory{} + require.True(t, connHistory.TryReserve(ResponsesWSBridgeHistoryLimit-free)) + t.Cleanup(func() { connHistory.Release(ResponsesWSBridgeHistoryLimit - free) }) + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_first")), + bridgeHistoryTestResponse(http.StatusTooManyRequests, `{"error":{"message":"rate limited"}}`), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 72, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + + done := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = conn.CloseNow() }() + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + hooks := &OpenAIWSIngressHooks{BridgeHistory: connHistory} + done <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token", firstMessage, hooks) + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + t.Cleanup(func() { _ = client.CloseNow() }) + + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"grok","input":"first"}`))) + _, frame, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, "resp_first", gjson.GetBytes(frame, "response.id").String()) + + // Larger than the remaining connection budget: this turn is not cached. + big := strings.Repeat("y", 4*free) + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(fmt.Sprintf(`{"type":"response.create","model":"grok","input":[{"type":"message","role":"user","content":%q}]}`, big)))) + + var runErr error + select { + case runErr = <-done: + case <-ctx.Done(): + t.Fatal("timed out waiting for bridge to return") + } + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, runErr, &failoverErr) + retryPayload, ok := OpenAIWSCurrentTurnRetryPayload(runErr) + require.True(t, ok) + require.NotEmpty(t, retryPayload, "uncached independent turn must remain retryable on another account") + require.Equal(t, big, gjson.GetBytes(retryPayload, "input.0.content").String()) + require.False(t, gjson.GetBytes(retryPayload, "previous_response_id").Exists()) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} + +// Replay and account-failover sequences share item bodies, so a single frame +// between limit/2 and limit must still be cacheable for a follow-up turn. +func TestOpenAIWSHTTPBridgeSharedItemsCountedOnceForLargeFrame(t *testing.T) { + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_first")), + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_second")), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 73, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + + // Between limit/2 and limit, so counting the shared items twice would overflow. + bigSize := ResponsesWSBridgeHistoryLimit * 5 / 8 + big := strings.Repeat("z", bigSize) + + done := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = conn.CloseNow() }() + conn.SetReadLimit(int64(bigSize) + 4096) + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + done <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token", firstMessage, nil) + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + t.Cleanup(func() { _ = client.CloseNow() }) + client.SetReadLimit(1 << 20) + + read := func(id string) { + _, frame, readErr := client.Read(ctx) + require.NoError(t, readErr) + require.Equal(t, id, gjson.GetBytes(frame, "response.id").String()) + } + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(fmt.Sprintf(`{"type":"response.create","model":"grok","input":[{"type":"message","role":"user","content":%q}]}`, big)))) + read("resp_first") + require.Greater(t, sharedResponsesWSBridgeHistory.bytes.Load()-processBytes, int64(bigSize)) + require.Less(t, sharedResponsesWSBridgeHistory.bytes.Load()-processBytes, int64(ResponsesWSBridgeHistoryLimit)) + + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(`{"type":"response.create","model":"grok","previous_response_id":"resp_first","input":"next"}`))) + read("resp_second") + require.Len(t, upstream.requests, 2) + + require.NoError(t, client.Close(coderws.StatusNormalClosure, "")) + require.NoError(t, <-done) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} From 71436d44cc67104522b90a5e079a74e16167321b Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 11:50:32 +0800 Subject: [PATCH 38/45] =?UTF-8?q?fix:=20keep=20existing=20400=20classifica?= =?UTF-8?q?tion=20before=20alpha=20search=20API-key=20failover=EF=BC=88aud?= =?UTF-8?q?it=20follow-up=20for=20#9149=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/openai_alpha_search.go | 33 ++++--- .../service/openai_alpha_search_test.go | 85 ++++++++++++++++++- 2 files changed, 107 insertions(+), 11 deletions(-) diff --git a/backend/internal/service/openai_alpha_search.go b/backend/internal/service/openai_alpha_search.go index 1b1b3e7834..aa55cc2a2e 100644 --- a/backend/internal/service/openai_alpha_search.go +++ b/backend/internal/service/openai_alpha_search.go @@ -91,16 +91,6 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co return nil, fmt.Errorf("read alpha search response: %w", err) } - // API key 中转可能只拒绝独立搜索端点。直接换号,不重试同一账号, - // 也不把这次 400 计入账号健康;耗尽时仍透传最后一次上游响应。 - if account.Type == AccountTypeAPIKey && resp.StatusCode == http.StatusBadRequest { - return nil, &UpstreamFailoverError{ - StatusCode: resp.StatusCode, - ResponseBody: respBody, - ResponseHeaders: resp.Header, - Reason: OpenAIAlphaSearchRejectedReason, - } - } if resp.StatusCode >= http.StatusBadRequest { upstreamMessage := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))) if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMessage, respBody) || @@ -126,6 +116,20 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co } } + // API key 中转可能只拒绝独立搜索端点。上面的既有分类(访问状态、transient + // 等)保持原有副作用;其余会被直接透传的 400,除 cyber_policy 与上下文 + // 窗口超限这类请求级错误外,直接换号,不重试同一账号,也不把这次 400 + // 计入账号健康;耗尽时仍透传最后一次上游响应。 + if account.Type == AccountTypeAPIKey && resp.StatusCode == http.StatusBadRequest && + !isOpenAIAlphaSearchRequestScoped400(sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))), respBody) { + return nil, &UpstreamFailoverError{ + StatusCode: resp.StatusCode, + ResponseBody: respBody, + ResponseHeaders: resp.Header, + Reason: OpenAIAlphaSearchRejectedReason, + } + } + if !account.IsShadow() { s.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, resp.Header) } @@ -557,6 +561,15 @@ func isOpenAIAlphaSearchEndpointUnsupported(account *Account, statusCode int) bo return statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed } +// isOpenAIAlphaSearchRequestScoped400 reports 400s that blame the request rather +// than the account/endpoint, which main passes through without rotating. +func isOpenAIAlphaSearchRequestScoped400(upstreamMessage string, responseBody []byte) bool { + if hit, _, _ := detectOpenAICyberPolicy(responseBody); hit { + return true + } + return isOpenAIContextWindowError(upstreamMessage, responseBody) +} + func shouldApplyOpenAIAlphaSearchAccountErrorSideEffects(statusCode int, upstreamMessage string, responseBody []byte) bool { switch statusCode { case http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed: diff --git a/backend/internal/service/openai_alpha_search_test.go b/backend/internal/service/openai_alpha_search_test.go index 64199e617b..ffc6bb1104 100644 --- a/backend/internal/service/openai_alpha_search_test.go +++ b/backend/internal/service/openai_alpha_search_test.go @@ -252,7 +252,7 @@ func TestForwardAlphaSearchAPIKeyMapsModelAndFailsOverOnBadRequest(t *testing.T) c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) c.Request.Header.Set("Content-Type", "application/json") - upstreamBody := `{"error":{"type":"invalid_request_error","message":"organization has been disabled"}}` + upstreamBody := `{"error":{"type":"invalid_request_error","message":"search command is not supported by this relay"}}` upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, @@ -759,3 +759,86 @@ func TestIsOpenAIAlphaSearchEndpointUnsupported(t *testing.T) { require.False(t, isOpenAIAlphaSearchEndpointUnsupported(oauth, http.StatusNotFound)) require.False(t, isOpenAIAlphaSearchEndpointUnsupported(nil, http.StatusNotFound)) } + +func newAlphaSearchAPIKeyBadRequestFixture(t *testing.T, upstreamBody string) (*OpenAIGatewayService, *alphaSearchAccountStateRepo, *Account, *gin.Context, *httptest.ResponseRecorder, []byte) { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(`{"id":"search-session","model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/alpha/search", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + repo := &alphaSearchAccountStateRepo{} + cfg := &config.Config{} + svc := &OpenAIGatewayService{ + cfg: cfg, httpUpstream: upstream, accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, cfg, nil, nil), + } + account := &Account{ + ID: 7, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://compat.example/v4", + }, + } + return svc, repo, account, c, recorder, body +} + +func TestForwardAlphaSearchAPIKeyBadRequestAccessStateKeepsMainSideEffects(t *testing.T) { + upstreamBody := `{"error":{"code":"organization_disabled","message":"Organization has been disabled"}}` + svc, repo, account, c, _, body := newAlphaSearchAPIKeyBadRequestFixture(t, upstreamBody) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Nil(t, result) + require.NotEqual(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason, "access-state 400 must stay on the existing classification") + require.Equal(t, 1, repo.setErrorCalls, "access-state 400 must still mark the account as in main") + require.False(t, c.Writer.Written()) +} + +func TestForwardAlphaSearchAPIKeyBadRequestRequestScopedPassesThrough(t *testing.T) { + tests := []struct { + name string + body string + }{ + {"cyber_policy", `{"error":{"code":"cyber_policy","message":"blocked by cyber policy"}}`}, + {"context window exceeded", `{"error":{"code":"context_length_exceeded","message":"Your input exceeds the context window of this model"}}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc, repo, account, c, recorder, body := newAlphaSearchAPIKeyBadRequestFixture(t, tt.body) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + require.NoError(t, err, "request-scoped 400 must not rotate accounts") + require.Nil(t, result) + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.JSONEq(t, tt.body, recorder.Body.String()) + require.Zero(t, repo.setErrorCalls) + }) + } +} + +func TestForwardAlphaSearchAPIKeyBadRequestUnrecognizedFailsOverWithoutAccountState(t *testing.T) { + upstreamBody := `{"error":{"code":"unsupported_endpoint","message":"alpha search is not available"}}` + svc, repo, account, c, _, body := newAlphaSearchAPIKeyBadRequestFixture(t, upstreamBody) + + result, err := svc.ForwardAlphaSearch(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Nil(t, result) + require.Equal(t, OpenAIAlphaSearchRejectedReason, failoverErr.Reason) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.Zero(t, repo.setErrorCalls) + require.False(t, c.Writer.Written()) +} From 1a55e8297368ed704c018bc4c05aa441836de871 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 12:04:31 +0800 Subject: [PATCH 39/45] =?UTF-8?q?fix:=20strip=20safety=20review=20details?= =?UTF-8?q?=20using=20the=20resolved=20SSE=20event=20type=EF=BC=88audit=20?= =?UTF-8?q?follow-up=20for=20#9147=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SSE data lines may omit "type"; the HTTP SSE path already resolved the event type from the event: line, so strip with that instead of re-reading the payload. --- .../openai_gateway_failed_event_sanitize_test.go | 16 ++++++++++++++++ .../service/openai_gateway_response_handling.go | 14 ++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_gateway_failed_event_sanitize_test.go b/backend/internal/service/openai_gateway_failed_event_sanitize_test.go index f5651ba7da..cc5d9e77f0 100644 --- a/backend/internal/service/openai_gateway_failed_event_sanitize_test.go +++ b/backend/internal/service/openai_gateway_failed_event_sanitize_test.go @@ -84,3 +84,19 @@ func TestStripOpenAISafetyReviewDetailsFromFailedResponseForClient(t *testing.T) require.Equal(t, in, string(stripOpenAISafetyReviewDetailsFromFailedResponseForClient([]byte(in)))) } } + +// SSE data lines may omit "type"; the event: line names the event and the +// HTTP SSE path passes that resolved type in. +func TestSanitizeOpenAIFailedEventWithoutTypeFieldStripsSafetyReviewDetails(t *testing.T) { + failed := []byte(`{"response":{"status":"failed","error":{"code":"misalignment_policy_violation","message":"blocked","misalignment":{"detailed_explanation":"another user's private project summary"}}}}`) + out, changed := sanitizeOpenAIResponseFailedEventForClient(failed, "response.failed", false) + require.True(t, changed) + require.False(t, gjson.GetBytes(out, "response.error.misalignment").Exists()) + require.Equal(t, "blocked", gjson.GetBytes(out, "response.error.message").String()) + + errEvent := []byte(`{"error":{"code":"misalignment_policy_violation","message":"blocked","misalignment":{"detailed_explanation":"another user's private project summary"}}}`) + out, changed = sanitizeOpenAIResponseFailedEventForClient(errEvent, "error", false) + require.True(t, changed) + require.False(t, gjson.GetBytes(out, "error.misalignment").Exists()) + require.NotContains(t, string(out), "another user's private") +} diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index a0ed1c00ee..1ef3d40d2e 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -2020,7 +2020,17 @@ func stripOpenAISafetyReviewDetailsForClient(payload []byte) ([]byte, bool) { if !bytes.Contains(payload, []byte("misalignment")) { return payload, true } - if t := gjson.GetBytes(payload, "type").String(); t != "response.failed" && t != "error" { + return stripOpenAISafetyReviewDetailsForClientEvent(payload, gjson.GetBytes(payload, "type").String()) +} + +// stripOpenAISafetyReviewDetailsForClientEvent strips using an already resolved +// event type, so SSE frames whose data omits "type" (the event: line names it) +// are still covered. +func stripOpenAISafetyReviewDetailsForClientEvent(payload []byte, eventType string) ([]byte, bool) { + if eventType != "response.failed" && eventType != "error" { + return payload, true + } + if !bytes.Contains(payload, []byte("misalignment")) { return payload, true } updated := payload @@ -2065,7 +2075,7 @@ func sanitizeOpenAIResponseFailedEventForClient(payload []byte, eventType string if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(updated); changed { updated = rewritten } - next, ok := stripOpenAISafetyReviewDetailsForClient(updated) + next, ok := stripOpenAISafetyReviewDetailsForClientEvent(updated, eventType) if !ok { return payload, false } From 293428484457b93727a6d3a0eb00a0156979973b Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 12:04:31 +0800 Subject: [PATCH 40/45] =?UTF-8?q?fix:=20drop=20bridge=20history=20when=20e?= =?UTF-8?q?nd-of-turn=20resize=20does=20not=20fit=EF=BC=88audit=20follow-u?= =?UTF-8?q?p=20for=20#9203=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retaining a turn can need more budget than the turn held because the replay and failover sequences get separate header arrays. When that growth does not fit, drop the history instead of keeping it under-accounted. Count a shared body only when both pointer and length match, and skip the common prefix by index so the lookup set covers only the diverging tail. --- .../service/openai_ws_forwarder_ingress.go | 9 +- .../service/openai_ws_http_bridge_history.go | 28 ++++-- .../openai_ws_http_bridge_history_test.go | 96 +++++++++++++++++++ 3 files changed, 126 insertions(+), 7 deletions(-) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index b9e5c36055..fc2d5e188c 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -797,7 +797,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( ) bridgeAccountFailoverInputExists = true } - history.resize(ResponsesWSBridgeReplayUnionBytes(bridgeReplayInput, bridgeAccountFailoverInput)) + if !history.resize(ResponsesWSBridgeReplayUnionBytes(bridgeReplayInput, bridgeAccountFailoverInput)) { + // 保存的历史超出可用预算时整体丢弃,保证持有预算始终覆盖已保留的历史; + // 后续续接回合将按 historyLost 以 1013 要求客户端重发完整输入。 + historyLost = true + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + history.resize(0) + } } history.budget.LogSize(openAIWSLegacyBridgeHistoryPath) if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go index 7aceca5371..259ed74556 100644 --- a/backend/internal/service/openai_ws_http_bridge_history.go +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -112,24 +112,40 @@ func ResponsesWSBridgeReplayUnionBytes(a, b []json.RawMessage) int { if len(a) == len(b) && (len(a) == 0 || &a[0] == &b[0]) { return ResponsesWSBridgeReplayItemsBytes(a) } - seen := make(map[*byte]struct{}, len(a)) - for _, item := range a { + size := ResponsesWSBridgeReplayItemsBytes(a) + len(b)*responsesWSBridgeHistoryItemOverhead + // The sequences usually share a leading run of bodies; walk it by index so + // the lookup set only covers the diverging tail. A body shared outside the + // tails is counted twice, which over-estimates and stays within budget. + prefix := 0 + for prefix < len(a) && prefix < len(b) && sameResponsesWSBridgeReplayBody(a[prefix], b[prefix]) { + prefix++ + } + seen := make(map[*byte]int, len(a)-prefix) + for _, item := range a[prefix:] { if len(item) > 0 { - seen[&item[0]] = struct{}{} + seen[&item[0]] = len(item) } } - size := ResponsesWSBridgeReplayItemsBytes(a) + len(b)*responsesWSBridgeHistoryItemOverhead - for _, item := range b { + for _, item := range b[prefix:] { if len(item) == 0 { continue } - if _, shared := seen[&item[0]]; !shared { + if seenLen, shared := seen[&item[0]]; !shared || seenLen != len(item) { size += len(item) } } return size } +// sameResponsesWSBridgeReplayBody reports whether two items are the same +// retained body, not merely equal bytes. +func sameResponsesWSBridgeReplayBody(a, b json.RawMessage) bool { + if len(a) != len(b) { + return false + } + return len(a) == 0 || &a[0] == &b[0] +} + // CloneResponsesWSBridgeReplayItems gives replay items their own backing bytes // so retaining an item cannot keep an entire client frame alive. func CloneResponsesWSBridgeReplayItems(items []json.RawMessage) []json.RawMessage { diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go index 0376a8d710..2ed62b0a0a 100644 --- a/backend/internal/service/openai_ws_http_bridge_history_test.go +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -330,3 +330,99 @@ func TestOpenAIWSHTTPBridgeSharedItemsCountedOnceForLargeFrame(t *testing.T) { require.NoError(t, <-done) require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) } + +func TestResponsesWSBridgeReplayUnionBytesPrefixAndAliases(t *testing.T) { + head := []json.RawMessage{json.RawMessage(`{"a":1}`), json.RawMessage(`{"b":2}`)} + replay := append(append([]json.RawMessage(nil), head...), json.RawMessage(`{"r":1}`)) + failover := append(append([]json.RawMessage(nil), head...), json.RawMessage(`{"f":1}`)) + want := ResponsesWSBridgeReplayItemsBytes(replay) + len(failover)*responsesWSBridgeHistoryItemOverhead + len(`{"f":1}`) + require.Equal(t, want, ResponsesWSBridgeReplayUnionBytes(replay, failover)) + + // A shorter view of the same backing bytes is a different body and must not + // be treated as already counted. + body := json.RawMessage(`{"long":"value"}`) + view := body[:7] + require.Equal(t, + ResponsesWSBridgeReplayItemsBytes([]json.RawMessage{body})+ResponsesWSBridgeReplayItemsBytes([]json.RawMessage{view}), + ResponsesWSBridgeReplayUnionBytes([]json.RawMessage{body}, []json.RawMessage{view})) +} + +// Retaining a turn can need more budget than the turn held (each sequence gets +// its own header array). When that growth does not fit, the history must be +// dropped instead of being kept under-accounted. +func TestOpenAIWSHTTPBridgeEndOfTurnResizeFailureDropsHistory(t *testing.T) { + const n = 200 + itemRaw := `{"type":"message","role":"user","content":"x"}` + items := make([]string, n) + for i := range items { + items[i] = itemRaw + } + outItem := `{"type":"message","id":"m1","role":"assistant","content":[]}` + itemsBytes := n * (len(itemRaw) + responsesWSBridgeHistoryItemOverhead) + collector := len(outItem) + responsesWSBridgeHistoryItemOverhead + len("m1") + free := itemsBytes + collector + 100 + + conn := &ResponsesWSBridgeHistory{} + pre := ResponsesWSBridgeHistoryLimit - free + require.True(t, conn.TryReserve(pre)) + t.Cleanup(func() { conn.Release(pre) }) + processBytes := sharedResponsesWSBridgeHistory.bytes.Load() + + heldAtTurn2 := -1 + hooks := &OpenAIWSIngressHooks{BridgeHistory: conn, BeforeTurn: func(turn int) error { + if turn == 2 { + heldAtTurn2 = conn.bytes - pre + } + return nil + }} + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + bridgeHistoryTestResponse(http.StatusOK, fmt.Sprintf( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_first\",\"output\":[%s]}}\n\n", outItem)), + bridgeHistoryTestResponse(http.StatusOK, bridgeHistoryTestCompleted("resp_second")), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 74, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"base_url": xai.DefaultCLIBaseURL}, + } + done := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + wsConn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer func() { _ = wsConn.CloseNow() }() + _, firstMessage, err := wsConn.Read(r.Context()) + if err != nil { + done <- err + return + } + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Request = r + done <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, wsConn, account, "access-token", firstMessage, hooks) + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + t.Cleanup(func() { _ = client.CloseNow() }) + + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(`{"type":"response.create","model":"grok","input":[`+strings.Join(items, ",")+`]}`))) + _, frame, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, "resp_first", gjson.GetBytes(frame, "response.id").String()) + + require.NoError(t, client.Write(ctx, coderws.MessageText, + []byte(`{"type":"response.create","model":"grok","previous_response_id":"resp_first","input":"next"}`))) + runErr := <-done + require.Zero(t, heldAtTurn2, "history that does not fit must be released, not kept under-accounted") + var closeErr *OpenAIWSClientCloseError + require.True(t, errors.As(runErr, &closeErr)) + require.Equal(t, coderws.StatusTryAgainLater, closeErr.StatusCode()) + require.Len(t, upstream.requests, 1) + require.Equal(t, processBytes, sharedResponsesWSBridgeHistory.bytes.Load()) +} From a64db2860beb39d9dd4187a6a51fa19dc9ccf287 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 12:37:30 +0800 Subject: [PATCH 41/45] =?UTF-8?q?test:=20pass=20the=20replay=20collector?= =?UTF-8?q?=20argument=20added=20by=20#9203=EF=BC=88audit=20follow-up=20fo?= =?UTF-8?q?r=20#9147=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_ws_failed_event_safety_review_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/openai_ws_failed_event_safety_review_test.go b/backend/internal/service/openai_ws_failed_event_safety_review_test.go index 4b7fde612f..f119f42048 100644 --- a/backend/internal/service/openai_ws_failed_event_safety_review_test.go +++ b/backend/internal/service/openai_ws_failed_event_safety_review_test.go @@ -176,7 +176,7 @@ func TestProxyOpenAIWSHTTPBridgeTurnStripsSafetyReviewDetailsForClient(t *testin _, _ = svc.proxyOpenAIWSHTTPBridgeTurn( context.Background(), c, account, "sk-test", payload, len(payload), - "gpt-5", "", "", "", "", 2, + "gpt-5", "", "", "", "", 2, nil, func(message []byte) error { writes = append(writes, append([]byte(nil), message...)) return nil From ec0e489ab770ea188ef221bd0abf6c8e0e3efb46 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 15:22:58 +0800 Subject: [PATCH 42/45] fix(release): require the tagged commit to carry the release VERSION The sync-version-file job committed the VERSION bump to main only after publishing, so every tag pointed at a commit whose VERSION was the previous release (v0.2.19 through v0.2.26). Published artifacts were unaffected because prepare rewrites VERSION from the tag, but source builds of a tag (go build, GitHub source archives, Docker builds without .git) reported the old version. prepare now fails before building or publishing when VERSION at the tag does not match the tag version. A manual run with allow_version_mismatch=true downgrades this to a warning for re-releasing older tags. The post-release sync job is removed: the VERSION bump is committed before tagging instead. --- .github/release-tools/README.md | 4 +- .github/release-tools/release_matrix.py | 10 +++++ .github/release-tools/test_release_matrix.py | 18 ++++++++- .github/workflows/release.yml | 41 +++++--------------- 4 files changed, 39 insertions(+), 34 deletions(-) diff --git a/.github/release-tools/README.md b/.github/release-tools/README.md index 6126de34fe..a1525e10b7 100644 --- a/.github/release-tools/README.md +++ b/.github/release-tools/README.md @@ -6,6 +6,8 @@ Each build uses GoReleaser OSS in snapshot mode with the selected release versio Go caches are isolated by target and refreshed on each source commit, with fallback to the preceding target cache. Save uses the original restore key, even if a build hook changes `go.sum`. Matrix jobs upload uniquely named artifacts. The publishing job extracts only the regular Linux binary from each verified archive and restores its executable permission before constructing Docker contexts. QEMU remains limited to runtime-image instructions. DockerHub images are omitted when its credentials are absent; GHCR is always retained. Simple mode still publishes only the amd64 GHCR image and the simple release description. +A tag push is rejected in `prepare`, before anything is built or published, unless `backend/cmd/server/VERSION` at the tagged commit already equals the tag version: commit the VERSION bump first, then tag that commit. Source builds of the tag (`go build`, GitHub source archives, Docker builds without `.git`) embed that file. To re-release an older tag created before this rule, run the workflow manually with `allow_version_mismatch=true`; it then emits a warning and builds with the tag version. + All build jobs use the commit resolved by `prepare`, including a manual release's selected tag. Helper scripts come from the workflow revision and are passed as a run-local artifact, so older application tags do not need to contain the new scripts. The workflow serializes release runs to prevent simultaneous updates to moving image tags. ## Validate without publication @@ -17,7 +19,7 @@ gh workflow run release.yml --ref \ -f tag= -f dry_run=true -f simple_release=false ``` -A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, Telegram notifications and VERSION synchronization. Test the simple path separately with `simple_release=true`. +A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, and Telegram notifications. Test the simple path separately with `simple_release=true`. Dry-run artifacts are available in the Actions run, including `release-dry-run-report`. Compare job start/end times, GoReleaser's build duration and cache restore results. Do not present an initial cold-cache run as a warmed-cache benchmark; publishing network time is not measured by dry runs. diff --git a/.github/release-tools/release_matrix.py b/.github/release-tools/release_matrix.py index 4ea183879f..b805349e3e 100644 --- a/.github/release-tools/release_matrix.py +++ b/.github/release-tools/release_matrix.py @@ -63,6 +63,15 @@ def plan(args): tagged_sha = subprocess.check_output(['git', 'rev-parse', '--verify', f'refs/tags/{tag}^{{commit}}'], text=True).strip() if sha != tagged_sha: raise ValueError('checkout does not match the selected release tag') + committed = VERSION_FILE.read_text().strip() + if committed != version: + # Source builds of the tag (go build, archives, Docker builds without .git) + # embed this file, so the tagged commit itself must carry the new version. + message = (f'{VERSION_FILE} at {tag} is {committed!r}, expected {version!r}; ' + 'commit the VERSION bump first, then tag that commit') + if not args.allow_version_mismatch: + raise ValueError(message) + print(f'::warning::{message}') if not VERSION_RE.fullmatch(version): raise ValueError('invalid VERSION') VERSION_FILE.write_text(version + '\n') @@ -161,6 +170,7 @@ def main(): p.add_argument('--ref', required=True) p.add_argument('--simple', action='store_true') p.add_argument('--dry-run', action='store_true') + p.add_argument('--allow-version-mismatch', action='store_true') p.set_defaults(run=plan) p = commands.add_parser('config') p.add_argument('mode', choices=['build', 'publish']) diff --git a/.github/release-tools/test_release_matrix.py b/.github/release-tools/test_release_matrix.py index bbfc0fc673..22e8c594b7 100644 --- a/.github/release-tools/test_release_matrix.py +++ b/.github/release-tools/test_release_matrix.py @@ -121,8 +121,24 @@ class ReleaseMatrixTest(unittest.TestCase): self.assertEqual(binary.read_bytes(), b'fixture') self.assertEqual(binary.stat().st_mode & 0o777, 0o755) + def test_tag_push_requires_committed_version_to_match_tag(self): + release.VERSION_FILE.write_text('9.8.6\n') + args = argparse.Namespace(ref='v9.8.7', dry_run=False, simple=False, allow_version_mismatch=False) + with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'): + with self.assertRaisesRegex(ValueError, "is '9.8.6', expected '9.8.7'"): + release.plan(args) + + def test_manual_release_of_older_tag_warns_and_uses_tag_version(self): + release.VERSION_FILE.write_text('9.8.6\n') + args = argparse.Namespace(ref='v9.8.7', dry_run=False, simple=False, allow_version_mismatch=True) + with patch.dict(os.environ, {'GITHUB_OUTPUT': 'outputs'}), patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'): + release.plan(args) + output = dict(line.split('=', 1) for line in Path('outputs').read_text().splitlines()) + self.assertEqual(output['version'], '9.8.7') + self.assertEqual(release.VERSION_FILE.read_text(), '9.8.7\n') + def test_plan_requires_a_tag_for_publication(self): - args = argparse.Namespace(ref='main', dry_run=False, simple=False) + args = argparse.Namespace(ref='main', dry_run=False, simple=False, allow_version_mismatch=False) with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'): with self.assertRaisesRegex(ValueError, 'version tag'): release.plan(args) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b5780a6be5..5912864a8a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,6 +20,11 @@ on: required: false type: boolean default: false + allow_version_mismatch: + description: 'Re-release an older tag whose committed VERSION predates the tag (builds with the tag version)' + required: false + type: boolean + default: false concurrency: group: release-${{ github.repository }} @@ -64,10 +69,14 @@ jobs: id: plan env: REQUESTED_REF: ${{ inputs.tag || github.ref_name }} + ALLOW_VERSION_MISMATCH: ${{ github.event_name == 'workflow_dispatch' && inputs.allow_version_mismatch == true }} run: | args=(--ref "$REQUESTED_REF") if [[ "$SIMPLE_RELEASE" == true ]]; then args+=(--simple); fi if [[ "$DRY_RUN" == true ]]; then args+=(--dry-run); fi + # The tagged commit must already carry the release VERSION. Only an explicit + # manual re-release of an older tag may bypass this. + if [[ "$ALLOW_VERSION_MISMATCH" == true ]]; then args+=(--allow-version-mismatch); fi python "$RUNNER_TEMP/release-tools/release_matrix.py" plan "${args[@]}" - uses: actions/upload-artifact@v7 with: @@ -374,35 +383,3 @@ jobs: parse_mode: "Markdown", disable_web_page_preview: true }')" - - sync-version-file: - needs: [prepare, release] - if: ${{ needs.release.result == 'success' && needs.prepare.outputs.dry_run != 'true' }} - runs-on: ubuntu-latest - permissions: - contents: write - env: - RELEASE_VERSION: ${{ needs.prepare.outputs.version }} - steps: - - name: Checkout default branch - uses: actions/checkout@v6 - with: - ref: ${{ github.event.repository.default_branch }} - - - name: Sync VERSION file to released tag - run: | - VERSION="$RELEASE_VERSION" - - CURRENT_VERSION=$(tr -d '\r\n' < backend/cmd/server/VERSION || true) - if [ "$CURRENT_VERSION" = "$VERSION" ]; then - echo "VERSION file already matches $VERSION" - exit 0 - fi - - echo "$VERSION" > backend/cmd/server/VERSION - - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add backend/cmd/server/VERSION - git commit -m "chore: sync VERSION to ${VERSION} [skip ci]" - git push origin HEAD:${{ github.event.repository.default_branch }} From 24b70236d5354172444194487d91e8ef61ab25cf Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 15:53:42 +0800 Subject: [PATCH 43/45] fix(risk-control): audit follow-up for #9191 - Excluded accounts no longer suppress image_safety / cyber_policy evidence, ban counting or notifications; those are upstream verdicts, not our audit. - Sampled multi-image inputs (more images than the audit sends) skip the clean cache and singleflight so one clean random sample cannot pin the verdict. - Account search truncates by rune and drops invalid UTF-8 so PG does not reject the pattern with a 500. - Account directory lookups are part of ContentModerationRepository instead of a runtime type assertion; lookup errors now propagate from Get/UpdateConfig. - Remove the never-set BodyValidated flag and the frontend id-only fallback. --- .../handler/openai_gateway_handler.go | 1 - .../handler/openai_gateway_handler_test.go | 8 +++++ .../internal/handler/openai_images_safety.go | 1 - .../repository/content_moderation_accounts.go | 16 +++++++--- .../content_moderation_accounts_unit_test.go | 22 +++++++++++++ .../internal/service/content_moderation.go | 25 ++++++++------- .../service/content_moderation_accounts.go | 32 +++++-------------- .../content_moderation_accounts_test.go | 21 +++++++++--- .../service/content_moderation_cyber_test.go | 8 +++++ .../service/content_moderation_engines.go | 9 ++++-- .../content_moderation_image_safety.go | 4 --- .../service/content_moderation_input.go | 10 +++--- .../service/content_moderation_test.go | 8 +++++ frontend/src/api/admin/riskControl.ts | 4 +-- frontend/src/views/admin/RiskControlView.vue | 13 +------- .../admin/__tests__/RiskControlView.spec.ts | 2 ++ 16 files changed, 112 insertions(+), 72 deletions(-) create mode 100644 backend/internal/repository/content_moderation_accounts_unit_test.go diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index d9557804c2..b714bf6bcd 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -4618,7 +4618,6 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey cmSvc.RecordCyberPolicyEvent(ctx, service.CyberPolicyRecordInput{ LogOnly: cyberLogOnly, RequestID: requestID, - AccountID: accountID, UserID: userID, UserEmail: userEmail, APIKeyID: apiKeyID, diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go index 0803ac0f3e..5ee7cbde51 100644 --- a/backend/internal/handler/openai_gateway_handler_test.go +++ b/backend/internal/handler/openai_gateway_handler_test.go @@ -1364,6 +1364,14 @@ func (r *contentModerationHandlerTestRepo) UpdateLogEmailSent(ctx context.Contex return nil } +func (r *contentModerationHandlerTestRepo) SearchModerationAccounts(context.Context, service.ContentModerationAccountSearchFilter) ([]service.ContentModerationExcludedAccount, error) { + return []service.ContentModerationExcludedAccount{}, nil +} + +func (r *contentModerationHandlerTestRepo) ListModerationAccountsByIDs(context.Context, []int64) ([]service.ContentModerationExcludedAccount, error) { + return []service.ContentModerationExcludedAccount{}, nil +} + func TestOpenAIResponsesWebSocket_ContentModerationBlocksFirstFrame(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/handler/openai_images_safety.go b/backend/internal/handler/openai_images_safety.go index 1302192b19..5480242091 100644 --- a/backend/internal/handler/openai_images_safety.go +++ b/backend/internal/handler/openai_images_safety.go @@ -51,7 +51,6 @@ func (h *OpenAIGatewayHandler) recordOpenAIImagesSafetyRefusal(c *gin.Context, a } } if account != nil { - in.AccountID = account.ID in.Provider = account.Platform } go func() { diff --git a/backend/internal/repository/content_moderation_accounts.go b/backend/internal/repository/content_moderation_accounts.go index 58b726a696..4ad2e1429f 100644 --- a/backend/internal/repository/content_moderation_accounts.go +++ b/backend/internal/repository/content_moderation_accounts.go @@ -5,6 +5,7 @@ import ( "fmt" "strconv" "strings" + "unicode/utf8" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/lib/pq" @@ -13,6 +14,7 @@ import ( const ( defaultModerationAccountSearchLimit = 20 maxModerationAccountSearchLimit = 50 + maxModerationAccountSearchRunes = 100 ) func escapeModerationLikePattern(raw string) string { @@ -20,6 +22,15 @@ func escapeModerationLikePattern(raw string) string { return replacer.Replace(raw) } +// truncateModerationAccountSearch 清洗非法 UTF-8 并按字符截断,避免 PG 拒绝截断出的半个多字节字符。 +func truncateModerationAccountSearch(raw string) string { + search := strings.TrimSpace(strings.ToValidUTF8(raw, "")) + if utf8.RuneCountInString(search) > maxModerationAccountSearchRunes { + search = strings.TrimSpace(string([]rune(search)[:maxModerationAccountSearchRunes])) + } + return search +} + func (r *contentModerationRepository) SearchModerationAccounts( ctx context.Context, filter service.ContentModerationAccountSearchFilter, @@ -54,10 +65,7 @@ func (r *contentModerationRepository) SearchModerationAccounts( )) } - search := strings.TrimSpace(filter.Search) - if len(search) > 100 { - search = search[:100] - } + search := truncateModerationAccountSearch(filter.Search) if search != "" { idCandidate := strings.TrimSpace(strings.TrimPrefix(search, "#")) if parsedID, err := strconv.ParseInt(idCandidate, 10, 64); err == nil && parsedID > 0 { diff --git a/backend/internal/repository/content_moderation_accounts_unit_test.go b/backend/internal/repository/content_moderation_accounts_unit_test.go new file mode 100644 index 0000000000..66bb3960fa --- /dev/null +++ b/backend/internal/repository/content_moderation_accounts_unit_test.go @@ -0,0 +1,22 @@ +//go:build unit + +package repository + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/require" +) + +func TestTruncateModerationAccountSearch_KeepsValidUTF8(t *testing.T) { + // 99 个 ASCII + 多字节汉字:按字节截到 100 会切出半个字符,PG 报 invalid byte sequence。 + raw := strings.Repeat("a", 99) + "账户名称" + got := truncateModerationAccountSearch(raw) + require.True(t, utf8.ValidString(got)) + require.Equal(t, strings.Repeat("a", 99)+"账", got) + + require.Equal(t, "ab", truncateModerationAccountSearch(" a\xffb ")) + require.Equal(t, "账户", truncateModerationAccountSearch("账户")) +} diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index 6b0d9a69a7..d8a6e45544 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -321,7 +321,6 @@ type ContentModerationModelFilter struct { type ContentModerationCheckInput struct { riskControlLogOnly bool // Captured at admission and retained by asynchronous tasks. - BodyValidated bool RequestID string AccountID int64 UserID int64 @@ -497,6 +496,10 @@ type ContentModerationRepository interface { CleanupExpiredLogs(ctx context.Context, hitBefore time.Time, nonHitBefore time.Time) (*ContentModerationCleanupResult, error) // UpdateLogEmailSent 回写邮件发送结果(F7:CreateLog 先行后补 EmailSent)。 UpdateLogEmailSent(ctx context.Context, id int64, sent bool) error + // SearchModerationAccounts 按审计分组范围模糊搜索排除账户候选。 + SearchModerationAccounts(ctx context.Context, filter ContentModerationAccountSearchFilter) ([]ContentModerationExcludedAccount, error) + // ListModerationAccountsByIDs 回填排除账户简要信息(已删除账户不返回)。 + ListModerationAccountsByIDs(ctx context.Context, ids []int64) ([]ContentModerationExcludedAccount, error) } type ContentModerationHashCache interface { @@ -685,7 +688,7 @@ func (s *ContentModerationService) GetConfig(ctx context.Context) (*ContentModer if err != nil { return nil, err } - return s.engineConfigViewWithContext(ctx, cfg), nil + return s.engineConfigViewWithContext(ctx, cfg) } func (s *ContentModerationService) UpdateConfig(ctx context.Context, input UpdateContentModerationConfigInput) (*ContentModerationConfigView, error) { @@ -803,7 +806,7 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat s.replaceRuntimeConfig(cfg, raw) // 代理选择可能已变化,丢弃已解析的代理 URL 缓存,下次调用即时生效。 s.moderationProxyCache.Store(nil) - return s.engineConfigViewWithContext(ctx, cfg), nil + return s.engineConfigViewWithContext(ctx, cfg) } func (s *ContentModerationService) TestAPIKeys(ctx context.Context, input TestContentModerationAPIKeysInput) (*TestContentModerationAPIKeysResult, error) { @@ -990,7 +993,6 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer input.Body, keywordEnabled, needImages, - input.BodyValidated, ) if cfg.Mode == ContentModerationModePreBlock { @@ -1150,8 +1152,11 @@ func (s *ContentModerationService) checkSync(ctx context.Context, input ContentM evalDigest = computeModerationEvalDigest(cfg) } } - hasMutableImage := hasMutableExternalModerationImage(content.Images) - useCleanFastPath := s != nil && allowBlock && queueDelay == nil && cfg != nil && !cfg.RecordNonHits && hashText != "" && !hasMutableImage + // 外链图片内容可变;超过上限的多图每次只随机抽检一张,同一 hash 的放行结论不代表全部图片。 + // 两种情况都不得复用放行缓存或合并在途请求。 + nonReusable := hasMutableExternalModerationImage(content.Images) || + len(content.Images) > maxContentModerationInputImages + useCleanFastPath := s != nil && allowBlock && queueDelay == nil && cfg != nil && !cfg.RecordNonHits && hashText != "" && !nonReusable if useCleanFastPath && s.lookupCleanInputCache(hashText, evalDigest) { if trackPreBlock { s.recordPreBlockSyncMetric(0, ContentModerationActionAllow) @@ -1165,7 +1170,7 @@ func (s *ContentModerationService) checkSync(ctx context.Context, input ContentM err error ) moderationInput := content.ModerationInput() - if s != nil && queueDelay == nil && hashText != "" && !hasMutableImage { + if s != nil && queueDelay == nil && hashText != "" && !nonReusable { sfKey := hex.EncodeToString(evalDigest[:16]) + ":" + hashText ch := s.inflightSync.DoChan(sfKey, func() (any, error) { sharedCtx := context.WithoutCancel(ctx) @@ -1212,7 +1217,7 @@ func (s *ContentModerationService) checkSync(ctx context.Context, input ContentM } flagged, highestCategory, highestScore := evaluateModerationScores(result.CategoryScores, cfg.Thresholds) - if !flagged && hashText != "" && !hasMutableImage && s != nil { + if !flagged && hashText != "" && !nonReusable && s != nil { s.storeCleanInputCache(hashText, evalDigest) } action := ContentModerationActionAllow @@ -3353,7 +3358,6 @@ func maskSecretTail(secret string) string { type CyberPolicyRecordInput struct { LogOnly bool // Trusted platform user: retain evidence without penalties or notifications. RequestID string - AccountID int64 UserID int64 UserEmail string APIKeyID int64 @@ -3385,9 +3389,6 @@ func (s *ContentModerationService) RecordCyberPolicyEvent(ctx context.Context, i if !runtimeSnapshot.riskControlEnabled { return } - if runtimeSnapshot.isAccountExcluded(in.AccountID) { - return - } cfg := runtimeSnapshot.config if !runtimeSnapshot.includesGroup(in.GroupID) || !runtimeSnapshot.includesModel(in.Model) { return diff --git a/backend/internal/service/content_moderation_accounts.go b/backend/internal/service/content_moderation_accounts.go index 3886bcce9c..c1efcde852 100644 --- a/backend/internal/service/content_moderation_accounts.go +++ b/backend/internal/service/content_moderation_accounts.go @@ -24,12 +24,6 @@ type ContentModerationAccountSearchFilter struct { Limit int } -// ContentModerationAccountDirectory 为可选仓储能力接口,避免侵入既有单测桩实现。 -type ContentModerationAccountDirectory interface { - SearchModerationAccounts(ctx context.Context, filter ContentModerationAccountSearchFilter) ([]ContentModerationExcludedAccount, error) - ListModerationAccountsByIDs(ctx context.Context, ids []int64) ([]ContentModerationExcludedAccount, error) -} - func normalizeExcludedAccountIDs(ids []int64) []int64 { if len(ids) == 0 { return []int64{} @@ -64,11 +58,7 @@ func (s *ContentModerationService) SearchAccounts( if !filter.AllGroups && len(filter.GroupIDs) == 0 { return []ContentModerationExcludedAccount{}, nil } - dir, ok := s.repo.(ContentModerationAccountDirectory) - if !ok { - return []ContentModerationExcludedAccount{}, nil - } - items, err := dir.SearchModerationAccounts(ctx, filter) + items, err := s.repo.SearchModerationAccounts(ctx, filter) if err != nil { return nil, err } @@ -81,20 +71,14 @@ func (s *ContentModerationService) SearchAccounts( func (s *ContentModerationService) resolveExcludedAccountsView( ctx context.Context, ids []int64, -) []ContentModerationExcludedAccount { +) ([]ContentModerationExcludedAccount, error) { normalized := normalizeExcludedAccountIDs(ids) if len(normalized) == 0 { - return []ContentModerationExcludedAccount{} + return []ContentModerationExcludedAccount{}, nil } - - var fetched []ContentModerationExcludedAccount - if s != nil && s.repo != nil { - if dir, ok := s.repo.(ContentModerationAccountDirectory); ok { - items, err := dir.ListModerationAccountsByIDs(ctx, normalized) - if err == nil { - fetched = items - } - } + fetched, err := s.repo.ListModerationAccountsByIDs(ctx, normalized) + if err != nil { + return nil, fmt.Errorf("resolve excluded moderation accounts: %w", err) } byID := make(map[int64]ContentModerationExcludedAccount, len(fetched)) @@ -108,13 +92,13 @@ func (s *ContentModerationService) resolveExcludedAccountsView( out = append(out, item) continue } - // 即使账户已被删除或测试桩未挂载目录查询,也保留回退项确保管理员可在界面看到并移除。 + // 账户已被删除时保留 #ID 回退项,确保管理员可在界面看到并移除。 out = append(out, ContentModerationExcludedAccount{ ID: id, Name: fmt.Sprintf("#%d", id), }) } - return out + return out, nil } type accountModerationHookContextKey struct{} diff --git a/backend/internal/service/content_moderation_accounts_test.go b/backend/internal/service/content_moderation_accounts_test.go index 2cf4f59d40..2d20adae82 100644 --- a/backend/internal/service/content_moderation_accounts_test.go +++ b/backend/internal/service/content_moderation_accounts_test.go @@ -108,21 +108,20 @@ func TestContentModeration_ExcludedAccountSkipsAllStagesWithZeroSideEffects(t *t require.Empty(t, hashCache.checked, "排除账户不得查询 Redis 违规哈希") require.Empty(t, repo.logs) - // 事后 image_safety 与 cyber_policy 对排除账户同样最优先忽略。 + // 事后 image_safety 与 cyber_policy 是上游给出的判定,排除账户不豁免:仍需留证与计数。 svc.RecordImageSafetyEvent(context.Background(), ImageSafetyRecordInput{ - AccountID: 101, UserID: 88, Model: "gpt-image-1", Prompt: "unsafe image", UpstreamStatus: 400, }) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ - AccountID: 202, UserID: 88, Model: "gpt-5.4", UpstreamMessage: "cyber policy violation", }) - require.Empty(t, repo.logs) + require.Len(t, repo.logs, 2, "排除账户不得豁免上游安全事件留证") + repo.logs = nil // 2. 非排除账户 303:正常执行拦截。 hashCache.hasResult = false @@ -362,6 +361,20 @@ func TestContentModeration_ExternalImageURLNotCachedInCleanCache(t *testing.T) { require.NoError(t, err) require.True(t, dInline2.Allowed) require.Equal(t, int32(3), upstreamCalls.Load(), "内联 Base64 图片应继续命中 Clean Cache") + + // 3. 超过上限的多张内联图片每次只随机抽检一张:放行结论不得缓存,后续请求必须重新抽检。 + multiBody := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"multi"},{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}},{"type":"image_url","image_url":{"url":"data:image/png;base64,BBBB"}}]}]}`) + for i := range 2 { + dMulti, checkErr := svc.Check(context.Background(), ContentModerationCheckInput{ + UserID: 1, + Protocol: ContentModerationProtocolOpenAIChat, + Model: "gpt-5.4", + Body: multiBody, + }) + require.NoError(t, checkErr) + require.True(t, dMulti.Allowed) + require.Equal(t, int32(4+i), upstreamCalls.Load(), "抽检的多图输入不得命中 Clean Cache") + } } func TestContentModeration_ConfigChangeInvalidatesCleanCacheEvalDigest(t *testing.T) { diff --git a/backend/internal/service/content_moderation_cyber_test.go b/backend/internal/service/content_moderation_cyber_test.go index 6df7f31db8..b12943d78a 100644 --- a/backend/internal/service/content_moderation_cyber_test.go +++ b/backend/internal/service/content_moderation_cyber_test.go @@ -37,6 +37,14 @@ func (r *cyberOrderingTestRepo) UpdateLogEmailSent(ctx context.Context, id int64 return nil } +func (r *cyberOrderingTestRepo) SearchModerationAccounts(context.Context, ContentModerationAccountSearchFilter) ([]ContentModerationExcludedAccount, error) { + return []ContentModerationExcludedAccount{}, nil +} + +func (r *cyberOrderingTestRepo) ListModerationAccountsByIDs(context.Context, []int64) ([]ContentModerationExcludedAccount, error) { + return []ContentModerationExcludedAccount{}, nil +} + func (r *cyberOrderingTestRepo) ListLogs(ctx context.Context, filter ContentModerationLogFilter) ([]ContentModerationLog, *pagination.PaginationResult, error) { return nil, nil, nil } diff --git a/backend/internal/service/content_moderation_engines.go b/backend/internal/service/content_moderation_engines.go index 407c265c1e..3ba367cafa 100644 --- a/backend/internal/service/content_moderation_engines.go +++ b/backend/internal/service/content_moderation_engines.go @@ -158,8 +158,11 @@ func (s *ContentModerationService) updateEngineProfile(ctx context.Context, cfg return nil } -func (s *ContentModerationService) engineConfigViewWithContext(ctx context.Context, cfg *ContentModerationConfig) *ContentModerationConfigView { - excludedAccounts := s.resolveExcludedAccountsView(ctx, cfg.ExcludedAccountIDs) +func (s *ContentModerationService) engineConfigViewWithContext(ctx context.Context, cfg *ContentModerationConfig) (*ContentModerationConfigView, error) { + excludedAccounts, err := s.resolveExcludedAccountsView(ctx, cfg.ExcludedAccountIDs) + if err != nil { + return nil, err + } view := s.configView(cfg.effectiveEngine(cfg.Engine)) view.ExcludedAccounts = excludedAccounts view.EngineConfigs = map[string]*ContentModerationConfigView{} @@ -168,7 +171,7 @@ func (s *ContentModerationService) engineConfigViewWithContext(ctx context.Conte subView.ExcludedAccounts = excludedAccounts view.EngineConfigs[engine] = subView } - return view + return view, nil } func scopedModerationKeyHash(key string, engine ...string) string { diff --git a/backend/internal/service/content_moderation_image_safety.go b/backend/internal/service/content_moderation_image_safety.go index 97d34514e9..ec31ebc64c 100644 --- a/backend/internal/service/content_moderation_image_safety.go +++ b/backend/internal/service/content_moderation_image_safety.go @@ -83,7 +83,6 @@ func isImageSafetyRefusalMessage(message string) bool { // ImageSafetyRecordInput 是一次图像上游安全拒绝的风控记录入参。 type ImageSafetyRecordInput struct { RequestID string - AccountID int64 UserID int64 UserEmail string APIKeyID int64 @@ -120,9 +119,6 @@ func (s *ContentModerationService) RecordImageSafetyEvent(ctx context.Context, i if !runtimeSnapshot.riskControlEnabled { return } - if runtimeSnapshot.isAccountExcluded(in.AccountID) { - return - } if !runtimeSnapshot.includesGroup(in.GroupID) || !runtimeSnapshot.includesModel(in.Model) { return } diff --git a/backend/internal/service/content_moderation_input.go b/backend/internal/service/content_moderation_input.go index bbcb313456..acee42f02e 100644 --- a/backend/internal/service/content_moderation_input.go +++ b/backend/internal/service/content_moderation_input.go @@ -29,23 +29,23 @@ type moderationTextCollector struct { } func extractContentModerationInput(protocol string, body []byte, filterReminders bool) ContentModerationInput { - return extractContentModerationInputCore(protocol, body, filterReminders, true, false, nil) + return extractContentModerationInputCore(protocol, body, filterReminders, true, nil) } // extractContentModerationInputFast 单次遍历请求体,同时产出语义审核输入(过滤 )与本地关键词文本(保留 )。 -func extractContentModerationInputFast(protocol string, body []byte, includeKeywords, includeImages, assumeValidJSON bool) (ContentModerationInput, string) { +func extractContentModerationInputFast(protocol string, body []byte, includeKeywords, includeImages bool) (ContentModerationInput, string) { var kwParts []string var kwPtr *[]string if includeKeywords { kwPtr = &kwParts } - content := extractContentModerationInputCore(protocol, body, true, includeImages, assumeValidJSON, kwPtr) + content := extractContentModerationInputCore(protocol, body, true, includeImages, kwPtr) return content, normalizeContentModerationText(strings.Join(kwParts, "\n")) } -func extractContentModerationInputCore(protocol string, body []byte, filterReminders, includeImages, assumeValidJSON bool, keywordParts *[]string) ContentModerationInput { +func extractContentModerationInputCore(protocol string, body []byte, filterReminders, includeImages bool, keywordParts *[]string) ContentModerationInput { collector := moderationTextCollector{filterReminders: filterReminders, keywordParts: keywordParts} - if len(body) == 0 || (!assumeValidJSON && !gjson.ValidBytes(body)) { + if len(body) == 0 || !gjson.ValidBytes(body) { return ContentModerationInput{} } var parts []string diff --git a/backend/internal/service/content_moderation_test.go b/backend/internal/service/content_moderation_test.go index 84300c4852..8c273ce949 100644 --- a/backend/internal/service/content_moderation_test.go +++ b/backend/internal/service/content_moderation_test.go @@ -121,6 +121,14 @@ func (r *contentModerationTestRepo) UpdateLogEmailSent(ctx context.Context, id i return nil } +func (r *contentModerationTestRepo) SearchModerationAccounts(context.Context, ContentModerationAccountSearchFilter) ([]ContentModerationExcludedAccount, error) { + return []ContentModerationExcludedAccount{}, nil +} + +func (r *contentModerationTestRepo) ListModerationAccountsByIDs(context.Context, []int64) ([]ContentModerationExcludedAccount, error) { + return []ContentModerationExcludedAccount{}, nil +} + func (r *contentModerationTestRepo) snapshotLogs() []ContentModerationLog { r.mu.Lock() defer r.mu.Unlock() diff --git a/frontend/src/api/admin/riskControl.ts b/frontend/src/api/admin/riskControl.ts index fb9d00e006..1c39a67d1f 100644 --- a/frontend/src/api/admin/riskControl.ts +++ b/frontend/src/api/admin/riskControl.ts @@ -47,8 +47,8 @@ export interface ContentModerationConfig { sample_rate: number all_groups: boolean group_ids: number[] - excluded_account_ids?: number[] - excluded_accounts?: ContentModerationExcludedAccount[] + excluded_account_ids: number[] + excluded_accounts: ContentModerationExcludedAccount[] record_non_hits: boolean thresholds: Record worker_count: number diff --git a/frontend/src/views/admin/RiskControlView.vue b/frontend/src/views/admin/RiskControlView.vue index 35e8ed97d2..6d07dfd741 100644 --- a/frontend/src/views/admin/RiskControlView.vue +++ b/frontend/src/views/admin/RiskControlView.vue @@ -1854,18 +1854,7 @@ function applyConfig(config: ContentModerationConfig) { configForm.sample_rate = config.sample_rate ?? 100 configForm.all_groups = config.all_groups configForm.group_ids = Array.isArray(config.group_ids) ? [...config.group_ids] : [] - if (Array.isArray(config.excluded_accounts) && config.excluded_accounts.length > 0) { - configForm.excluded_accounts = config.excluded_accounts.map((item) => ({ ...item })) - } else if (Array.isArray(config.excluded_account_ids) && config.excluded_account_ids.length > 0) { - configForm.excluded_accounts = config.excluded_account_ids.map((id) => ({ - id, - name: `#${id}`, - platform: '', - type: '', - })) - } else { - configForm.excluded_accounts = [] - } + configForm.excluded_accounts = config.excluded_accounts.map((item) => ({ ...item })) configForm.record_non_hits = config.record_non_hits configForm.worker_count = config.worker_count || 4 configForm.queue_size = config.queue_size || 32768 diff --git a/frontend/src/views/admin/__tests__/RiskControlView.spec.ts b/frontend/src/views/admin/__tests__/RiskControlView.spec.ts index 3e05175706..d576e681cd 100644 --- a/frontend/src/views/admin/__tests__/RiskControlView.spec.ts +++ b/frontend/src/views/admin/__tests__/RiskControlView.spec.ts @@ -91,6 +91,8 @@ const baseConfig = (): ContentModerationConfig => ({ api_key_statuses: [], timeout_ms: 3000, sample_rate: 100, + excluded_account_ids: [], + excluded_accounts: [], all_groups: true, group_ids: [], record_non_hits: false, From ce7940a9007f77cd38294c4608d425b72bb6adda Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 16:18:57 +0800 Subject: [PATCH 44/45] chore: update sponsors --- README.md | 9 ++------- README_CN.md | 9 ++------- README_JA.md | 9 ++------- assets/partners/logos/NiuProxy.jpg | Bin 10574 -> 0 bytes 4 files changed, 6 insertions(+), 21 deletions(-) delete mode 100644 assets/partners/logos/NiuProxy.jpg diff --git a/README.md b/README.md index 854e03c6b8..c3f2eb4bb3 100644 --- a/README.md +++ b/README.md @@ -133,8 +133,8 @@ Please read the following carefully before using this project: -AxisNow -Thanks to AxisNow for sponsoring this project! AxisNow protects and accelerates websites and APIs, delivering an optimal access experience across mainland China and globally, while extending acceleration and security capabilities to native/mobile apps through client SDKs — self-hosted private-deployment CDN | subscription-based DDoS-protected CDN | autonomous, flexibly composable CDN network. +AxisNow +Protect and accelerate your Sub2API with AxisNow
Optimized routes for users in mainland China, WAF and rate limiting to protect your API entry point, and support for self-hosted or subscription CDN edge nodes. View the Sub2API integration guide → @@ -162,11 +162,6 @@ Please read the following carefully before using this project: 🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY.
WeChat: Liuyou-zawd | Telegram: AACC8888888 - -NiuProxy -NiuProxy provides affordable global proxy solutions for web scraping, AI agents, automation, and data collection. With residential proxies starting at $0.35/GB across 190+ countries and regions, NiuProxy offers flexible plans and HTTP(S)/SOCKS5 support.
🎁 Use code PAY2 for 10% OFF your recharge! - - SoleAPI Thanks to SoleAPI for supporting this project! SoleAPI is an AI model gateway for developers and enterprises: one API key gives you access to 30+ leading models including Claude, GPT and Gemini. It is natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex, Cursor and your existing SDKs work by simply changing the Base URL. Requests are routed in real time by latency and upstream health, with millisecond-level automatic failover to backup channels, 99.99% service availability and 24/7 technical support. Every call lands on a single bill with per-request token and cost breakdowns you can inspect at any time. Sign up through this project's referral link to receive free trial credits, and earn ongoing cashback by inviting friends who top up! diff --git a/README_CN.md b/README_CN.md index f1e330e868..a35544007b 100644 --- a/README_CN.md +++ b/README_CN.md @@ -136,8 +136,8 @@ -AxisNow -感谢 AxisNow 赞助了本项目!AxisNow 保护并加速网站与 API,兼顾中国大陆及全球的访问体验,并通过客户端 SDK,将加速与安全能力延伸至原生/移动 App — 自建私有部署 CDN|订阅式高防 CDN|自主可控、灵活组合的 CDN 网络。 +AxisNow +使用 AxisNow 保护并加速你的 Sub2API
为中国大陆用户提供优化线路,通过 WAF 和速率控制保护 API 入口,支持自建或订阅 CDN 边缘节点。查看 Sub2API 接入教程 → @@ -165,11 +165,6 @@ 🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。
微信:Liuyou-zawd|TG:AACC8888888 - -NiuProxy -NiuProxy 为网页抓取、AI 智能体、自动化和数据采集提供高性价比的全球代理解决方案。住宅代理低至 $0.35/GB,覆盖 190+ 个国家和地区,套餐灵活,支持 HTTP(S)/SOCKS5 协议。
🎁 使用优惠码 PAY2 充值立享 9 折优惠! - - SoleAPI 感谢 SoleAPI 对本项目的支持!SoleAPI 是面向开发者与企业的 AI 模型网关:一个 API Key 即可调用 Claude、GPT、Gemini 等 30+ 主流模型。原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex、Cursor 及现有 SDK 只需修改 Base URL 即可接入。请求按延迟与上游健康度实时路由,毫秒级自动切换至备用通道,服务可用性达 99.99%,并提供 7×24 小时技术支持。所有调用统一账单结算,每次请求的 token 与费用明细随时可查。通过本项目的推荐链接注册即可获得免费试用额度,邀请好友充值还可持续获得返现! diff --git a/README_JA.md b/README_JA.md index bbe438346b..7fdc6ffd7d 100644 --- a/README_JA.md +++ b/README_JA.md @@ -135,8 +135,8 @@ -AxisNow -AxisNow のご支援に感謝します!AxisNow はウェブサイトと API を保護・高速化し、中国本土および世界中で快適なアクセス体験を実現します。クライアント SDK により、ネイティブ/モバイルアプリにも高速化・セキュリティ機能を拡張できます — 自社構築・プライベートデプロイ CDN|サブスクリプション型高防御 CDN|自律制御で柔軟に組み合わせられる CDN ネットワーク。 +AxisNow +AxisNow で Sub2API を保護・高速化
中国本土のユーザー向けに最適化された回線を提供し、WAF とレート制御で API の入口を保護します。自社構築またはサブスクリプションの CDN エッジノードに対応しています。Sub2API 導入ガイドを見る → @@ -164,11 +164,6 @@ 🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。
WeChat:Liuyou-zawd|Telegram:AACC8888888 - -NiuProxy -NiuProxy は、Web スクレイピング、AI エージェント、自動化、データ収集向けに、手頃な価格のグローバルプロキシソリューションを提供します。住宅プロキシは $0.35/GB から、190 以上の国と地域をカバーし、柔軟なプランと HTTP(S)/SOCKS5 に対応しています。
🎁 コード PAY2 でチャージが 10% オフ! - - SoleAPI SoleAPI 様、本プロジェクトへのご支援ありがとうございます!SoleAPI は開発者と企業向けの AI モデルゲートウェイです。1 つの API キーで Claude、GPT、Gemini をはじめとする 30 以上の主要モデルを利用できます。OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex、Cursor や既存の SDK も Base URL を変更するだけで動作します。リクエストはレイテンシと上流の稼働状況に応じてリアルタイムにルーティングされ、ミリ秒単位でバックアップチャネルへ自動フェイルオーバーします。サービス可用性は 99.99%、24 時間 365 日の技術サポートも提供しています。すべての呼び出しは 1 つの請求書にまとめられ、リクエストごとの token 数と費用の内訳をいつでも確認できます。本プロジェクトの紹介リンクから登録すると無料トライアルクレジットを受け取れ、友人を招待してチャージしてもらうと継続的にキャッシュバックを獲得できます! diff --git a/assets/partners/logos/NiuProxy.jpg b/assets/partners/logos/NiuProxy.jpg deleted file mode 100644 index 51f400987fb2f761562e3466164cd2711461411d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10574 zcmbVyXH-*L*KQD`7irRoN(TXfAe{&vx)4E%bSVmm^j@PNs8m6UAcAxO0qMP$&|8oy z9qA>Z1_;TwIp@6Zz2pA6_wF$=#$IDTd(QdHvi4eQ20w*g1l`b7)ldZy0M}iDyC4vL z7W5EAN=!^be4UhpgoKQYl$?@*ijsnYl7)_*hJk|>%*nyZ&VGwqgzwg!yIkz-{89pU z?}19?mRDB)tgUZsZlMnjkB(1H zF=yvjya+&q|Iqp`v;Tt^Ex_v<5fLE~$rUexYd*k_ke2BBZ82gxC0!CLH~Kr`Z%7%G z<1)+I$hai*P>j~@qvSWaAxk{yD{6l;`@bU=^8dx`zr_9*uNe>}ApsCPLRt_MbdZ73 zkW|8hMAdK@OH?i%^!AGZ9+Xjm2L*~^3{@ESF8nhFhUKR8a0aKWco6E-RtL^v_!8B! zq=g5Osg~kFP`j%)fA|Xoyv!Kr_#4OuMkQ>64^QCxVR#U^B}TI<_Ur+32cO z7hnez!bJaAx>d>>|A;*c#DjVqaSSb}WXFd%OXvX|Jk0vVCrE(tsnxN+Wnc5EGal4# zRYG$X2tM6}w#Q-~RSlnA{(b+`LwinZX1F%UB>6zJj)Mlvn|g}H#aoJ$YY!B##6qXO@^l<>kdr z@oS1E*T-c2-8zgQ+N8C?M9J5QCk8S!!o)LmvbwT;%&3{03`u|6D9O9?t$E3`i>b%E z=6$ly_iAOR%6Ad0#0Df>;z8PDCGd*kypQ))13xzIy10s^mgZx8jDFqaZ7xTy zrB7V@EB@P(tGEZ|hJAfNaIaBp z2}}&6Ol1|Cw;{hVigCu_rh}4n;>W?KzO~@Ay6~XRUlec>OvDz2 z@#5%Sx=I#qm~1W{^A1a~cF0JxZUyFHLuYMPjqo)@~Lu z2Q@yy2Ew2Ojn z+=K6TT4J>gIEm0o2X9856Z%gX6Nq0?rjre84zhB7_xhB584lmQF&jKsvpyt&+#DW@ zwNklEfZ9>_%mMCBSplC@f-lfaK;mft#!7TUk62v(8Jpp9^DH(_!;z1x0|LSbqMT(w zM};Z5$1kBh%}WP}vR?q%0d(voaRv^H_?PU}`>gPPD>Ki&;5?UR)zY0K?!VYoJg7ws z4?;t(=m78j0miz(Sh7zyRWUalZWYu+{WDM#9k*Gcl>rk3>f_TD(^xEm=fB7&r_M`w z(0(S6FQs}YW|y;*=2a$HI1om0AdEW;r(3{lX)Sbt_6S1rFStuJz_>~N9(}tI1r=>a z*NHjCt^0E^S=$^wH9)alt?P*wdGNNd~mq`^~ z(N0d3}-?(i{IZvioN8~c3gsK?^C@U7IQI_DIwLn0%UEX=7TN~g>pvKhDgCneR? zc+yixV>>E@TCC?z9gz*&yC>l!w<2cKnU8ytd|3>4jp$T;=k|nj45ZyZRh9%OB!|jN zt`t<#upsg~?DBgV%3mgxeJ$J9`6?Fsnf*K}U@{HUu$+{?%q9bgzR&FWl|)W&Z2DUA zBNTJ&>OIBEdXlIrD#E3crX`m$a~7A+esqG*AK#%cGmmm8IaK8;%o=1RjzZZRXBfGpZ53D&ukW$A+{aq@_2T z>I3?dQ)-8mHsr`RAj2Fl>tSIcSUDHQ%!+zCGLF%x&u*ci4IBzZCjA-K^hOHE4yjal z^wKC+@3jj2`I?F#pLLJH#|ztV@TG^oyc8b91Mh|&4=vz9D#gC}Ve)oGzOrk6l?yx* zUKHF<3T&n2*{{j4pYAzoB9@(Ntd@nfOe5yIO1wZJ&+QkU&4AcccVfQw{!sYBF}i6% z6SfyfwxZ>$-#BKma3||Pi@Eh$QJ{E5Z8gTUKXY-uq@UwnO* zsjHTXl~1-t9&85OPO|6Gd*a5u`YeP-vBhknX|fwiXa3NSur2>gir;4TkJMfpvz*R8 zBJJ?(iR;HtYTta#kG|uGXR7Pidh_1G6>g-(orEKlY0P{|fN$rrTG$bk!h8dF1Gyf( z_mD=cjXW%z;`xUcuRM3LMejM~ei^m#wTB47e%i2|NPUTw7}##$2&y*{)qYr85_G-5 zH~h2%PVD(*PG&+buev&#TafLAKAo%Y5W)8LBh*mAcWC=pHH&f^k5aRg=cxt{p7v0W zc)y9cAwbA{vex)T4?R>+=xaFHQPE|8cQ=H{QR1-#ySusY1s@Df}anpSr zc9Bg|4)VPfdIar@QM3AeJWOV}#mR#)|IzZ{b3gTTqFtPF(u0&?*pf`!G3PIrrSjoI ztb94_h7$d3m+WP9u6%hm&E1S_N}9(coXrNymJuev{C8LTZPxtEAbL&h+DBW?D2*Y7 zaKVxWG>z$`=e8WNsi}~uno)!tw|%S7sejq#OnzM0=oIF(Gqw30+7Z^&pqz9+K)YP@ z_L9{HnhV4l=M-m3sfr>;IVX@YZ(AEJU?;(I(;EwiNa&v1Q7LmRS|=OLdH85l(j#vM zclxK9_QvKx+PZKQJGJyG`JTLEsj08&Ql}!zJ43BqRdtnW42m>TKAu3DEm(ILGBZuE zYQgnu6;1Mf|5$BhmoDisVlQ6>9P%1U-q&`5?cx=1)Kj^-QItNdHSd$ydMSHdj&wtk zhKeU9*~MQ{P9|z=a8-q091*);io$t?R$c^Kr#<(6ocsCBETk{uahgHCP;^z$bwI|( zl^h;nd-X+@d%kU_>|@^uY6L(rZfRp0r`C9o&w1({unZpL)e@H@78)AYmj9EoVKNl^ z@Eplc6y76`B%D*EX{ngiJg`{kpF1En^wMtdUr&oT6!YD;dJ;b;>XZN5i9E1x z{e6xLm(yP_TvS*fGbh0MbavVl>(~-8bk6qMVb3mUo-sl~WVMI9(cg~aaK3TD7-jVS zM_yw~!)Qr%g$Anz_iTHK|2T3WQ^37no8H2Qp`g;^rzy-`J%oklmhD?TH{E-JUFsdw zViuFj29tZmkPg(JDPK?10)3<{>9&YY-~h*Tw?z8cu;fF;E0Qp*6ldcJqT6~YaE0Z` zovtLrXQSA?U>SseH%nU1WPR0UkWrz)SlJ&c2iM5D#W=Mh0YiCJ-PWPECRm&YI-Q2nk_K>K2x8t*S%;%FNev8Lwrf#i6AGhZsUtSjZeAjvz z4tY#+UQLuHGdrvx#Yw~Xm2#=qLz}xeh@*ScTfVD`!;o2bZuRNHUPJf21!Xl!9ksf8 zVh76j>x*Tpq8Otl#iFc0Ro0q!I;GF=rG4=Hz7nqQOD-Z?yW{BmT<~o)s`z7B} za%5#}d5=rdpQQs(?>wUt;bgAK5MTdA&vag;OZFBYtZbDzKS#VDS8^YIs_FOE6{rWU2pl=Zb-> zW-io!SF~kpRh7xxF18-xR5f03bSLk=&ut$zKjrfs>5_}ic?i-4dqZAPM6~M5g1lyZ z;*nHqK1@s`@plzyI!|b2n%dnkc zs)HOcmcZ(RwzgNUG!r=&j1waZFOnTLyxCcg`d!s_(C#$g%}bh#ZF4;6eRgv^QscfD zCK@rVx{{;K?l=;(+vj&wQ1GQs{LdfLsuoA8CyLI#b6}g>hDTh)IjIxNQv&H^TvUDg zdJ;#2{_oyd8dP91zr#-G{er9Up!%ALl0=dBf-P?Cy9=={^{^(-c*?) z?hsP=l{sdyedbcFFg=)S+#%4FIv7$cj9R7lpZ=pqba_vdBRx9-3uEEzevVGq7Cwfz1?d1BMA;-luG zaSkC)D7U-v?DOcjSZS+J&9a`+WPR(v>nR2yGd`&Ezw?q&po13RT_&=H1KY=Cu^OlKPX>ZI1WV$E6X z)LA;2%B_6Cq-Wo3KSi9z4avglm@e}1AZ5vhtd}#A(N&%P;Sn`s8k|#UL!)QHp@)Gj z0rIY{#0uN8r&-gW{%%;ugz~OirvDW&yx2MM*aaRdIE-Rf#M=#B9;r#6}~&ZVZuDZK50uT437yk zw1D-m$Qr3WedRIBwubpaJCu4eod-ScU0;Hz2`8?-A+!8K4`k`qYpuX=GWcAt*F2HY z$0ine^i|CuA@8e|m*1_eYEU&?2zi`H{|w!ZdohvChsS-iEpA9K08Q(8|obJ@K>A3Qc2xstLg=6i2c- zIE!||Uxxik5U@Y}*!ah&ieb$_S36wv+{xAHIsVj4Xy|8M}T`_jzQ*W@DE0%74*S z!Bxn&7cy&j8&M(lt-7}Ht5paKUt+C(w3gU8fhl2|h0ru2+^aZ$tlbjF+x)FIvLk~+ zp2ID`=~5KRLiiMvrtXs_4NH?>7a`sslD!?6C7je zr{oU0G`+cWn1_SgbD8k1`KLS<1%ixL7}kj9mNGa^pdQMW$;XgPva0>3SRXNl-F3>U z=hi8Qst~YUW5K+Hk@=QfsQQR=-=)-}JzcR%gqpE~T^%*uqvle_Q&eX@Gc(k7FeUf6JE{> zvD(r(S0fp^U46yVn6N*Ywy0cx1a7V1O0`9v?hVS&MNhA*R{jW-D|s2`S05bxeGYMX z5n%K&_!;Xt+fs6Skc7&Z@UepPkWiC}C*7+QDdAfAFmm6ytpHAvW>{pfJR)z)V{@Jp zxm15cEV?A$<4*-O^)F`bfK|KALI1*R=Mf{m_&pDeB_q?|V}qxka7T z){US`bZAaDAmX^9jPt`!SfP;?yXHVYI3Dy2I0zXnGx`x|fG){ibfKBvVtsYLLQ8V$ zP0}Bh@VTgIwx=G6;IEI?`{lT$+qc#S;xVS3Vj^dr3fd&z0U9KSj7c{3({bZP)a2<@ z0f-Pqi0`LP3xV>ny(3eNZ?8S_UDx8PBKK09&1bcBjAh|CS2bdu(ANuqF}Suf(5 z6_C26Jg@&pe;f3!a)AT)$Ztr!T|b1JpK;1si~FFjuwGjfsNx|SY;z0lb%H*aJi{eyPwi4s3K$tNs_aVuQ}rb|`|Haa{#OMkJ_;O&uiJmfd%q?2%F5+|PKl6eg4 zHW%DCz_wS|x*q1!hN_3{wOKHdIu_Om_MQSiAxS6;8e3qB%)G z!D_iSP2i}qW(F22H0tMtq0h6;kNd)tGD8yksgKw5ek{|uCDq7gg!pSuB%;=S&t-F& z51jHx-BZ4Q4QJ(XB)PJ{c1$XY;~x5WBe>UvqakiC{3*_~3}XaahR4=08J0ROHOUlH zPzDulgnI!SMB)dEs~NezBVXq+=4LOJ2GVWQ9ry-hdVl+;ofhWmm<_oz(}y2}f=`6j(Bw^)KJ?1FPS!}R7v3`^VR?Z{s6UlRt?#BPUUXW_#wl)b zarN>E3PFnD&HmwrVai*%3Mv@3at-ubL%U9Ms~{bhL?r$_>Cp#xL7O~P^j&wgz1 zZHIdONhTaq$i2`nZ|K96wp3TJU2aKu(9K3Gs>M`uWdWqjy{7u>T*%in+vcj#=(6Sk z;p0pGA@5y>;`e8WdMR*;LZL6#4>d7kE=7FFQG>Sr<2AjfL z>Ei<=#&XIl(MI7}k^1GF27l_+QMLVl4b&~3Sfy7TH2T|4nkKsHPd$Q`4dHojq2hbzqgYs9EAC(GE zo1fjJew?+fkI66XKOZ;XD~_$M98{gP7}-6hknwQwA@%fNQbD5)*?#+msZSKsbkGRIpiwXTbXm03d*{YT$!N z{93)=c6D{V*ncQ{asT?1gOSlEjE7nT|7|~xnK5VrNJBv=sWGruODkXhNZAVjrv-&7<)3lHUf zpPkdDtabvKJ~w>UHTvf4Gi6|YlfQR1x~4U?Q-C^uX;Aru+i5HLzN>m>S=8$>PCv*N zGP$y;B#cbNe4tqF*JVukykwxNA(_dW;%Ij;Z`K`8UB)-GaAl035jefCMO}Rl2JSf-*4~ooY zRl}at0lgFljci5<}J!@hh#7`*JK%Q zCY_|nnxReK8!xy`6}AQ+t9NS*o2_~uroSjj=EZ~7Z7d7nzKd_hpzBqL%QG<6Kx7w; z3owT-Bm&B|Gb?a?6GwBhLr%Q&h@p7qXCKSCbhhr-QPX=**d*EAWnz8|V|=$9baPv+ z<^7y+~APR23VktkQ*m&u*=usFMw8y`Sz}(fNrLXwlZRQR7A5H zy#9fCF}(Z1u;Lu?{5-Ue=N%5cV!H`GL|)7adM2SK!km^(U4A;m zfAEpmjN9zn0o@W)dlj{48y9u4me+`^@(?NDELe0RpVf%AWV*&(MJtLb*OBo+UQ8bq zJ`I~vEWKRw8^&rv*NcZQ&n$5wQJWmO|E)uhBKvt(%kX*H`lgi1i-L*8%9A7kiQ#wP zz`D;*<8Wde%^AL zvStjV+`nozV`#M2r#!w44~ernyN-&Egs*Q8uFi!PZX4meL246ZCjB_6x%bMk!Us!X;# z{R77oN;yCeCxEhw#R)dCX^d8e(nRErd6MR#8JKc~AwgQN!r20&%DZ*gFZb4&Ip7iV zxl7yED^Y{<1vYsm3xfr-nKd`THhv#}(s4Z;`OdeW=GHBfy{&ojGstw{V0i|HJ^qio zknw$etIHHUHJl$rY@jJ;aFgSf_p?9!icv zn;;7dg{D$;SGSBCkZVvtg>&*zjn2Wo zfyHLahiBsxXaskr`3d3g!^b}PA{wnMkkME3laMb$(kqVI%0lh>bT)=&G}-*Ps$rjk zJnzG)B96@WhUZV*%LNpegDYoYR?5P{=G}Usp{bez3@@i%x;O~-(kEEq)K58ox$BSZ zPxaW`ALGm;Jb*8d6Em(6KzXO`(>|Hvz|JRkN3_GK<=!~6W;Pd$e4_cH4CZ|n!1!Uoz)C|5TdsS?a zCm*0qY8iZ|-x~u+DvGe(3nvySv1eq!bD-sp_FUL0mT1lfcEqpyfkK^-x-Xn}yXKEIj^!NbWH<9-KtkbjK*3C)!~ zu{+VCGPsf2;md%lFQnGxr@sZP{39UphovHHUw6Ita_h^(pJ#%Aib}}WdmfkBZW-q% zKy`)YI;5=VW&r3(fc*~_MN0tPzpXj4!#PxX$OfI3wF^>(V@beRa}rG?bb||uBP<2< zJe?10uJk+bAAK1V8V>-$0PvEC53mzp*EM>Xm~>MQM)H+(WN_s5YO>{(a;JAGHOc-jG+YLV|{i2_Z?mD zzg$s+03I*Eb`PHzrU3cI7KJ_5oS4gAmK$~#Y6>_1(M2W7$b^%?_crpIwM zju)a=@%|UU4ut=2JOXzOV9EZs_gLl6piL?(Qx-${hisP9srJwVTHwz%e+Ohk_C>0W zPPRMjAMgJyzdN>4 Date: Wed, 2 Dec 2026 16:28:35 +0800 Subject: [PATCH 45/45] chore: release v0.2.27 --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 770cb090eb..b32698427d 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.2.26 +0.2.27