diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go
index 8899c2d70d..2977fc76b7 100644
--- a/backend/internal/service/account.go
+++ b/backend/internal/service/account.go
@@ -971,7 +971,13 @@ func (a *Account) isModelMappingSupported(requestedModel string) bool {
// credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被
// model_mapping 白名单错误排除出候选集,导致 no available accounts / 404(issue #4936)。
if a.IsOpenAIPassthroughEnabled() {
- return true
+ if !a.IsOpenAIPassthroughModelFilterEnabled() {
+ return true
+ }
+ // Explicit opt-in filters candidates by source keys only. Forward still
+ // ignores mapping targets and preserves the passthrough request body.
+ mapping := a.GetModelMapping()
+ return len(mapping) == 0 || mappingSupportsRequestedModel(mapping, strings.TrimSpace(requestedModel))
}
mapping := a.GetModelMapping()
if len(mapping) == 0 {
@@ -2198,6 +2204,13 @@ func (a *Account) IsOpenAIPassthroughEnabled() bool {
return false
}
+// IsOpenAIPassthroughModelFilterEnabled reports the explicit opt-in to model
+// filtering during passthrough account selection. Missing or invalid values
+// preserve the default behavior of ignoring leftover model_mapping entries.
+func (a *Account) IsOpenAIPassthroughModelFilterEnabled() bool {
+ return a.IsOpenAIPassthroughEnabled() && a.Extra["openai_passthrough_model_filter"] == true
+}
+
// IsOpenAIResponsesWebSocketV2Enabled 返回 OpenAI 账号是否开启 Responses WebSocket v2。
//
// 分类型新字段:
diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go
index b1219980e7..5d7b24a374 100644
--- a/backend/internal/service/gateway_scheduling.go
+++ b/backend/internal/service/gateway_scheduling.go
@@ -2664,8 +2664,8 @@ func (s *GatewayService) isModelSupportedByAccount(account *Account, requestedMo
_, ok := ResolveBedrockModelID(account, requestedModel)
return ok
}
- // OpenAI 透传模式:仅替换认证,允许所有模型
- if account.Platform == PlatformOpenAI && account.IsOpenAIPassthroughEnabled() {
+ // Passthrough ignores leftover mappings unless model filtering is enabled.
+ if account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() {
return true
}
// OAuth/SetupToken 账号使用 Anthropic 标准映射(短ID → 长ID)
diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go
index e6e8131009..53c8c702e2 100644
--- a/backend/internal/service/gateway_service.go
+++ b/backend/internal/service/gateway_service.go
@@ -1443,12 +1443,12 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
hasAnyMapping := false
for _, acc := range accounts {
- // Passthrough routing accepts models independently of model_mapping, so a
+ // Default passthrough accepts models independently of model_mapping, so a
// stale mapping on a passthrough account must not narrow the public list.
// Treat it like an unmapped account: skip its mapping here and let
// supplementUnmappedOpenAIModels contribute the default set. Mappings on
// the ordinary accounts in the same group still count.
- if platform == PlatformOpenAI && acc.IsOpenAIPassthroughEnabled() {
+ if platform == PlatformOpenAI && acc.IsOpenAIPassthroughEnabled() && !acc.IsOpenAIPassthroughModelFilterEnabled() {
continue
}
diff --git a/backend/internal/service/group_model_allowlist.go b/backend/internal/service/group_model_allowlist.go
index cac5be04e7..4dd3ab5cf3 100644
--- a/backend/internal/service/group_model_allowlist.go
+++ b/backend/internal/service/group_model_allowlist.go
@@ -29,9 +29,8 @@ func GroupModelAllowlistFromDomain(cfg domain.GroupModelAllowlist) GroupModelAll
}
// supplementUnmappedOpenAIModels ensures a partial mapping catalog does not
-// hide models from unmapped or passthrough OpenAI accounts (passthrough routing
-// ignores model_mapping, so it serves the same default set as an unmapped
-// account). An empty catalog is left unchanged so callers retain their existing
+// hide models from unmapped or unrestricted passthrough OpenAI accounts.
+// An empty catalog is left unchanged so callers retain their existing
// discovery fallback.
func supplementUnmappedOpenAIModels(accounts []Account, models []string) []string {
if len(models) == 0 {
@@ -39,7 +38,8 @@ func supplementUnmappedOpenAIModels(accounts []Account, models []string) []strin
}
for i := range accounts {
account := &accounts[i]
- if account.Platform == PlatformOpenAI && (account.IsOpenAIPassthroughEnabled() || len(account.GetModelMapping()) == 0) {
+ unrestrictedPassthrough := account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled()
+ if account.Platform == PlatformOpenAI && (unrestrictedPassthrough || len(account.GetModelMapping()) == 0) {
return dedupeAndSortModelIDs(slices.Concat(models, openai.DefaultModelIDs()))
}
}
diff --git a/backend/internal/service/openai_models_list.go b/backend/internal/service/openai_models_list.go
index dedb9f559b..7b2030dfa4 100644
--- a/backend/internal/service/openai_models_list.go
+++ b/backend/internal/service/openai_models_list.go
@@ -177,7 +177,8 @@ func projectAccountModelsBody(body []byte, account *Account, group *Group, codex
// projectAccountModelAliases retains the source entry's metadata, never changes
// the shared response, and never synthesizes models absent from this account.
func projectAccountModelAliases(body []byte, account *Account, group *Group, codex bool) ([]byte, error) {
- if account.IsOpenAIPassthroughEnabled() || len(account.GetModelMapping()) == 0 {
+ passthrough := account.IsOpenAIPassthroughEnabled()
+ if (passthrough && !account.IsOpenAIPassthroughModelFilterEnabled()) || len(account.GetModelMapping()) == 0 {
return body, nil
}
field, idField := "data", "id"
@@ -237,6 +238,10 @@ func projectAccountModelAliases(body []byte, account *Account, group *Group, cod
continue
}
target, matched := account.ResolveMappedModel(id)
+ if passthrough {
+ // Filtering changes eligibility, never the upstream/public model name.
+ target, matched = id, account.IsModelSupported(id)
+ }
raw, available := byID[strings.TrimSpace(target)]
if !matched || !available {
continue
diff --git a/backend/internal/service/openai_models_list_test.go b/backend/internal/service/openai_models_list_test.go
index edb50a569e..bac0195bfb 100644
--- a/backend/internal/service/openai_models_list_test.go
+++ b/backend/internal/service/openai_models_list_test.go
@@ -209,6 +209,27 @@ func TestProjectAccountModelsPassthroughIgnoresStaleMappings(t *testing.T) {
require.JSONEq(t, string(body), string(projected))
}
+func TestProjectAccountModelsPassthroughFilterKeepsSourceNames(t *testing.T) {
+ for _, codex := range []bool{false, true} {
+ t.Run(fmt.Sprint(codex), func(t *testing.T) {
+ account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
+ account.Extra = map[string]any{"openai_passthrough": true, "openai_passthrough_model_filter": true}
+ account.Credentials["model_mapping"] = map[string]any{
+ "qwen3.8-max": "must-not-rewrite", "qwen3.8-*": "also-not-a-model", "absent-alias": "gpt-6.1-sol",
+ }
+ body := `{"object":"list","data":[{"id":"qwen3.8-max","display_name":"Qwen Max"},{"id":"qwen3.8-plus"},{"id":"gpt-6.1-sol"}]}`
+ want := `{"object":"list","data":[{"id":"qwen3.8-max","display_name":"Qwen Max"},{"id":"qwen3.8-plus"}]}`
+ if codex {
+ body = strings.NewReplacer(`"data"`, `"models"`, `"id"`, `"slug"`).Replace(body)
+ want = strings.NewReplacer(`"data"`, `"models"`, `"id"`, `"slug"`).Replace(want)
+ }
+ projected, err := projectAccountModelsBody([]byte(body), account, nil, codex)
+ require.NoError(t, err)
+ require.JSONEq(t, want, string(projected))
+ })
+ }
+}
+
func TestFetchOpenAIModelsListEmptyAndMalformedResponses(t *testing.T) {
for _, body := range []string{`{"data":[]}`, `{"data":null}`, `{}`, `{"data":{}}`, `{"data":[{}]}`, `{"data":[null]}`} {
t.Run(body, func(t *testing.T) {
diff --git a/backend/internal/service/openai_passthrough_model_filter_test.go b/backend/internal/service/openai_passthrough_model_filter_test.go
new file mode 100644
index 0000000000..abf34145a6
--- /dev/null
+++ b/backend/internal/service/openai_passthrough_model_filter_test.go
@@ -0,0 +1,166 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// Synthetic accounts share an ordinary OpenAI group; no provider traffic is sent.
+func passthroughModelFilterAccounts(passthrough bool, oauthPriority int) []Account {
+ return []Account{
+ {
+ ID: 1, Name: "bailian-compatible", Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
+ Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 1,
+ GroupIDs: []int64{17}, RateMultiplier: f64p(1),
+ Credentials: map[string]any{
+ "api_key": "synthetic-key", "base_url": "https://bailian.example",
+ "model_mapping": map[string]any{"qwen3.8-max": "qwen3.8-max"},
+ },
+ Extra: map[string]any{"openai_passthrough": passthrough},
+ },
+ {
+ ID: 2, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth,
+ Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: oauthPriority,
+ GroupIDs: []int64{17}, RateMultiplier: f64p(1),
+ Credentials: map[string]any{
+ "access_token": "synthetic-token",
+ "model_mapping": map[string]any{"gpt-6.1-sol": "gpt-6.1-sol"},
+ },
+ },
+ }
+}
+
+func TestOpenAIPassthroughModelFilterEligibility(t *testing.T) {
+ for _, accountType := range []string{AccountTypeAPIKey, AccountTypeOAuth} {
+ t.Run(accountType, func(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ flag any
+ model string
+ want bool
+ }{
+ {"default ignores leftover mapping", nil, "gpt-6.1-sol", true},
+ {"disabled ignores leftover mapping", false, "gpt-6.1-sol", true},
+ {"invalid flag does not opt in", "true", "gpt-6.1-sol", true},
+ {"opt in rejects other provider", true, "gpt-6.1-sol", false},
+ {"opt in accepts exact source key", true, "qwen3.8-max", true},
+ {"opt in accepts wildcard source key", true, "qwen3.8-plus", true},
+ {"mapping targets do not grant access", true, "upstream-only", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ account := &Account{
+ Platform: PlatformOpenAI, Type: accountType,
+ Extra: map[string]any{"openai_passthrough": true, "openai_passthrough_model_filter": tc.flag},
+ Credentials: map[string]any{"model_mapping": map[string]any{
+ "qwen3.8-max": "upstream-only", "qwen3.8-*": "wildcard-target",
+ }},
+ }
+ require.Equal(t, tc.want, account.IsModelSupported(tc.model))
+ require.Equal(t, tc.want, (&GatewayService{}).isModelSupportedByAccount(account, tc.model))
+ })
+ }
+ account := &Account{Platform: PlatformOpenAI, Type: accountType,
+ Extra: map[string]any{"openai_passthrough": true, "openai_passthrough_model_filter": true}}
+ require.True(t, account.IsModelSupported("qwen3.8-max"), "empty restrictions still allow all models")
+ })
+ }
+}
+
+func TestOpenAIPassthroughModelFilterMixedPoolSelection(t *testing.T) {
+ groupID := int64(17)
+ for _, mode := range []string{"legacy", "load-batch"} {
+ t.Run(mode, func(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ filter bool
+ model string
+ excluded map[int64]struct{}
+ wantID int64
+ }{
+ {"default preserves passthrough", false, "gpt-6.1-sol", nil, 1},
+ {"filter chooses GPT account", true, "gpt-6.1-sol", nil, 2},
+ {"filter keeps Qwen account", true, "qwen3.8-max", nil, 1},
+ {"failover never leaks GPT to Qwen", true, "gpt-6.1-sol", map[int64]struct{}{2: {}}, 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ accounts := passthroughModelFilterAccounts(true, 2)
+ accounts[0].Extra["openai_passthrough_model_filter"] = tc.filter
+ repo := schedulerTestOpenAIAccountRepo{accounts: accounts}
+ cfg := &config.Config{}
+ cfg.Gateway.Scheduling.LoadBatchEnabled = mode == "load-batch"
+ svc := &OpenAIGatewayService{accountRepo: repo, cfg: cfg}
+ var selected *Account
+ var err error
+ if mode == "legacy" {
+ selected, err = svc.SelectAccountForModelWithExclusions(context.Background(), &groupID, "", tc.model, tc.excluded)
+ } else {
+ svc.concurrencyService = NewConcurrencyService(stubConcurrencyCache{})
+ selection, selectErr := svc.SelectAccountWithLoadAwareness(context.Background(), &groupID, "", tc.model, tc.excluded)
+ err = selectErr
+ if selection != nil {
+ selected = selection.Account
+ if selection.ReleaseFunc != nil {
+ defer selection.ReleaseFunc()
+ }
+ }
+ }
+ if tc.wantID == 0 {
+ require.Error(t, err)
+ require.Nil(t, selected)
+ return
+ }
+ require.NoError(t, err)
+ require.NotNil(t, selected)
+ require.Equal(t, tc.wantID, selected.ID)
+ })
+ }
+ })
+ }
+}
+
+func TestOpenAIPassthroughModelFilterPreservesForwardBody(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ accounts := passthroughModelFilterAccounts(true, 2)
+ accounts[0].Extra["openai_passthrough_model_filter"] = true
+ accounts[0].Credentials["model_mapping"] = map[string]any{"qwen3.8-max": "must-not-rewrite"}
+ repo := schedulerTestOpenAIAccountRepo{accounts: accounts}
+ body := []byte(`{ "model": "qwen3.8-max", "input":"synthetic query", "tools":[{"type":"web_search"}], "stream":false }`)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
+ upstream := &httpUpstreamRecorder{resp: &http.Response{
+ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"output":[],"usage":{"input_tokens":1,"output_tokens":1}}`)),
+ }}
+ svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}, httpUpstream: upstream}
+ groupID := int64(17)
+ account, err := svc.SelectAccountForModelWithExclusions(context.Background(), &groupID, "", "qwen3.8-max", nil)
+ require.NoError(t, err)
+ require.Equal(t, int64(1), account.ID)
+ result, err := svc.Forward(context.Background(), c, account, body)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.NotNil(t, upstream.lastReq)
+ require.Equal(t, body, upstream.lastBody, "whitelist filtering must not activate model rewriting")
+ require.Equal(t, "https://bailian.example/v1/responses", upstream.lastReq.URL.String())
+}
+
+func TestOpenAIPassthroughModelFilterGroupCatalog(t *testing.T) {
+ accounts := passthroughModelFilterAccounts(true, 2)
+ accounts[0].Extra["openai_passthrough_model_filter"] = true
+ svc := &GatewayService{accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}}
+ groupID := int64(17)
+ models := svc.GetAvailableModels(context.Background(), &groupID, PlatformOpenAI)
+ require.ElementsMatch(t, []string{"qwen3.8-max", "gpt-6.1-sol"}, models,
+ "a restricted passthrough account must not contribute the unrestricted default catalog")
+}
diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue
index 6b839b1a00..d04af5f3f7 100644
--- a/frontend/src/components/account/BulkEditAccountModal.vue
+++ b/frontend/src/components/account/BulkEditAccountModal.vue
@@ -79,6 +79,21 @@
]"
/>
+
@@ -1739,6 +1754,7 @@ const rateMultiplier = ref(1)
const status = ref<'active' | 'inactive'>('active')
const groupIds = ref([])
const openaiPassthroughEnabled = ref(false)
+const openaiPassthroughModelFilterEnabled = ref(false)
// Codex namespace 工具摊平兼容开关(仅 OAuth),缺省关闭即原样保留
const openaiFlattenNamespacesEnabled = ref(false)
const openAILongContextBillingEnabled = ref(false)
@@ -1798,7 +1814,8 @@ const isOpenAIModelRestrictionDisabled = computed(
() =>
allOpenAIPassthroughCapable.value &&
enableOpenAIPassthrough.value &&
- openaiPassthroughEnabled.value
+ openaiPassthroughEnabled.value &&
+ !openaiPassthroughModelFilterEnabled.value
)
const openAIWSModeOptions = computed(() => [
@@ -2026,6 +2043,7 @@ const buildUpdatePayload = (): Record | null => {
if (enableOpenAIPassthrough.value) {
const extra = ensureExtra()
extra.openai_passthrough = openaiPassthroughEnabled.value
+ extra.openai_passthrough_model_filter = openaiPassthroughEnabled.value && openaiPassthroughModelFilterEnabled.value
if (!openaiPassthroughEnabled.value) {
extra.openai_oauth_passthrough = false
}
@@ -2437,6 +2455,7 @@ watch(
// Reset all values
baseUrl.value = ''
openaiPassthroughEnabled.value = false
+ openaiPassthroughModelFilterEnabled.value = false
openaiFlattenNamespacesEnabled.value = false
openAILongContextBillingEnabled.value = false
openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS]
diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue
index aa27e6e841..34906ac3e4 100644
--- a/frontend/src/components/account/CreateAccountModal.vue
+++ b/frontend/src/components/account/CreateAccountModal.vue
@@ -3299,6 +3299,7 @@