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
55 changes: 55 additions & 0 deletions .github/scripts/account-probe-penalty-screenshot.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Actual account setting component with synthetic state; no production access.
import { execFileSync } from 'node:child_process'
import { createRequire } from 'node:module'
import { mkdirSync, writeFileSync, rmSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
const root = resolve('frontend'), output = process.env.SCREENSHOT_DIR
if (!output || !process.env.PLAYWRIGHT_ROOT) throw Error('Missing screenshot configuration')
mkdirSync(output, { recursive: true })
const require = createRequire(join(root, 'package.json'))
const { build, preview } = await import(pathToFileURL(join(root, 'node_modules/vite/dist/node/index.js')).href)
const vue = (await import(pathToFileURL(require.resolve('@vitejs/plugin-vue')).href)).default
const { chromium } = await import(pathToFileURL(join(process.env.PLAYWRIGHT_ROOT, 'index.mjs')).href)
const tailwind = (await import(pathToFileURL(join(root, 'tailwind.config.js')).href)).default
const prefix = `.probe-penalty-${process.pid}`, files = []
const create = (name, text) => { const path = join(root, name); writeFileSync(path, text, { flag: 'wx' }); files.push(path); return path }
let server, browser
try {
const html = create(prefix + '.html', `<html lang="zh"><meta charset="utf-8"><div id="app"></div><script type="module" src="./${prefix}.js"></script></html>`)
create(prefix + '.js', `
import {createApp,defineComponent,ref,h} from 'vue'; import {createPinia} from 'pinia'; import {createI18n} from 'vue-i18n';
import {useAuthStore} from '/src/stores/auth.ts'; import Setting from '/src/components/account/ProbePenaltySettings.vue';
import zh from '/src/i18n/locales/zh/index.ts'; import '/src/style.css';
const app=createApp(defineComponent({setup(){const enabled=ref(false),minimum=ref(.001);return()=>h('main',{class:'p-6 bg-white dark:bg-dark-900'},[h('h1',{class:'text-lg mb-4 dark:text-white'},'账号管理 / 编辑虚构 Claude 账号'),h(Setting,{enabled:enabled.value,minimum:minimum.value,'onUpdate:enabled':v=>enabled.value=v,'onUpdate:minimum':v=>minimum.value=v})])}}));
const pinia=createPinia();app.use(pinia);useAuthStore().user={id:41,role:'admin',email:'admin@example.invalid'};
app.use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}})).mount('#app');
`)
await build({ root, configFile: false, base: './', resolve: { alias: { '@': join(root, 'src') } }, plugins: [vue()],
css: { postcss: { plugins: [require('tailwindcss')({ ...tailwind, content: [html, join(root, 'src/**/*.{vue,js,ts}')] }), require('autoprefixer')()] } },
build: { outDir: join(output, 'build'), emptyOutDir: true, rollupOptions: { input: html } } })
server = await preview({ root, configFile: false, build: { outDir: join(output, 'build') }, preview: { host: '127.0.0.1', port: 4198, strictPort: true } })
browser = await chromium.launch({ headless: true })
const page = await browser.newPage({ viewport: { width: 1000, height: 620 } }), errors = []
page.on('pageerror', e => errors.push(e.message))
await page.route('**/*', route => new URL(route.request().url()).origin === 'http://127.0.0.1:4198' ? route.continue() : route.abort())
await page.goto(`http://127.0.0.1:4198/${prefix}.html`)
const card = page.locator('[data-testid="probe-penalty-settings"]')
await card.waitFor()
await page.locator('main').screenshot({ path: join(output, 'disabled.png') })
await page.locator('[data-testid="probe-penalty-enabled"]').check()
if (await page.locator('[data-testid="probe-penalty-minimum"]').inputValue() !== '0.001') throw Error('Wrong default minimum')
await page.locator('main').screenshot({ path: join(output, 'enabled.png') })
await page.evaluate(() => document.documentElement.classList.add('dark'))
await page.locator('main').screenshot({ path: join(output, 'dark.png') })
await card.locator('[data-testid="new-feature-badge"]').click()
await page.reload(); await card.waitFor()
if (await card.locator('[data-testid="new-feature-badge"]').count()) throw Error('Dismissal did not persist')
if (errors.length) throw Error(errors.join('\n'))
writeFileSync(join(output, 'manifest.json'), JSON.stringify({ commit: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), scope: 'actual ProbePenaltySettings component with synthetic parent state, not full account page or production', screenshots: ['disabled.png', 'enabled.png', 'dark.png'], errors }, null, 2))
} finally {
if (browser) await browser.close()
if (server) await new Promise(resolve => server.httpServer.close(resolve))
for (const file of files) rmSync(file, { force: true })
rmSync(join(output, 'build'), { recursive: true, force: true })
}
1 change: 1 addition & 0 deletions .github/scripts/prepare-image-usage-free-fast-red.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# backporting either the cache-price producer or UltraFast behavior.
addition = ('\n\tImageMinimumCharge float64 `json:"image_minimum_charge,omitempty"`\n'
'\tImageMinimumChargeAdjustment float64 `json:"image_minimum_charge_adjustment,omitempty"`\n'
'\tProbePenalty *ProbePenaltyReceipt `json:"probe_penalty,omitempty"`\n'
'\tFreeUltrafast bool `json:"free_ultrafast,omitempty"`\n'
'\tCacheCostDetails []CustomerCacheCostDetail `json:"cache_cost_details,omitempty"`\n')
else:
Expand Down
4 changes: 4 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,7 @@ backend/internal/service/ciallo_test.go
# Controls diagnostics require the newer recovery APIs, not historical RED sources.
backend/internal/service/openai_409_controls_diagnostics_test.go
backend/internal/handler/openai_owner_conflict_diagnostics_test.go

# Probe penalty tests use receipt types absent from historical WS sources.
backend/internal/handler/probe_penalty_response_test.go
backend/internal/service/account_probe_penalty_test.go
42 changes: 42 additions & 0 deletions .github/workflows/account-probe-penalty.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Account probe penalty UI
on:
workflow_dispatch:
pull_request:
branches: [production]
paths:
- 'frontend/src/components/account/ProbePenaltySettings.vue'
- '.github/scripts/account-probe-penalty-screenshot.mjs'
- '.github/workflows/account-probe-penalty.yml'
permissions:
contents: read
jobs:
screenshots:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- run: pnpm --dir frontend install --frozen-lockfile
- name: Install isolated browser
run: |
npm install --prefix "$RUNNER_TEMP/probe-browser" --no-save --ignore-scripts playwright@1.56.1
"$RUNNER_TEMP/probe-browser/node_modules/.bin/playwright" install --with-deps chromium
- name: Render actual account setting
env:
PLAYWRIGHT_ROOT: ${{ runner.temp }}/probe-browser/node_modules/playwright
SCREENSHOT_DIR: ${{ runner.temp }}/probe-ui
run: node .github/scripts/account-probe-penalty-screenshot.mjs
- uses: actions/upload-artifact@v7
if: always()
with:
name: account-probe-penalty-ui-${{ github.event.pull_request.head.sha || github.sha }}
path: ${{ runner.temp }}/probe-ui
12 changes: 10 additions & 2 deletions backend/internal/handler/gateway_compat_stream_usage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func runCompatStreamUsageHandler(t *testing.T, endpoint, upstreamStream string,
return runCompatStreamUsageHandlerWithDelivery(t, endpoint, upstreamStream, closeUpstream, nil, "")
}

func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStream string, closeUpstream bool, durable service.UsageBillingRepository, baseURL string) compatStreamUsageRun {
func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStream string, closeUpstream bool, durable service.UsageBillingRepository, baseURL string, accountExtra ...map[string]any) compatStreamUsageRun {
t.Helper()
cfg := &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 1}}
cfg.Security.URLAllowlist.AllowPrivateHosts = true
Expand All @@ -85,6 +85,9 @@ func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStr
Credentials: map[string]any{"api_key": "test-key"},
AccountGroups: []service.AccountGroup{{AccountID: 9301, GroupID: groupID}},
}
if len(accountExtra) > 0 {
account.Extra = accountExtra[0]
}
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil)
run := compatStreamUsageRun{
rec: httptest.NewRecorder(),
Expand Down Expand Up @@ -126,6 +129,9 @@ func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStr
}

body := `{"model":"claude-sonnet-4.5","stream":true,"input":"hello"}`
if endpoint == "messages" {
body = `{"model":"claude-sonnet-4.5","stream":true,"max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`
}
if endpoint == "chat/completions" {
body = `{"model":"claude-sonnet-4.5","stream":true,"messages":[{"role":"user","content":"hello"}]}`
}
Expand All @@ -136,7 +142,9 @@ func runCompatStreamUsageHandlerWithDelivery(t *testing.T, endpoint, upstreamStr
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9303})

if endpoint == "chat/completions" {
if endpoint == "messages" {
h.Messages(c)
} else if endpoint == "chat/completions" {
h.ChatCompletions(c)
} else {
h.Responses(c)
Expand Down
70 changes: 59 additions & 11 deletions backend/internal/handler/gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -926,12 +926,52 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
writerSizeBeforeForward := c.Writer.Size()
var probeResponse *probePenaltyResponse
if account.ProbePenaltyMinimum() > 0 {
if !h.gatewayService.ProbePenaltySettlementEnabled() {
if queueRelease != nil {
queueRelease()
}
if accountReleaseFunc != nil {
accountReleaseFunc()
}
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "Probe penalty requires durable settlement", streamStarted)
return
}
probeResponse, err = newProbePenaltyResponse(c.Writer, attemptParsedReq.Stream)
if err != nil {
if queueRelease != nil {
queueRelease()
}
if accountReleaseFunc != nil {
accountReleaseFunc()
}
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "Probe penalty response unavailable", streamStarted)
return
}
defer probeResponse.close()
c.Writer = probeResponse
}
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession)
} else {
result, err = h.gatewayService.Forward(requestCtx, c, account, attemptParsedReq)
}

if probeResponse != nil {
c.Writer = probeResponse.ResponseWriter
if err == nil {
err = probeResponse.validate()
}
if err != nil && probeResponse.size >= 0 {
if probeResponse.status >= http.StatusBadRequest {
_ = probeResponse.finish(nil)
} else {
probeResponse.settlementError()
}
}
}

// 兜底释放串行锁(正常情况已通过回调提前释放)
if queueRelease != nil {
queueRelease()
Expand Down Expand Up @@ -975,8 +1015,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
forceCacheBilling := fs.ForceCacheBilling
quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey)
sessionID := service.ExtractClientSessionID(c)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
record := func(ctx context.Context) error {
return h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
QuotaPlatform: quotaPlatform,
APIKey: currentAPIKey,
Expand All @@ -993,15 +1033,23 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
ForceCacheBilling: forceCacheBilling,
APIKeyService: h.apiKeyService,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
}); err != nil {
logger.L().With(
zap.String("component", "handler.gateway.messages"),
zap.Int64("user_id", subject.UserID),
zap.Int64("api_key_id", currentAPIKey.ID),
zap.Any("group_id", currentAPIKey.GroupID),
zap.String("model", reqModel),
zap.Int64("account_id", account.ID),
).Error("gateway.record_usage_failed", zap.Error(err))
})
}
if probeResponse != nil && err == nil {
result.ProbePenaltyEligible = true
if billingErr := record(service.WithProbePenaltyResult(context.WithoutCancel(c.Request.Context()), result)); billingErr != nil {
reqLog.Error("gateway.probe_penalty_settlement_failed", zap.Error(billingErr))
probeResponse.settlementError()
return
}
if responseErr := probeResponse.finish(result); responseErr != nil {
reqLog.Error("gateway.probe_penalty_response_failed", zap.Error(responseErr))
}
return
}
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if billingErr := record(ctx); billingErr != nil {
reqLog.Error("gateway.record_usage_failed", zap.Error(billingErr))
}
})
}
Expand Down
60 changes: 53 additions & 7 deletions backend/internal/handler/gateway_handler_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,26 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
var result *service.ForwardResult
setActualUpstreamEndpoint(c, "")
var probeResponse *probePenaltyResponse
if account.ProbePenaltyMinimum() > 0 {
if !h.gatewayService.ProbePenaltySettlementEnabled() {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", "Probe penalty requires durable settlement")
return
}
probeResponse, err = newProbePenaltyResponse(c.Writer, reqStream)
if err != nil {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", "Probe penalty response unavailable")
return
}
defer probeResponse.close()
c.Writer = probeResponse
}
if account.Platform == service.PlatformGemini {
if h.geminiCompatService == nil {
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Gemini compatibility service is not configured")
Expand All @@ -329,6 +349,20 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
result, err = h.gatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, parsedReq)
}

if probeResponse != nil {
c.Writer = probeResponse.ResponseWriter
if err == nil {
err = probeResponse.validate()
}
if err != nil && probeResponse.size >= 0 {
if probeResponse.status >= http.StatusBadRequest {
_ = probeResponse.finish(nil)
} else {
probeResponse.settlementError()
}
}
}

if accountReleaseFunc != nil {
accountReleaseFunc()
}
Expand All @@ -348,8 +382,8 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
record := func(ctx context.Context) error {
return h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
QuotaPlatform: quotaPlatform,
APIKey: apiKey,
Expand All @@ -365,11 +399,23 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
APIKeyService: h.apiKeyService,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
}); err != nil {
reqLog.Error("gateway.cc.record_usage_failed",
zap.Int64("account_id", account.ID),
zap.Error(err),
)
})
}
if probeResponse != nil && err == nil {
result.ProbePenaltyEligible = true
if billingErr := record(service.WithProbePenaltyResult(context.WithoutCancel(c.Request.Context()), result)); billingErr != nil {
reqLog.Error("gateway.probe_penalty_settlement_failed", zap.Error(billingErr))
probeResponse.settlementError()
return
}
if responseErr := probeResponse.finish(result); responseErr != nil {
reqLog.Error("gateway.probe_penalty_response_failed", zap.Error(responseErr))
}
return
}
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if billingErr := record(ctx); billingErr != nil {
reqLog.Error("gateway.record_usage_failed", zap.Error(billingErr))
}
})
}
Expand Down
Loading
Loading