diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 10bb77450d..6fa1187851 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1255,7 +1255,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( Duration: time.Since(turnStart), FirstTokenMs: firstTokenMs, } - if replayInput := replayCollector.Items(); len(replayInput) > 0 { + replayInput := replayCollector.Items() + if account.IsOpenAIOAuthLike() && lease.initializedWithoutWebSearch() { + // Keep complete output while search activation can require a new socket. + replayInput = replayCollector.AllItems() + } + if len(replayInput) > 0 { result.wsReplayInput = replayInput result.wsReplayInputExists = true } @@ -1347,6 +1352,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( var lastTurnStrictState *openAIWSIngressPreviousTurnStrictState lastTurnReplayInput := []json.RawMessage(nil) lastTurnReplayInputExists := false + lastTurnReplayInputComplete := false currentTurnReplayInput := []json.RawMessage(nil) currentTurnReplayInputExists := false skipBeforeTurn := false @@ -1562,6 +1568,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( currentPayload, currentPreviousResponseID != "", ) + currentTurnReplayInputComplete := replayInputErr == nil && (currentPreviousResponseID == "" || + (lastTurnReplayInputComplete && currentPreviousResponseID == lastTurnResponseID)) if replayInputErr != nil { logOpenAIWSModeInfo( "ingress_ws_replay_input_skip account_id=%d turn=%d conn_id=%s reason=build_error cause=%s", @@ -1678,6 +1686,28 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( unpinSessionConn(sessionConnID) } } + if account.IsOpenAIOAuthLike() && sessionLease.initializedWithoutWebSearch() && openAIWSWebSearchDeclared(currentPayload) { + fullPayload, safe, err := buildOpenAIWSCurrentTurnRetryPayload(currentPayload, currentTurnReplayInput, currentTurnReplayInputExists, "") + if err != nil { + return fmt.Errorf("rebuild websocket input for web search activation: %w", err) + } + if !safe || !currentTurnReplayInputComplete { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "web search activation requires complete input history; please reconnect with full input", nil) + } + logOpenAIWSModeInfo("ingress_ws_web_search_activation account_id=%d turn=%d action=reconnect", account.ID, turn) + resetSessionLease(true) + acquiredLease, acquireErr := acquireTurnLease(turn, "", false, true) + if acquireErr != nil { + return fmt.Errorf("acquire upstream websocket for web search activation: %w", acquireErr) + } + sessionLease = acquiredLease + sessionConnID = strings.TrimSpace(sessionLease.ConnID()) + pinSessionConn(sessionConnID) + currentPayload = fullPayload + currentPayloadBytes = len(fullPayload) + currentPreviousResponseID = "" + forcePreferredConn = false + } shouldPreflightPing := turn > 1 && sessionLease != nil && sessionLease.SupportsIdlePingWithoutReader() && turnRetry == 0 if shouldPreflightPing && openAIWSIngressPreflightPingIdle > 0 && !lastTurnFinishedAt.IsZero() { if time.Since(lastTurnFinishedAt) < openAIWSIngressPreflightPingIdle { @@ -1857,6 +1887,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // collector 增量经 combine 合并(新头数组)。 lastTurnReplayInput = currentTurnReplayInput lastTurnReplayInputExists = currentTurnReplayInputExists + lastTurnReplayInputComplete = currentTurnReplayInputComplete if result.wsReplayInputExists { lastTurnReplayInput = combineOpenAIWSReplayItems(lastTurnReplayInput, result.wsReplayInput) lastTurnReplayInputExists = true diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index b632bba523..ae4e3fe2c7 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -292,6 +292,9 @@ type openAIWSConn struct { readMu sync.Mutex writeMu sync.Mutex + // The subscription backend fixes hosted-search support on the first create. + responseCreateSent bool // guarded by writeMu + initialWebSearch bool // guarded by writeMu // readerLoopResults 非 nil 表示池为该连接常驻了读循环:coder/websocket 只在 // 阻塞读期间应答上游 ping,空闲连接没有读循环会被上游按保活超时关闭。 @@ -600,6 +603,9 @@ func (c *openAIWSConn) writeJSON(value any, writeCtx context.Context) error { if err := c.ws.WriteJSON(writeCtx, value); err != nil { return err } + if !c.responseCreateSent { + c.recordInitialWebSearch(value) + } c.touch() return nil } diff --git a/backend/internal/service/openai_ws_search_activation.go b/backend/internal/service/openai_ws_search_activation.go new file mode 100644 index 0000000000..6d1e640c11 --- /dev/null +++ b/backend/internal/service/openai_ws_search_activation.go @@ -0,0 +1,60 @@ +package service + +import ( + "encoding/json" + + "github.com/tidwall/gjson" +) + +func openAIWSWebSearchDeclared(payload []byte) bool { + fields := gjson.GetMany(openAIWSPayloadStringView(payload), "tools", "input") + if gjsonToolsContainWebSearch(fields[0]) { + return true + } + for _, item := range fields[1].Array() { + if item.Get("type").String() == openAIAdditionalToolsItemType && gjsonToolsContainWebSearch(item.Get("tools")) { + return true + } + } + return false +} + +// Called under writeMu, only after the first response.create was written. +func (c *openAIWSConn) recordInitialWebSearch(value any) { + var body []byte + switch payload := value.(type) { + case json.RawMessage: + body = payload + case []byte: + body = payload + case map[string]any: + if payload["type"] != "response.create" { + return + } + c.responseCreateSent = true + c.initialWebSearch = openAIToolsContainWebSearch(payload["tools"]) + input, _ := payload["input"].([]any) + for _, raw := range input { + if item, ok := raw.(map[string]any); ok && item["type"] == openAIAdditionalToolsItemType && openAIToolsContainWebSearch(item["tools"]) { + c.initialWebSearch = true + } + } + return + default: + return + } + if gjson.GetBytes(body, "type").String() == "response.create" { + c.responseCreateSent = true + c.initialWebSearch = openAIWSWebSearchDeclared(body) + } +} + +func (l *openAIWSConnLease) initializedWithoutWebSearch() bool { + c, err := l.activeConn() + if err != nil { + return false + } + c.writeMu.Lock() + defer c.writeMu.Unlock() + return c.responseCreateSent && !c.initialWebSearch +} diff --git a/backend/internal/service/openai_ws_search_activation_test.go b/backend/internal/service/openai_ws_search_activation_test.go new file mode 100644 index 0000000000..d45387b050 --- /dev/null +++ b/backend/internal/service/openai_ws_search_activation_test.go @@ -0,0 +1,202 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIWSIngressWebSearchActivation(t *testing.T) { + const search = `,"tools":[{"type":"web_search","external_web_access":false}]` + const userInput = `[{"type":"message","role":"user","content":"continue"}]` + const toolOutput = `[{"type":"function_call_output","call_id":"fc_lookup","output":"42"}]` + const firstOutput = `[{"type":"reasoning","id":"rs_first","summary":[{"type":"summary_text","text":"Keep this reasoning"}]},{"type":"message","id":"msg_first","role":"assistant","content":[{"type":"output_text","text":"Keep this answer"}]},{"type":"function_call","id":"fc_lookup","call_id":"fc_lookup","name":"lookup","arguments":"{}"}]` + for _, tc := range []struct { + name string + accountType string + firstFields string + firstInput string + firstOutput string + nextFields string + nextInput string + nextPrevious string + wantReconnect bool + wantFailClose bool + wantTypes []string + }{ + {name: "empty OAuth prewarm", accountType: AccountTypeOAuth, firstFields: `,"generate":false`, nextFields: search, nextInput: userInput, wantReconnect: true, wantTypes: []string{"message"}}, + {name: "Lite search history injection", accountType: AccountTypeOAuth, firstFields: `,"generate":false`, nextFields: `,"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}`, nextInput: `[{"type":"web_search_call","id":"ws_history","status":"completed","action":{"type":"search","query":"example"}},{"type":"message","role":"user","content":"continue"}]`, wantReconnect: true, wantTypes: []string{"web_search_call", "message", "additional_tools"}}, + {name: "tool continuation preserves all output", accountType: AccountTypeOAuth, firstFields: `,"tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, firstInput: `[{"type":"message","role":"user","content":"Run lookup for my original question"}]`, firstOutput: firstOutput, nextFields: search, nextInput: toolOutput, wantReconnect: true, wantTypes: []string{"message", "reasoning", "message", "function_call", "function_call_output"}}, + {name: "search initialized socket", accountType: AccountTypeOAuth, firstFields: search, nextFields: search, nextInput: userInput}, + {name: "API key provider", accountType: AccountTypeAPIKey, firstFields: `,"generate":false`, nextFields: search, nextInput: userInput}, + {name: "function called web_search", accountType: AccountTypeOAuth, nextFields: `,"tools":[{"type":"function","name":"web_search","parameters":{"type":"object"}}]`, nextInput: userInput}, + {name: "missing tool context fails closed", accountType: AccountTypeOAuth, nextFields: search, nextInput: toolOutput, wantFailClose: true}, + {name: "unknown response history fails closed", accountType: AccountTypeOAuth, nextFields: search, nextInput: userInput, nextPrevious: "resp_unknown", wantFailClose: true}, + } { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 2 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 2 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + output := tc.firstOutput + if output == "" { + output = "[]" + } + events := [][]byte{ + []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_first","model":"gpt-6.1-sol","output":%s,"usage":{"input_tokens":1,"output_tokens":1}}}`, output)), + []byte(`{"type":"response.completed","response":{"id":"resp_second","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_third","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_fourth","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`), + } + first := &openAIWSCaptureConn{events: append([][]byte(nil), events...)} + second := &openAIWSCaptureConn{events: append([][]byte(nil), events[1:]...)} + dialer := &openAIWSQueueDialer{conns: []openAIWSClientConn{first, second}} + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(dialer) + t.Cleanup(pool.Close) + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), openaiWSPool: pool} + account := &Account{ID: 71, Platform: PlatformOpenAI, Type: tc.accountType, Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token", "api_key": "test-token"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}} + serverErr := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + serverErr <- err + return + } + defer conn.CloseNow() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + _, payload, err := conn.Read(ctx) + if err == nil { + err = svc.ProxyResponsesWebSocketFromClient(ctx, c, conn, account, "test-token", payload, nil) + } + serverErr <- err + })) + defer server.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer client.CloseNow() + write := func(fields, input string) { + payload := fmt.Sprintf(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"input":%s%s}`, input, fields) + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(payload))) + } + read := func(id string) { + _, event, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, id, gjson.GetBytes(event, "response.id").String()) + } + input := tc.firstInput + if input == "" { + input = "[]" + } + write(tc.firstFields, input) + read("resp_first") + previous := tc.nextPrevious + if previous == "" { + previous = "resp_first" + } + write(fmt.Sprintf(`,"previous_response_id":%q`, previous)+tc.nextFields, tc.nextInput) + if tc.wantFailClose { + _, _, err := client.Read(ctx) + require.Error(t, err) + require.Error(t, <-serverErr) + require.Len(t, first.writes, 1, "unsafe continuation must not reach upstream") + return + } + read("resp_second") + // Removing and restoring search must keep the search-initialized socket. + write(`,"previous_response_id":"resp_second"`, userInput) + read("resp_third") + write(`,"previous_response_id":"resp_third"`+tc.nextFields, userInput) + read("resp_fourth") + require.NoError(t, client.Close(coderws.StatusNormalClosure, "done")) + require.NoError(t, <-serverErr) + if !tc.wantReconnect { + require.Equal(t, 1, dialer.DialCount()) + require.Len(t, first.writes, 4) + return + } + require.Equal(t, 2, dialer.DialCount()) + require.Len(t, first.writes, 1, "search must never be sent on the incompatible socket") + require.Len(t, second.writes, 3) + forwarded, err := json.Marshal(second.writes[0]) + require.NoError(t, err) + require.False(t, gjson.GetBytes(forwarded, "previous_response_id").Exists()) + var types []string + for _, item := range gjson.GetBytes(forwarded, "input").Array() { + types = append(types, item.Get("type").String()) + } + require.Equal(t, tc.wantTypes, types) + if tc.firstOutput != "" { + require.Contains(t, string(forwarded), "Run lookup for my original question") + require.Contains(t, string(forwarded), "Keep this reasoning") + require.Contains(t, string(forwarded), "Keep this answer") + require.Contains(t, string(forwarded), `"output":"42"`) + } + }) + } +} + +func TestOpenAIWSConnWebSearchInitialization(t *testing.T) { + const search = `{"type":"response.create","tools":[{"type":"web_search"}]}` + for _, first := range []struct { + name string + body string + wantReconnect bool + }{ + {"empty prewarm", `{"type":"response.create","generate":false,"input":[]}`, true}, + {"hosted search", search, false}, + {"Lite hosted search", `{"type":"response.create","input":[{"type":"additional_tools","tools":[{"type":"web_search"}]}]}`, false}, + {"function lookalike", `{"type":"response.create","tools":[{"type":"function","name":"web_search"}]}`, true}, + } { + for _, format := range []string{"map", "raw", "bytes"} { + t.Run(first.name+"/"+format, func(t *testing.T) { + conn := newOpenAIWSConn("test", 1, &openAIWSCaptureConn{}, nil) + defer conn.close() + lease := &openAIWSConnLease{conn: conn} + require.False(t, lease.initializedWithoutWebSearch(), "an unused socket is compatible") + var payload any + switch format { + case "map": + require.NoError(t, json.Unmarshal([]byte(first.body), &payload)) + case "raw": + payload = json.RawMessage(first.body) + case "bytes": + payload = []byte(first.body) + } + require.NoError(t, lease.WriteJSON(payload, time.Second)) + // Capability belongs to the socket, even after it is leased again. + lease = &openAIWSConnLease{conn: conn} + require.Equal(t, first.wantReconnect, lease.initializedWithoutWebSearch()) + require.NoError(t, lease.WriteJSON(json.RawMessage(search), time.Second)) + require.Equal(t, first.wantReconnect, lease.initializedWithoutWebSearch(), "later writes cannot change initial capability") + }) + } + } +}