Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/scripts/model-billing-groups-browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ try {
const page=Number(url.searchParams.get('page'))
if(page===2&&failSecondPage)return route.fulfill({status:503,json:{code:503,message:'synthetic page failure'}})
data={items:[groups[page-1]],total:2,page,page_size:100,pages:2}
} else if(url.pathname==='/api/v1/admin/accounts'){
assert.equal(route.request().method(),'GET')
for(const [key,value] of Object.entries({platform:'openai',type:'apikey',status:'active',lite:'1'}))assert.equal(url.searchParams.get(key),value)
data={items:[],total:0,page:1,page_size:100,pages:0}
} else if(url.pathname==='/api/v1/admin/account-quality-plans')data=[]
else if(url.pathname==='/api/v1/admin/account-ops/auto-config/events')data={items:[],has_more:false}
else throw new Error('Unexpected synthetic API: '+url.pathname)
Expand All @@ -104,6 +108,7 @@ try {
assert.equal(await page.getByTestId('model-billing-group-0-5').isChecked(),true)
assert.equal(await page.getByTestId('model-billing-group-1-6').isChecked(),true)
assert(requests.some(r=>r.path==='/api/v1/admin/groups'&&r.page==='2'))
assert(requests.some(r=>r.path==='/api/v1/admin/accounts'&&r.method==='GET'))
await page.getByTestId('model-billing').screenshot({path:path.join(output,'selected-groups-desktop-zh.png')})
await page.setViewportSize({width:390,height:1000})
await page.getByTestId('model-billing').screenshot({path:path.join(output,'selected-groups-mobile-zh.png')})
Expand Down
14 changes: 12 additions & 2 deletions .github/scripts/oauth-degradation-browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ const {default:Page}=new URLSearchParams(location.search).has('baseline')?await
import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';
import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts';
import {defaultOpenAITwoFAAdmissionConfig} from '/src/utils/openaiTwoFAAdmission.ts';
import {defaultOpenAIAPIKeyFallbackConfig} from '/src/utils/openaiAPIKeyFallback.ts';
import '/src/style.css';
window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null};
window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),openai_apikey_fallback:defaultOpenAIAPIKeyFallbackConfig(),openai_disable_scheduling_on_429_7d_threshold_percent:98,model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null};
const lang=new URLSearchParams(location.search).get('lang')||'zh';await loadLocaleMessages(lang);i18n.global.locale.value=lang;
createApp(Page).use(i18n).use(createPinia()).mount('#app');</script>`
process.chdir(frontend) // Tailwind/PostCSS resolve the actual frontend config.
Expand Down Expand Up @@ -61,7 +62,7 @@ const errors = [], external = [], saves = [], requests = []
let saved
const groups = [{ id: 5, name: 'OpenAI 示例组', platform: 'openai', status: 'active' }, { id: 6, name: 'Anthropic 示例组', platform: 'anthropic', status: 'active' }]
try {
const context = await browser.newContext({ viewport: { width: 1280, height: 1000 } })
const context = await browser.newContext({ viewport: { width: 1280, height: 1000 }, timezoneId: 'UTC' })
await context.route('**/*', async route => {
const url = new URL(route.request().url())
if (url.origin !== 'http://127.0.0.1:4183') { external.push(url.origin); return route.abort() }
Expand All @@ -72,6 +73,11 @@ try {
if (route.request().method() === 'PUT') { saved = route.request().postDataJSON(); saves.push(structuredClone(saved)) }
data = saved ?? await route.request().frame().evaluate(() => window.fixture)
} else if (url.pathname === '/api/v1/admin/groups/all') data = groups
else if (url.pathname === '/api/v1/admin/accounts') {
assert.equal(route.request().method(), 'GET')
assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc', timezone: 'UTC' })
data = { items: [], page: 1, page_size: 100, pages: 1, total: 0 }
}
else if (url.pathname === '/api/v1/admin/groups') data = { items: groups, page: 1, page_size: 100, pages: 1, total: 2 }
else if (url.pathname === '/api/v1/admin/account-quality-plans') data = []
else if (url.pathname === '/api/v1/admin/account-ops/auto-config/events') data = { items: [], has_more: false }
Expand All @@ -90,6 +96,10 @@ try {
assert.equal(await page.getByTestId('degradation-action').count(), 0)
await page.screenshot({ path: path.join(output, 'before-zh.png'), fullPage: true })
await open()
await page.getByTestId('apikey-fallback-loading').waitFor({ state: 'detached' })
assert.equal(await page.getByTestId('apikey-fallback-accounts-error').count(), 0)
assert.equal(await page.getByTestId('apikey-fallback-enabled').isChecked(), false)
assert(requests.some(request => request.path === '/api/v1/admin/accounts' && request.method === 'GET'))
const card=page.getByTestId('degradation-action')
const annotate=()=>page.addStyleTag({content:'[data-testid=degradation-action]::before{content:"CI fixture · 虚构数据 · 非生产";display:block;color:#92400e;font-size:12px}'})
assert.equal(await page.getByTestId('degradation-enabled').isChecked(),false)
Expand Down
14 changes: 12 additions & 2 deletions .github/scripts/oauth-initial-model-selection-browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ const {default:Page}=new URLSearchParams(location.search).has('baseline')?await
import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';
import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts';
import {defaultOpenAITwoFAAdmissionConfig} from '/src/utils/openaiTwoFAAdmission.ts';
import {defaultOpenAIAPIKeyFallbackConfig} from '/src/utils/openaiAPIKeyFallback.ts';
import '/src/style.css';
window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null};
window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),openai_apikey_fallback:defaultOpenAIAPIKeyFallbackConfig(),openai_disable_scheduling_on_429_7d_threshold_percent:98,model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null};
const lang=new URLSearchParams(location.search).get('lang')||'zh';await loadLocaleMessages(lang);i18n.global.locale.value=lang;
createApp(Page).use(i18n).use(createPinia()).mount('#app');</script>`
process.chdir(frontend) // Tailwind/PostCSS resolve the actual frontend config.
Expand Down Expand Up @@ -62,7 +63,7 @@ const errors = [], external = [], saves = [], requests = []
let saved
const groups = [{ id: 5, name: 'OpenAI 示例组', platform: 'openai', status: 'active' }, { id: 6, name: 'Anthropic 示例组', platform: 'anthropic', status: 'active' }]
try {
const context = await browser.newContext({ viewport: { width: 1280, height: 1000 } })
const context = await browser.newContext({ viewport: { width: 1280, height: 1000 }, timezoneId: 'UTC' })
await context.route('**/*', async route => {
const url = new URL(route.request().url())
if (url.origin !== 'http://127.0.0.1:4183') { external.push(url.origin); return route.abort() }
Expand All @@ -73,6 +74,11 @@ try {
if (route.request().method() === 'PUT') { saved = route.request().postDataJSON(); saves.push(structuredClone(saved)) }
data = saved ?? await route.request().frame().evaluate(() => window.fixture)
} else if (url.pathname === '/api/v1/admin/groups/all') data = groups
else if (url.pathname === '/api/v1/admin/accounts') {
assert.equal(route.request().method(), 'GET')
assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc', timezone: 'UTC' })
data = { items: [], page: 1, page_size: 100, pages: 1, total: 0 }
}
else if (url.pathname === '/api/v1/admin/groups') data = { items: groups, page: 1, page_size: 100, pages: 1, total: 2 }
else if (url.pathname === '/api/v1/admin/account-quality-plans') data = []
else if (url.pathname === '/api/v1/admin/account-ops/auto-config/events') data = { items: [], has_more: false }
Expand All @@ -91,6 +97,10 @@ try {
assert.equal(await page.getByTestId('initial-model-selection').count(), 0)
await page.getByTestId('initial-enabled').locator('xpath=ancestor::section').screenshot({ path: path.join(output, 'before-initial-template-zh.png') })
await open()
await page.getByTestId('apikey-fallback-loading').waitFor({ state: 'detached' })
assert.equal(await page.getByTestId('apikey-fallback-accounts-error').count(), 0)
assert.equal(await page.getByTestId('apikey-fallback-enabled').isChecked(), false)
assert(requests.some(request => request.path === '/api/v1/admin/accounts' && request.method === 'GET'))
const scope = page.getByTestId('initial-model-selection')
const initialSection = page.getByTestId('initial-enabled').locator('xpath=ancestor::section')
const rotation = page.getByTestId('totp-rotate-on-429')
Expand Down
15 changes: 13 additions & 2 deletions .github/scripts/oauth-initial-ws-preview.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,23 @@ import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';
import {apiClient} from '/src/api/client.ts';
import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts';
import {defaultOpenAITwoFAAdmissionConfig} from '/src/utils/openaiTwoFAAdmission.ts';
import {defaultOpenAIAPIKeyFallbackConfig} from '/src/utils/openaiAPIKeyFallback.ts';
import {defaultModelBillingConfig} from '/src/utils/modelBilling.ts';
import {defaultOAuthModelMappings} from '/src/utils/oauthModelMappings.ts';
import View from '/src/views/admin/AutoConfigView.vue';
import '/src/style.css';
const locale=new URL(location.href).searchParams.get('locale')||'zh';
await loadLocaleMessages(locale);i18n.global.locale.value=locale;
let config={enabled:false,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic-preview',openai_totp_rotate_on_429:false,openai_disable_scheduling_on_429:false,openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),excel_bps:defaultExcelBPSDefaults(),model_billing:defaultModelBillingConfig(),model_mappings:defaultOAuthModelMappings('openai')};
let config={enabled:false,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic-preview',openai_totp_rotate_on_429:false,openai_disable_scheduling_on_429:false,openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),openai_apikey_fallback:defaultOpenAIAPIKeyFallbackConfig(),openai_disable_scheduling_on_429_7d_threshold_percent:98,excel_bps:defaultExcelBPSDefaults(),model_billing:defaultModelBillingConfig(),model_mappings:defaultOAuthModelMappings('openai')};
const groups=[{id:5,name:'OpenAI Demo',platform:'openai',status:'active'},{id:6,name:'Anthropic Demo',platform:'anthropic',status:'active'}];
window.__previewRequests=[];
apiClient.defaults.adapter=async request=>{let data;window.__previewRequests.push({method:request.method,url:request.url});switch(request.url){
case '/admin/account-ops/auto-config':if(request.method==='put'){config=typeof request.data==='string'?JSON.parse(request.data):request.data;window.__saved=structuredClone(config)}data=structuredClone(config);break;
case '/admin/accounts':{
const expected={page:1,page_size:100,platform:'openai',type:'apikey',status:'active',lite:'1',sort_by:'id',sort_order:'asc',timezone:'UTC'};
if(request.method!=='get'||Object.keys(request.params||{}).length!==Object.keys(expected).length||Object.entries(expected).some(([key,value])=>request.params[key]!==value))throw Error('Unexpected preview account query');
data={items:[],page:1,page_size:100,pages:1,total:0};break;
}
case '/admin/groups/all':data=groups;break;
case '/admin/groups':data={items:groups,page:1,pages:1,page_size:100,total:groups.length};break;
case '/admin/account-quality-plans':data=[];break;
Expand Down Expand Up @@ -75,7 +81,7 @@ window.preview=mount(View,{attachTo:'#preview',global:{plugins:[createPinia(),i1
})
await server.listen()
browser = process.env.SUB2API_CDP_ENDPOINT ? await chromium.connectOverCDP(process.env.SUB2API_CDP_ENDPOINT) : await chromium.launch({ headless: true })
context = await browser.newContext({ viewport: { width: 1180, height: 1000 }, locale: 'zh-CN' })
context = await browser.newContext({ viewport: { width: 1180, height: 1000 }, locale: 'zh-CN', timezoneId: 'UTC' })
const page = await context.newPage()
page.on('pageerror', error => { errors.push(error.message); console.error(error.message) })
page.on('console', message => {
Expand All @@ -101,6 +107,11 @@ window.preview=mount(View,{attachTo:'#preview',global:{plugins:[createPinia(),i1
server.moduleGraph.invalidateAll()
await page.reload({ waitUntil: 'networkidle' })
await page.getByTestId('initial-ws-mode-select').waitFor({ timeout: 60000 })
await page.getByTestId('apikey-fallback').waitFor()
await page.getByTestId('apikey-fallback-loading').waitFor({ state: 'detached' })
if (await page.getByTestId('apikey-fallback-accounts-error').count()) throw Error('Fallback account fixture failed to load')
if (await page.getByTestId('apikey-fallback-enabled').isChecked()) throw Error('Fallback must remain disabled in the WS fixture')
if (!await page.evaluate(() => window.__previewRequests.some(request => request.method === 'get' && request.url === '/admin/accounts'))) throw Error('Missing fallback account request')
await capture('after-defaults.png')
await page.getByTestId('initial-enabled').check()
await page.getByTestId('initial-group-5').check()
Expand Down
9 changes: 9 additions & 0 deletions .github/scripts/oauth-initial-ws-screenshot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ try {
if(request.method==='put'){state.config=JSON.parse(request.data);state.writes.push(structuredClone(state.config));localStorage.setItem('fixture-oauth-ws',JSON.stringify(state.config))}
data=structuredClone(state.config);
}else if(path==='/admin/account-ops/auto-config/events')data={items:[],has_more:false};
else if(path==='/admin/accounts'&&request.method==='get'){
const params=request.params||{};
if(params.platform!=='openai'||params.type!=='apikey'||params.status!=='active'||params.lite!=='1')throw Error('Unexpected fallback account filters');
data={items:[],total:0,page:1,page_size:100,pages:1};
}
else if(path==='/admin/groups/all')data=groups;
else if(path==='/admin/groups')data={items:groups,total:1,page:1,page_size:100,pages:1};
else if(path==='/admin/account-quality-plans')data=[];
Expand Down Expand Up @@ -79,6 +84,10 @@ try {
await screenshot('before.png')
manifest.results.push({ mode, ws_controls_present: false })
} else {
await page.getByTestId('apikey-fallback-loading').waitFor({state:'detached'})
assert.equal(await page.getByTestId('apikey-fallback-accounts-error').count(), 0)
assert.equal(await page.getByTestId('apikey-fallback-enabled').isChecked(), false)
assert.equal(await page.evaluate(() => window.__oauthWSFixture.requests.some(request => request.method==='get'&&request.path==='/admin/accounts')), true)
const select = () => page.getByTestId('initial-ws-mode-select')
const acceleration = () => page.getByTestId('initial-ws-sse-acceleration-enabled')
assert.equal(await select().inputValue(), 'ctx_pool')
Expand Down
51 changes: 51 additions & 0 deletions backend/internal/handler/admin/account_auto_config_429_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,54 @@ func TestAutoConfigDisableScheduling429SaveAndLegacyClient(t *testing.T) {
})
}
}

func TestAutoConfigWeekly429ThresholdSaveValidationAndLegacyClient(t *testing.T) {
gin.SetMode(gin.TestMode)
// An old stored template still receives the safe weekly threshold default.
repo := &opsHandlerWritableSettings{raw: `{"enabled":false,"platform":"openai","openai_disable_scheduling_on_429":true}`}
cfg := &config.Config{}
cfg.Runtime.Role = config.RuntimeRoleGateway
svc := service.ProvideAccountOpsService(repo, opsHandlerQueue{}, nil, nil, modelBillingHandlerGroups{}, cfg, nil, nil, nil, nil, nil)
svc.Stop()
handler := NewAccountOpsHandler(svc, nil)
router := gin.New()
router.PUT("/config", handler.SaveAutoConfig)
router.GET("/config", handler.GetAutoConfig)
for _, tc := range []struct {
name, body string
status int
threshold float64
}{
{"legacy default", `{"priority":6}`, http.StatusOK, 98},
{"fractional value", `{"openai_disable_scheduling_on_429_7d_threshold_percent":97.5}`, http.StatusOK, 97.5},
{"legacy client preserves saved value", `{"priority":7}`, http.StatusOK, 97.5},
{"negative", `{"openai_disable_scheduling_on_429_7d_threshold_percent":-1}`, http.StatusBadRequest, 97.5},
{"over 100", `{"openai_disable_scheduling_on_429_7d_threshold_percent":100.01}`, http.StatusBadRequest, 97.5},
{"string", `{"openai_disable_scheduling_on_429_7d_threshold_percent":"98"}`, http.StatusBadRequest, 97.5},
{"null", `{"openai_disable_scheduling_on_429_7d_threshold_percent":null}`, http.StatusBadRequest, 97.5},
{"boolean", `{"openai_disable_scheduling_on_429_7d_threshold_percent":true}`, http.StatusBadRequest, 97.5},
{"zero", `{"openai_disable_scheduling_on_429_7d_threshold_percent":0}`, http.StatusOK, 0},
{"100", `{"openai_disable_scheduling_on_429_7d_threshold_percent":100}`, http.StatusOK, 100},
} {
t.Run(tc.name, func(t *testing.T) {
before := repo.raw
written := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(tc.body))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(written, request)
require.Equal(t, tc.status, written.Code, written.Body.String())
if tc.status != http.StatusOK {
require.Equal(t, before, repo.raw)
}
read := httptest.NewRecorder()
router.ServeHTTP(read, httptest.NewRequest(http.MethodGet, "/config", nil))
require.Equal(t, http.StatusOK, read.Code)
var payload struct {
Data service.OAuthAutoConfig `json:"data"`
}
require.NoError(t, json.Unmarshal(read.Body.Bytes(), &payload))
require.Equal(t, tc.threshold, payload.Data.OpenAIDisableSchedulingOn4297dThresholdPercent)
require.True(t, payload.Data.OpenAIDisableSchedulingOn429)
})
}
}
5 changes: 3 additions & 2 deletions backend/internal/handler/admin/account_auto_config_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ func (h *AccountOpsHandler) GetAutoConfig(c *gin.Context) {
}
response.Success(c, struct {
service.OAuthAutoConfig
RuntimeBlocked bool `json:"runtime_blocked"`
}{cfg, h.svc.AutoConfigBlocked()})
RuntimeBlocked bool `json:"runtime_blocked"`
OpenAIAPIKeyFallbackStatus service.OpenAIAPIKeyFallbackStatus `json:"openai_apikey_fallback_status"`
}{cfg, h.svc.AutoConfigBlocked(), h.svc.OpenAIAPIKeyFallbackStatus()})
}
func (h *AccountOpsHandler) SaveAutoConfig(c *gin.Context) {
// Preserve fields unknown to older clients, including the BPS template.
Expand Down
Loading
Loading