From ed3317d02bb277022b93cfb1ebae515eaa09a552 Mon Sep 17 00:00:00 2001 From: pood1e Date: Tue, 1 Dec 2026 04:35:50 -0800 Subject: [PATCH] feat(openai): let API-key accounts send an isolated session ID on Chat Completions Self-hosted routers such as vllm-router keep a session on one decode replica by the X-Session-ID header, but the Chat Completions outbound path forwards only accept-language and user-agent from the client. The new account extra key `openai_chat_session_id` makes that path send the client's session as X-Session-ID, isolated per API key with isolateOpenAIUpstreamSessionID. The session comes from the same sources as x-opencode-session: client session headers first, then the prompt_cache_key or metadata.user_id remembered before protocol conversion, so /v1/responses and /v1/messages requests converted to Chat Completions keep their sessions. Account header overrides still apply last, and accounts without the key send the same headers as before. Co-Authored-By: Claude Opus 5.5 --- .../service/openai_gateway_cc_pipeline.go | 1 + .../service/openai_gateway_chat_session_id.go | 30 ++++ .../openai_gateway_chat_session_id_test.go | 150 ++++++++++++++++++ 3 files changed, 181 insertions(+) create mode 100644 backend/internal/service/openai_gateway_chat_session_id.go create mode 100644 backend/internal/service/openai_gateway_chat_session_id_test.go diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 09eb7d9598..cafe9339f9 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -260,6 +260,7 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( // 官方 OpenCode / Command Code 上游收敛为规范客户端 UA:客户端透传的编程库 // UA 会命中其前置 Cloudflare bot 拦截(CF 1010/403),并被计入账号 403 strike。 applyOpenCodeUpstreamUserAgent(account, targetURL, upstreamReq.Header) + applyOpenAIChatSessionIDHeader(c, account, upstreamReq.Header, body) // 账号级请求头覆写:放在所有内置默认头(含 Grok CLI 身份头)之后应用, // 使配置值获得除共享传输层强制头之外的最高优先级。 diff --git a/backend/internal/service/openai_gateway_chat_session_id.go b/backend/internal/service/openai_gateway_chat_session_id.go new file mode 100644 index 0000000000..783e2530a7 --- /dev/null +++ b/backend/internal/service/openai_gateway_chat_session_id.go @@ -0,0 +1,30 @@ +package service + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +// OpenAIChatSessionIDExtraKey 是账号 extra 中的可选开关,通过 admin 账号更新 API 的 extra +// 字段设置。为 true 时,OpenAI API Key 账号的 CC 出站请求携带按 API Key 隔离的会话标识, +// 供可信的自托管上游(如 vLLM router)做会话亲和。 +const OpenAIChatSessionIDExtraKey = "openai_chat_session_id" + +// openAIChatSessionIDHeader 是 vLLM router 读取会话标识的请求头。 +const openAIChatSessionIDHeader = "X-Session-ID" + +// applyOpenAIChatSessionIDHeader 为开启 OpenAIChatSessionIDExtraKey 的账号写入会话头。 +// 会话来源与 x-opencode-session 相同:客户端会话头优先,其次是协议转换前记下的 +// prompt_cache_key / metadata.user_id。出站值经 isolateOpenAIUpstreamSessionID 隔离, +// 不同 API Key 的同名会话互不冲突。 +func applyOpenAIChatSessionIDHeader(c *gin.Context, account *Account, headers http.Header, body []byte) { + if account == nil || !account.IsOpenAIApiKey() || !account.getExtraBool(OpenAIChatSessionIDExtraKey) { + return + } + clientSessionID := resolveOpenCodeSessionID(c, nil, false, append(openCodeInboundBodies(c), body)...) + sessionID := isolateOpenAIUpstreamSessionID(getAPIKeyIDFromContext(c), codexAccountIdentitySource(c, account), clientSessionID) + if sessionID != "" { + headers.Set(openAIChatSessionIDHeader, sessionID) + } +} diff --git a/backend/internal/service/openai_gateway_chat_session_id_test.go b/backend/internal/service/openai_gateway_chat_session_id_test.go new file mode 100644 index 0000000000..6e6da80e4b --- /dev/null +++ b/backend/internal/service/openai_gateway_chat_session_id_test.go @@ -0,0 +1,150 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func openAIChatSessionTestContext(path string, apiKeyID int64, header http.Header, body []byte) *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + for key, values := range header { + c.Request.Header[key] = values + } + c.Set("api_key", &APIKey{ID: apiKeyID}) + return c +} + +func openAIChatSessionTestUpstream() *httpUpstreamRecorder { + return &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader( + `{"id":"chatcmpl_session","object":"chat.completion","model":"deepseek-v4.1-flash","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + )), + }} +} + +// sendOpenAIChatSessionTestRequest sends a Chat Completions request through the +// shared CC outbound path and returns the headers the upstream received. +func sendOpenAIChatSessionTestRequest(t *testing.T, apiKeyID int64, account *Account, header http.Header, body string) http.Header { + t.Helper() + c := openAIChatSessionTestContext("/v1/chat/completions", apiKeyID, header, []byte(body)) + upstream := openAIChatSessionTestUpstream() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + resp, err := svc.sendCCUpstreamRequest(context.Background(), c, account, "http://vllm.internal:8000/v1/chat/completions", []byte(body), false, "sk-test", "", "") + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + return upstream.lastReq.Header +} + +func openAIChatSessionClientHeader(pairs ...string) http.Header { + header := http.Header{} + for i := 0; i+1 < len(pairs); i += 2 { + header.Set(pairs[i], pairs[i+1]) + } + return header +} + +func TestOpenAIChatSessionIDHeaderDisabledKeepsHeaders(t *testing.T) { + gin.SetMode(gin.TestMode) + + oauth := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true}) + oauth.Type = AccountTypeOAuth + disabled := map[string]*Account{ + "not opted in": selfHostedRawChatCompletionsTestAccount(nil), + "explicitly false": selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: false}), + "string value": selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: "true"}), + "OAuth account": oauth, + } + client := openAIChatSessionClientHeader( + "session_id", "conv-1", + "X-Session-ID", "client-session", + "User-Agent", "opencode/1.19.6", + "Accept-Language", "zh-CN", + ) + want := http.Header{ + "Content-Type": []string{"application/json"}, + "Authorization": []string{"Bearer sk-test"}, + "Accept": []string{"application/json"}, + "User-Agent": []string{"opencode/1.19.6"}, + "Accept-Language": []string{"zh-CN"}, + } + for name, account := range disabled { + t.Run(name, func(t *testing.T) { + got := sendOpenAIChatSessionTestRequest(t, 7, account, client, `{"model":"deepseek-v4.1-flash","prompt_cache_key":"pck-1"}`) + require.Equal(t, want, got) + }) + } +} + +func TestOpenAIChatSessionIDHeaderStablePerSession(t *testing.T) { + gin.SetMode(gin.TestMode) + + account := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true}) + client := openAIChatSessionClientHeader("session_id", "conv-1", "X-Session-ID", "client-session") + body := `{"model":"deepseek-v4.1-flash"}` + + first := sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Values(openAIChatSessionIDHeader) + require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, "conv-1")}, first, "the client session header wins and the raw X-Session-ID is never forwarded") + require.Regexp(t, `^[0-9a-f]{16}$`, first[0]) + require.Equal(t, first, sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Values(openAIChatSessionIDHeader)) + + fromPromptCacheKey := sendOpenAIChatSessionTestRequest(t, 7, account, nil, `{"model":"deepseek-v4.1-flash","prompt_cache_key":"pck-1"}`) + require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, "pck-1")}, fromPromptCacheKey.Values(openAIChatSessionIDHeader)) + + require.Empty(t, sendOpenAIChatSessionTestRequest(t, 7, account, nil, body).Values(openAIChatSessionIDHeader)) +} + +func TestOpenAIChatSessionIDHeaderIsolatesAPIKeys(t *testing.T) { + gin.SetMode(gin.TestMode) + + account := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true}) + client := openAIChatSessionClientHeader("session_id", "conv-1") + body := `{"model":"deepseek-v4.1-flash"}` + + first := sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Get(openAIChatSessionIDHeader) + second := sendOpenAIChatSessionTestRequest(t, 8, account, client, body).Get(openAIChatSessionIDHeader) + require.NotEmpty(t, first) + require.NotEmpty(t, second) + require.NotEqual(t, first, second) +} + +func TestForwardResponses_ChatFallbackSessionIDFromPromptCacheKey(t *testing.T) { + gin.SetMode(gin.TestMode) + + account := forceChatResponsesFallbackAccount() + account.Extra[OpenAIChatSessionIDExtraKey] = true + body := []byte(`{"model":"deepseek-v4.1-flash","input":"hello","prompt_cache_key":"codex-thread-1","stream":false}`) + + tests := []struct { + name string + header http.Header + want string + }{ + {name: "without session header", want: "codex-thread-1"}, + {name: "session header first", header: openAIChatSessionClientHeader("session_id", "conv-9"), want: "conv-9"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := openAIChatSessionTestContext("/v1/responses", 7, tt.header, body) + upstream := openAIChatSessionTestUpstream() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.Equal(t, "http://upstream.example/v1/chat/completions", upstream.lastReq.URL.String()) + require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, tt.want)}, upstream.lastReq.Header.Values(openAIChatSessionIDHeader)) + }) + } +}