Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
ef51690
fix(antigravity): preserve string const constraints in tool schemas
Achordchan Sep 20, 2026
f867e3e
test(antigravity): check schema properties type assertion
Achordchan Sep 22, 2026
1af3269
fix(groups): clean up modal listeners and pending searches
ouchihao Sep 22, 2026
b5b5f1f
fix(model-plaza): apply independent video billing multipliers
Achordchan Sep 23, 2026
17ce21c
test(scheduler): pass explicit multiplier pointer to snapshot
Achordchan Sep 23, 2026
ecba49f
fix(gateway): let OpenAI passthrough accounts supplement model discov…
HuntercodeT Sep 23, 2026
2fc9166
fix(apicompat): honor disabled thinking in OpenAI bridges
TouHouQing Sep 23, 2026
00f6f4e
fix(ccswitch): stop usage query from requesting /v1/v1/usage
helianthus1 Sep 23, 2026
1ca7b2a
fix(scheduler): keep auto reset-credit fields in the scheduler projec…
Yukinoshita-Yukino Sep 23, 2026
5979521
fix(openai): inject DeepSeek reasoning placeholder for OpenCode Zen u…
william-drakemond Sep 22, 2026
82b092f
fix(apicompat): treat every GPT generation from 5 on as a reasoning m…
SPHINX998 Sep 24, 2026
090b2cc
fix(apicompat): recover streamed text when the final output message i…
SPHINX998 Sep 24, 2026
97bdde3
fix(apicompat): keep tool arguments sent on content_block_start
SPHINX998 Sep 24, 2026
a2007db
fix(billing): keep catalog image prices when channel pricing leaves t…
Yukinoshita-Yukino Sep 24, 2026
9461196
fix(openai): keep Responses support unknown when the probe model is m…
SPHINX998 Sep 24, 2026
1d126c8
fix(openai): require a successful completion before billing an alpha …
SPHINX998 Sep 24, 2026
ca2746f
fix(antigravity): forward chat PDF file parts as Gemini inlineData
ResidualBlood Sep 24, 2026
f0ebc18
feat(groups): allow wildcard positions in model allowlist
wucm667 Sep 25, 2026
8581036
fix(auto-reset): stop re-querying confirmed no-credit accounts and ba…
Yukinoshita-Yukino Sep 25, 2026
11ffee5
fix: recognize OpenRouter Claude Opus 5.5 alias for billing
far5man Sep 25, 2026
630639f
test: preserve Opus 5.5 thinking for OpenRouter alias
far5man Sep 25, 2026
52c2f4c
fix(antigravity): trigger failover retry on empty stream caused by MA…
ResidualBlood Sep 26, 2026
f91a683
Add multiple timezones to openai_request_timezones.txt
mofelee Sep 26, 2026
afbe51a
Merge upstream main and retain string const enum intersection
Achordchan Sep 26, 2026
510b680
Merge upstream main and retain upstream scheduler test fix
Achordchan Sep 26, 2026
f4f8ff0
fix(gateway): 客户端断开统一标记 499,不再被记成 502/200 上游错误
feeeei Sep 26, 2026
c802c45
fix(deploy): 用 exec 列表形式重写 redis command
nhirsama Sep 26, 2026
994048e
fix(ui): show reset countdown for idle usage windows with known reset…
ZeroClover Sep 26, 2026
3c5ea29
fix(billing): keep zero-cost usage log when Free Fast has no pricing
yujunkim Sep 26, 2026
7626110
fix(openai): break websocket chain on context rollover
UnlastingR Sep 26, 2026
5c3cfa0
Merge pull request #19 from mofelee/patch-1
MACOSDO Sep 26, 2026
8b95dc9
fix(openai): preserve Responses multi-agent beta
korkin25 Sep 27, 2026
fd7af1d
fix(billing): honor long-context gate in account stats pricing
SavitarC Sep 27, 2026
14483c9
fix(ccswitch): preserve Codex provider root endpoint
Sep 27, 2026
02088be
fix(openai): retain quota pause until known future reset
wucm667 Sep 27, 2026
6b40449
fix(antigravity): exclude Signature-only events from meaningful data …
ResidualBlood Sep 27, 2026
f652d0e
fix(keys): use ~/ for the Codex model catalog path on Windows
Sterbennicht Sep 27, 2026
82d2552
fix(apicompat): mark converted role items as messages
wucm667 Sep 28, 2026
f45126c
Merge pull request #7622 from Anti2077/fix/ccswitch-codex-root-endpoint
Wei-Shaw Sep 28, 2026
512aa8b
fix(setup): omit obsolete rate limit defaults
wucm667 Sep 28, 2026
35d2ef0
Merge pull request #7636 from wucm667/fix/issue-7631-remove-unused-ra…
Wei-Shaw Sep 28, 2026
ec334fd
Merge pull request #7628 from Sterbennicht/fix/codex-windows-catalog-…
Wei-Shaw Sep 28, 2026
99d86e4
Merge pull request #7611 from ZeroClover/fix/usage-bar-idle-reset-time
Wei-Shaw Sep 28, 2026
89e9976
Merge pull request #7497 from ouchihao/codex/bug-group-modal-cleanup
Wei-Shaw Sep 28, 2026
66f07ef
Merge pull request #7549 from helianthus1/fix/ccswitch-usage-v1-path
Wei-Shaw Sep 28, 2026
be64b55
Merge pull request #7635 from wucm667/fix/issue-7629-responses-messag…
Wei-Shaw Sep 28, 2026
6655f4e
Merge pull request #7393 from Achordchan/fix/antigravity-string-const
Wei-Shaw Sep 28, 2026
51a10e4
Merge pull request #7585 from ResidualBlood/fix/antigravity-pdf-inlin…
Wei-Shaw Sep 28, 2026
00ae7c3
Merge pull request #7570 from SPHINX998/fix/apicompat-tool-input-on-b…
Wei-Shaw Sep 28, 2026
8aa7fb8
Merge pull request #7569 from SPHINX998/fix/apicompat-recover-empty-f…
Wei-Shaw Sep 28, 2026
11608c5
Merge pull request #7568 from SPHINX998/fix/apicompat-gpt6-reasoning-…
Wei-Shaw Sep 28, 2026
dc4874a
Merge pull request #7613 from yujunkim/fix/openai-free-fast-missing-p…
Wei-Shaw Sep 28, 2026
6906062
Merge pull request #7597 from far5man/codex/opus55-openrouter-alias-main
Wei-Shaw Sep 28, 2026
06f70a6
Merge pull request #7572 from SPHINX998/fix/openai-alpha-search-requi…
Wei-Shaw Sep 28, 2026
9375e28
Merge pull request #7571 from SPHINX998/fix/openai-probe-model-unavai…
Wei-Shaw Sep 28, 2026
90ae81e
Merge pull request #7624 from wucm667/fix/issue-7620-future-quota-reset
Wei-Shaw Sep 28, 2026
e4b3444
Merge pull request #7619 from SavitarC/fix/account-stats-long-context…
Wei-Shaw Sep 28, 2026
37f35b1
Merge pull request #7524 from Achordchan/fix/plaza-video-rate
Wei-Shaw Sep 28, 2026
f592b33
Merge pull request #7595 from wucm667/feat/issue-7587-allowlist-glob
Wei-Shaw Sep 28, 2026
1ff2bd6
Merge pull request #7573 from Yukinoshita-Yukino/fix/channel-image-pr…
Wei-Shaw Sep 28, 2026
790723e
Merge pull request #7610 from nhirsama/fix/redis-command-exec-form
Wei-Shaw Sep 28, 2026
79c18ec
Merge pull request #7609 from feeeei/fix/client-disconnect-499
Wei-Shaw Sep 28, 2026
ff6b85e
Merge pull request #7615 from UnlastingR/fix/codex-ws-context-rollove…
Wei-Shaw Sep 28, 2026
68c2f5a
fix(anthropic): preserve requested structured outputs beta
Achordchan Sep 28, 2026
93c3da0
Merge pull request #7555 from Yukinoshita-Yukino/fix/openai-auto-rese…
Wei-Shaw Sep 28, 2026
8616d4e
Merge pull request #7617 from korkin25/fix/responses-beta-upstream
Wei-Shaw Sep 28, 2026
b3c7038
Merge pull request #7526 from HuntercodeT/fix/passthrough-model-disco…
Wei-Shaw Sep 28, 2026
1df5c39
Merge pull request #7562 from william-drakemond/fix/opencode-zen-deep…
Wei-Shaw Sep 28, 2026
5a35010
Merge pull request #7607 from ResidualBlood/fix/antigravity-malformed…
Wei-Shaw Sep 28, 2026
b5298fd
Merge pull request #7538 from TouHouQing/fix/claude-thinking-disabled…
Wei-Shaw Sep 28, 2026
4c00df2
Merge pull request #7638 from Achordchan/fix/anthropic-structured-out…
Wei-Shaw Sep 28, 2026
9a62841
chore: sync VERSION to 0.2.9 [skip ci]
github-actions[bot] Sep 28, 2026
bcccc9b
chore(release): merge SUB2API 0.2.9 for 1.1.6
Sep 28, 2026
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
2 changes: 1 addition & 1 deletion backend/cmd/server/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.1.5
1.1.6
10 changes: 7 additions & 3 deletions backend/internal/handler/admin/account_request_timezone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ func TestGetOpenAIRequestTimezones(t *testing.T) {
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
require.Equal(t, service.DefaultOpenAIRequestTimezone, payload.Data.Default)
require.Len(t, payload.Data.Timezones, 30)
require.Greater(t, len(payload.Data.Timezones), 30)
require.Equal(t, service.OpenAIRequestTimezoneOptions(), payload.Data.Timezones)
require.Contains(t, payload.Data.Timezones, "Europe/London")
require.NotContains(t, payload.Data.Timezones, "Europe/Oslo")
require.NotContains(t, payload.Data.Timezones, "Asia/Shanghai")
require.Contains(t, payload.Data.Timezones, "Europe/Oslo")
require.Contains(t, payload.Data.Timezones, "Asia/Shanghai")
require.Contains(t, payload.Data.Timezones, "Asia/Hong_Kong")
require.Contains(t, payload.Data.Timezones, "Asia/Taipei")
require.NotContains(t, payload.Data.Timezones, "Invalid/Timezone")
}
65 changes: 65 additions & 0 deletions backend/internal/handler/concurrency_error_response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package handler

import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -73,3 +76,65 @@ func TestConcurrencyErrorResponse(t *testing.T) {
})
}
}

func TestGoogleConcurrencyError(t *testing.T) {
tests := []struct {
name string
err error
wantStatus int
wantGStatus string
wantMessage string
}{
{
name: "client cancellation is 499",
err: context.Canceled,
wantStatus: statusClientClosedRequest,
wantGStatus: "CANCELLED",
wantMessage: "context canceled",
},
{
name: "full wait queue is 429",
err: &WaitQueueFullError{SlotType: "user"},
wantStatus: http.StatusTooManyRequests,
wantGStatus: "RESOURCE_EXHAUSTED",
wantMessage: "Too many pending requests, please retry later",
},
{
name: "slot wait timeout is 429",
err: &ConcurrencyError{SlotType: "user", IsTimeout: true},
wantStatus: http.StatusTooManyRequests,
wantGStatus: "RESOURCE_EXHAUSTED",
wantMessage: "Concurrency limit exceeded for user, please retry later",
},
{
name: "acquire backend error is 503",
err: errors.New("redis unavailable"),
wantStatus: http.StatusServiceUnavailable,
wantGStatus: "INTERNAL",
wantMessage: "Service temporarily unavailable, please retry later",
},
}

gin.SetMode(gin.TestMode)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)

googleConcurrencyError(c, tt.err, "user")

require.Equal(t, tt.wantStatus, rec.Code)
var body struct {
Error struct {
Code int `json:"code"`
Message string `json:"message"`
Status string `json:"status"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
require.Equal(t, tt.wantStatus, body.Error.Code)
require.Equal(t, tt.wantGStatus, body.Error.Status)
require.Equal(t, tt.wantMessage, body.Error.Message)
})
}
}
13 changes: 13 additions & 0 deletions backend/internal/handler/gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
for {
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err))
return
}
if len(fs.FailedAccountIDs) == 0 {
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, service.PlatformGemini)
if !cls.ModelNotFound {
Expand Down Expand Up @@ -660,6 +664,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
)
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err))
return
}
if len(fs.FailedAccountIDs) == 0 {
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, currentAPIKey, reqModel, reqModel, platform)
if !cls.ModelNotFound {
Expand Down Expand Up @@ -1988,10 +1996,15 @@ func (h *GatewayHandler) handleStreamingAwareErrorWithCode(c *gin.Context, statu
// Writer 已被写过时(ping 已 flush)走 streamStarted 分支,
// 让 handleStreamingAwareError 通过 SSE 发协议合规的终止事件,
// 否则下游收到的就是 silent EOF。
// 客户端已断开时不补写,响应未提交则标记 499(见 failoverClientGone)。
func (h *GatewayHandler) ensureForwardErrorResponse(c *gin.Context, streamStarted bool) bool {
if c == nil || c.Writer == nil {
return false
}
if c.Request != nil && errors.Is(c.Request.Context().Err(), context.Canceled) {
failoverClientGone(c)
return false
}
if service.IsResponseCommitted(c) {
return false
}
Expand Down
2 changes: 2 additions & 0 deletions backend/internal/handler/gateway_handler_cancellation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ func TestGatewayHandlerPreCancelledCompatibleRequestsDoNotSelectAccount(t *testi
require.Zero(t, schedulerCache.snapshotCalls.Load(), "a cancelled request must stop before the account selector")
_, selected := c.Get(opsAccountIDKey)
require.False(t, selected)
require.Equal(t, statusClientClosedRequest, c.Writer.Status(), "an uncommitted cancelled request is marked 499")
require.Zero(t, recorder.Body.Len())
})
}
}
6 changes: 5 additions & 1 deletion backend/internal/handler/gateway_handler_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,15 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}

for {
if c.Request.Context().Err() != nil {
if failoverClientGone(c) {
return
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err))
return
}
if len(fs.FailedAccountIDs) == 0 {
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, groupPlatform)
cls = classifySelectionFailureError(err, cls)
Expand Down
38 changes: 38 additions & 0 deletions backend/internal/handler/gateway_handler_error_fallback_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handler

import (
"context"
"encoding/json"
"errors"
"net/http"
Expand Down Expand Up @@ -70,6 +71,43 @@ func TestGatewayEnsureForwardErrorResponse_SkipsCommittedSSEError(t *testing.T)
require.Equal(t, 1, strings.Count(w.Body.String(), "event: error"))
}

// 客户端已断开且响应未提交:不补写 502,标记 499 供访问日志与 ops 归类。
func TestGatewayEnsureForwardErrorResponse_SkipsCanceledClient(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
ctx, cancel := context.WithCancel(context.Background())
c.Request = httptest.NewRequest(http.MethodPost, EndpointMessages, nil).WithContext(ctx)
cancel()

h := &GatewayHandler{}
wrote := h.ensureForwardErrorResponse(c, false)

require.False(t, wrote)
require.Equal(t, statusClientClosedRequest, c.Writer.Status())
require.Empty(t, w.Body.String())
}

// 客户端已断开但流已开始:状态码已固化为 200,不再向断开的连接追加错误帧。
func TestGatewayEnsureForwardErrorResponse_CanceledClientAfterStreamStartedAppendsNothing(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
ctx, cancel := context.WithCancel(context.Background())
c.Request = httptest.NewRequest(http.MethodPost, EndpointMessages, nil).WithContext(ctx)
c.Header("Content-Type", "text/event-stream")
_, _ = c.Writer.WriteString(":\n\n")
cancel()

h := &GatewayHandler{}
wrote := h.ensureForwardErrorResponse(c, true)

require.False(t, wrote)
require.Equal(t, http.StatusOK, c.Writer.Status())
require.Equal(t, ":\n\n", w.Body.String())
require.Empty(t, service.GetOpsStreamErrors(c))
}

// case B 回归:Anthropic-backed /responses,Writer 已被写过时
// ensureForwardErrorResponse 仍要发 response.failed。
func TestGatewayEnsureForwardErrorResponse_ResponsesRouteAfterWrittenEmitsResponseFailed(t *testing.T) {
Expand Down
6 changes: 5 additions & 1 deletion backend/internal/handler/gateway_handler_responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,15 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
fs := NewFailoverState(h.maxAccountSwitches, false)

for {
if requestCtx.Err() != nil {
if failoverClientGone(c) {
return
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(requestCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if failoverClientGone(c) {
reqLog.Info("gateway.responses.account_select_aborted_client_disconnected", zap.Error(err))
return
}
if len(fs.FailedAccountIDs) == 0 {
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, effectiveAPIKeyPlatform(c, apiKey))
cls = classifySelectionFailureError(err, cls)
Expand Down
12 changes: 12 additions & 0 deletions backend/internal/handler/gateway_models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,18 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T
accounts: accounts[1:],
want: []string{sparkModel, alias},
},
{
// A passthrough account with a stale mapping behaves like an unmapped
// one: it adds the defaults but never its own mapping keys, and it no
// longer hides the aliases declared on ordinary accounts.
name: "passthrough account contributes defaults without hiding mapped aliases",
accounts: append([]service.Account{{
ID: 5, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth,
Credentials: map[string]any{"model_mapping": map[string]any{"stale-model": "stale-model"}},
Extra: map[string]any{"openai_passthrough": true},
}}, accounts[1:]...),
want: append(openai.DefaultModelIDs(), alias),
},
{
name: "unmapped accounts from another platform do not add defaults",
accounts: append([]service.Account{{ID: 4, Platform: service.PlatformAnthropic}}, accounts[1:]...),
Expand Down
130 changes: 130 additions & 0 deletions backend/internal/handler/gemini_client_cancel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
//go:build unit

package handler

import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"net/url"
"sync/atomic"
"testing"

"github.com/MACOS-DO/sub4api/internal/config"
"github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
middleware "github.com/MACOS-DO/sub4api/internal/server/middleware"
"github.com/MACOS-DO/sub4api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)

// clientCancelUpstream 模拟上游尚未响应时客户端断开:Do 期间取消请求 context,
// 并按 net/http 的形态返回包裹 context.Canceled 的 *url.Error。
type clientCancelUpstream struct {
service.HTTPUpstream
cancel context.CancelFunc
calls atomic.Int32
}

func (u *clientCancelUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.calls.Add(1)
u.cancel()
return nil, &url.Error{Op: "Post", URL: req.URL.String(), Err: context.Canceled}
}

type geminiClientCancelFixture struct {
handler *GatewayHandler
group *service.Group
apiKey *service.APIKey
upstream *clientCancelUpstream
ctx context.Context
}

func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
t.Helper()
groupID := int64(9200)
accountID := int64(9201)
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive}
account := &service.Account{
ID: accountID,
Platform: service.PlatformGemini,
Type: service.AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "test-key"},
Status: service.StatusActive,
Schedulable: true,
Concurrency: 1,
Priority: 1,
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}},
}
h, cleanup := newTestGatewayHandler(t, group, []*service.Account{account})
t.Cleanup(cleanup)

ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
upstream := &clientCancelUpstream{cancel: cancel}
h.geminiCompatService = service.NewGeminiMessagesCompatService(nil, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})

apiKey := &service.APIKey{
ID: 9202, UserID: 9203, GroupID: &groupID, Group: group, Status: service.StatusActive,
User: &service.User{ID: 9203, Concurrency: 10, Balance: 100},
}
return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, ctx: ctx}
}

// serve 经 ops 错误日志中间件执行请求,返回响应与 ops 队列中的条目数。
func (f *geminiClientCancelFixture) serve(t *testing.T, route, path, body string, call func(*gin.Context)) (*httptest.ResponseRecorder, int64) {
t.Helper()
setupOpsErrorLogTestQueue(t, 4)
ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.Use(OpsErrorLoggerMiddleware(ops))
router.POST(route, func(c *gin.Context) {
c.Set(string(middleware.ContextKeyAPIKey), f.apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: f.apiKey.UserID, Concurrency: 10})
call(c)
})

req := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(body))
req = req.WithContext(context.WithValue(f.ctx, ctxkey.Group, f.group))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
return rec, OpsErrorLogQueueLength()
}

// 原生入口:上游响应前客户端断开,响应未提交,标记 499;纯客户端取消不落 ops 错误日志。
func TestGeminiV1BetaModels_ClientCancelBeforeUpstreamResponseMarks499(t *testing.T) {
gin.SetMode(gin.TestMode)
f := newGeminiClientCancelFixture(t)

rec, opsQueued := f.serve(t,
"/v1beta/models/*modelAction",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
f.handler.GeminiV1BetaModels,
)

require.Equal(t, int32(1), f.upstream.calls.Load())
require.Equal(t, statusClientClosedRequest, rec.Code)
require.Zero(t, rec.Body.Len())
require.Zero(t, opsQueued)
}

// Chat Completions 兼容入口(Gemini 分组):同一场景标记 499,不再补写 502。
func TestGatewayChatCompletions_GeminiClientCancelBeforeUpstreamResponseMarks499(t *testing.T) {
gin.SetMode(gin.TestMode)
f := newGeminiClientCancelFixture(t)

rec, opsQueued := f.serve(t,
"/v1/chat/completions",
"/v1/chat/completions",
`{"model":"gemini-2.5-flash","messages":[{"role":"user","content":"hi"}],"stream":true}`,
f.handler.ChatCompletions,
)

require.Equal(t, int32(1), f.upstream.calls.Load())
require.Equal(t, statusClientClosedRequest, rec.Code)
require.Zero(t, rec.Body.Len())
require.Zero(t, opsQueued)
}
Loading
Loading