From b56311903e3962c0df071de92a0ea80a1b2aa6b0 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 20 Nov 2026 22:35:54 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20=E6=81=A2=E5=A4=8D=E5=A4=A7=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E4=B8=8E=20OAuth=20=E6=A1=A5=E6=8E=A5=E7=9A=84=20WS?= =?UTF-8?q?=20=E5=B7=A5=E5=85=B7=E7=BB=93=E6=9E=9C=E7=BB=AD=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ws-http-bridge-warmup.yml | 5 +- .../openai_ws_tool_result_bridge_test.go | 102 ++++++++++++++++++ .../service/openai_tool_provenance.go | 25 ++++- .../service/openai_ws_agent_recovery.go | 70 +++++++++++- .../internal/service/openai_ws_http_bridge.go | 2 +- .../service/openai_ws_http_bridge_account.go | 8 ++ 6 files changed, 199 insertions(+), 13 deletions(-) create mode 100644 backend/internal/handler/openai_ws_tool_result_bridge_test.go create mode 100644 backend/internal/service/openai_ws_http_bridge_account.go diff --git a/.github/workflows/ws-http-bridge-warmup.yml b/.github/workflows/ws-http-bridge-warmup.yml index 356d314f1ab8..c6241fc3696e 100644 --- a/.github/workflows/ws-http-bridge-warmup.yml +++ b/.github/workflows/ws-http-bridge-warmup.yml @@ -9,6 +9,7 @@ on: - 'backend/internal/service/openai_gateway_service.go' - 'backend/internal/handler/openai_gateway_handler.go' - 'backend/internal/handler/openai_http_bridge_warmup_test.go' + - 'backend/internal/handler/openai_ws_tool_result_bridge_test.go' - '.github/workflows/ws-http-bridge-warmup.yml' permissions: contents: read @@ -51,12 +52,12 @@ jobs: - name: Candidate warmup, full-history tool loop and refusal controls run: | set -euo pipefail - (cd backend && go test -race -json -tags=unit,bridgewarmup ./internal/handler ./internal/service -run '^Test(HTTPBridgeWarmup|HTTPBridgeAcceptedHistory|OpenAIWSHTTPBridgeAPIKeyReusesClientToolMappingWhenFollowupOmitsTools|PrepareOpenAIWSHTTPBridgeBody)' -count=1 -timeout=3m) | tee "$RUNNER_TEMP/http-warmup-head.jsonl" + (cd backend && go test -race -json -tags=unit,bridgewarmup ./internal/handler ./internal/service -run '^Test(HTTPBridgeLargeHistoryToolResult|HTTPBridgeWarmup|HTTPBridgeAcceptedHistory|OpenAIWSHTTPBridgeAPIKeyReusesClientToolMappingWhenFollowupOmitsTools|PrepareOpenAIWSHTTPBridgeBody)' -count=1 -timeout=3m) | tee "$RUNNER_TEMP/http-warmup-head.jsonl" python3 - "$RUNNER_TEMP/http-warmup-head.jsonl" <<'PY' import json,sys rows=[json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] assert not any(r.get('Action') in ('build-fail','fail','skip') for r in rows) - for name in ('TestHTTPBridgeWarmupThenToolContinuation','TestHTTPBridgeWarmupGuards','TestHTTPBridgeWarmupDefaultsAndForeignPointer','TestHTTPBridgeWarmupWithPriorCompletedToolHistory','TestHTTPBridgeAcceptedHistoryRequiresCompletedDelivery'): + for name in ('TestHTTPBridgeLargeHistoryToolResult/api_key_large','TestHTTPBridgeLargeHistoryToolResult/oauth_large','TestHTTPBridgeLargeHistoryToolResult/oauth_wrong_response','TestHTTPBridgeLargeHistoryToolResult/oauth_unobserved_call','TestHTTPBridgeLargeHistoryToolResult/oauth_old_call','TestHTTPBridgeWarmupThenToolContinuation','TestHTTPBridgeWarmupGuards','TestHTTPBridgeWarmupDefaultsAndForeignPointer','TestHTTPBridgeWarmupWithPriorCompletedToolHistory','TestHTTPBridgeAcceptedHistoryRequiresCompletedDelivery'): assert any(r.get('Test')==name and r.get('Action')=='pass' for r in rows),name PY - uses: actions/upload-artifact@v7 diff --git a/backend/internal/handler/openai_ws_tool_result_bridge_test.go b/backend/internal/handler/openai_ws_tool_result_bridge_test.go new file mode 100644 index 000000000000..d4d243a6a348 --- /dev/null +++ b/backend/internal/handler/openai_ws_tool_result_bridge_test.go @@ -0,0 +1,102 @@ +//go:build unit && bridgewarmup + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + ws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestHTTPBridgeLargeHistoryToolResult(t *testing.T) { + for _, tc := range []struct { + name, account, previous, call string + size int + accept bool + }{ + {"api_key_large", service.AccountTypeAPIKey, "resp_one", "turn_one", (8 << 20) + 1024, true}, + {"oauth_large", service.AccountTypeOAuth, "resp_one", "turn_one", (16 << 20) + 1024, true}, + {"oauth_wrong_response", service.AccountTypeOAuth, "resp_foreign", "turn_one", 256, false}, + {"oauth_unobserved_call", service.AccountTypeOAuth, "resp_one", "never_delivered", 256, false}, + {"oauth_old_call", service.AccountTypeOAuth, "resp_one", "prior", 256, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var calls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + n := calls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + if n == 1 { + fmt.Fprint(w, `data: {"type":"response.completed","response":{"id":"resp_one","status":"completed","output":[{"type":"function_call","name":"lookup","call_id":"turn_one","arguments":"{}","status":"completed"}],"usage":{"input_tokens":1,"output_tokens":1}}}`+"\n\n") + return + } + if !tc.accept || n != 2 || gjson.GetBytes(body, "previous_response_id").Exists() || + gjson.GetBytes(body, `input.#(call_id=="turn_one")#.type`).Raw != `["function_call","function_call_output"]` || + gjson.GetBytes(body, `input.#(call_id=="prior")#.type`).Raw != `["function_call","function_call_output"]` || + gjson.GetBytes(body, `input.#(type=="function_call_output")#.output`).Raw != `["old receipt","new receipt"]` { + t.Error("unexpected bridge payload or repeated dispatch") + } + fmt.Fprint(w, `data: {"type":"response.completed","response":{"id":"resp_two","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`+"\n\n") + })) + defer upstream.Close() + h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstream.URL, http.Header{"Session-Id": {"fixture-tool-result"}}, map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}, nil, func(k *service.APIKey) { k.AllowLongContext = true }, func(a *service.Account, cfg *config.Config, transport *service.HTTPUpstream, _ *service.AccountRepository) { + a.Extra["openai_apikey_responses_websockets_v2_mode"] = service.OpenAIWSIngressModeHTTPBridge + if tc.account == service.AccountTypeOAuth { + a.Type = tc.account + a.Credentials = map[string]any{"access_token": "fixture-token", "chatgpt_account_id": "fixture-account"} + a.Extra["openai_oauth_responses_websockets_v2_enabled"] = true + a.Extra["openai_oauth_responses_websockets_v2_mode"] = service.OpenAIWSIngressModeCtxPool + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.HTTPBridgeEnabled = true + cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes = 128 + target, err := url.Parse(upstream.URL) + require.NoError(t, err) + *transport = &httpRebuildTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + } + }) + defer h.clientConn.CloseNow() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + first := `{"type":"response.create","model":"gpt-5.1","store":false,"input":[{"role":"user","content":"` + strings.Repeat("x", tc.size) + `"},{"type":"function_call","name":"lookup","call_id":"prior","arguments":"{}","status":"completed"},{"type":"function_call_output","call_id":"prior","output":"old receipt"}]}` + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(first))) + _, raw, err := h.clientConn.Read(ctx) + require.NoError(t, err) + require.Equal(t, "resp_one", gjson.GetBytes(raw, "response.id").String()) + next := fmt.Sprintf(`{"type":"response.create","model":"gpt-5.1","store":false,"previous_response_id":%q,"input":[{"type":"function_call_output","call_id":%q,"output":"new receipt"}]}`, tc.previous, tc.call) + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(next))) + _, raw, err = h.clientConn.Read(ctx) + if tc.accept { + require.NoError(t, err, "BRIDGE_TOOL_RESULT_REFUSED") + require.Equal(t, "resp_two", gjson.GetBytes(raw, "response.id").String(), "BRIDGE_TOOL_RESULT_REFUSED") + require.EqualValues(t, 2, calls.Load()) + return + } + if err == nil { + require.True(t, json.Valid(raw)) + require.Equal(t, "error", gjson.GetBytes(raw, "type").String()) + } else { + require.NotEqual(t, ws.StatusCode(-1), ws.CloseStatus(err)) + } + require.EqualValues(t, 1, calls.Load()) + }) + } +} diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go index 7a0da80b1ff4..ba2f5ff86efc 100644 --- a/backend/internal/service/openai_tool_provenance.go +++ b/backend/internal/service/openai_tool_provenance.go @@ -9,7 +9,9 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/tidwall/gjson" + "go.uber.org/zap" ) // Only hashes and delivery/route metadata; never tool arguments/results. A @@ -480,6 +482,13 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputs(ctx context.Context, r *op return s.verifyOpenAIToolInputProofs(ctx, r, body, false) } +// The externally visible refusal stays stable. Only fixed classifications go +// to the journal; call IDs, proof bytes and tool contents stay private. +func openAIToolProvenanceRefusal(ctx context.Context, r *openAIAgentRecoveryRequest, detail string) error { + logger.FromContext(ctx).Warn("openai.tool_provenance_refused", zap.String("check", detail)) + return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) +} + func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context, r *openAIAgentRecoveryRequest, body []byte, discoveryOnly bool) error { if discoveryOnly { hasDiscovery := false @@ -513,7 +522,7 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context, } fingerprint, ok := openAIToolFingerprint(item) if !ok || r.userID <= 0 { - return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + return openAIToolProvenanceRefusal(ctx, r, "invalid_call_or_principal") } key := r.toolKey(item.Get("call_id").String()) raw, err := s.toolProofGet(ctx, key) @@ -522,7 +531,7 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context, select { case <-ctx.Done(): timer.Stop() - return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + return openAIToolProvenanceRefusal(ctx, r, "pending_interrupted") case <-timer.C: } raw, err = s.toolProofGet(ctx, key) @@ -530,15 +539,21 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context, // same ownership refusal whether the timer or GET sees the deadline. // An independent backend timeout/error remains a store failure. if ctx.Err() == context.DeadlineExceeded && errors.Is(err, context.DeadlineExceeded) { - return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + return openAIToolProvenanceRefusal(ctx, r, "pending_timeout") } } if err != nil { return openAIRecoveryDiagnosticError("store_unavailable", "tool_provenance_unavailable", r) } var proof openAIToolProof - if len(raw) > OpenAIToolProvenanceMaxBytes || json.Unmarshal([]byte(raw), &proof) != nil || proof.Call != fingerprint { - return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + if raw == "" { + return openAIToolProvenanceRefusal(ctx, r, "record_missing") + } + if len(raw) > OpenAIToolProvenanceMaxBytes || json.Unmarshal([]byte(raw), &proof) != nil { + return openAIToolProvenanceRefusal(ctx, r, "record_unusable") + } + if proof.Call != fingerprint { + return openAIToolProvenanceRefusal(ctx, r, "fingerprint_mismatch") } handoffValid := false if h, ok := ctx.Value(openAIWSDiscoveryHandoffKey{}).(*openAIWSDiscoveryHandoff); ok && h != nil && kind == "tool_search_call" { diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index b62b17294666..efeb8365fa76 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -70,6 +70,7 @@ type openAIWSAgentRecovery struct { pendingHistoryTools map[string]openAIWSAcceptedToolHistory historicalToolIDs map[[32]byte]struct{} historicalToolIDsExhausted bool + completedTurnTools map[string]openAIWSDeliveredTool deliveredTools map[string]openAIWSDeliveredTool pendingTools map[string]openAIWSDeliveredTool localHistory openAIWSLocalHistory @@ -360,7 +361,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, previous := gjson.GetBytes(source, "previous_response_id").String() projected := false if proof, ok := req.Context().Value(openAIWSPlaintextProjectionKey{}).(*openAIWSPlaintextProjection); ok { - if proof == nil || mode != "http_bridge" || !account.IsOpenAIApiKey() || proof.accountID != account.ID || + if proof == nil || mode != "http_bridge" || !openAIWSPlaintextBridgeAccount(account) || proof.accountID != account.ID || proof.anchor.response == "" || proof.anchor != r.completedBridge || proof.anchor != openAIWSBridgeAnchor(r.request, account, previous) || r.request.owner != nil || len(r.request.items) != 0 || r.request.preservesHistory() || proof.previous != previous || r.request.previousResponseID != previous || @@ -369,6 +370,13 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, proof.controls != openAI409ControlsDigest(payload) { return openAIWSWireRefusal(ctx, "ws_projection_integrity", source, payload) } + if account.IsOpenAIOAuth() && (r.request.disallowLearning || r.request.userID <= 0 || r.request.keyID <= 0 || + !oauthBridgeDeliveredResults(source, r.request.model, previous, r.completedTurnTools) || + openAIWSHasOpaqueField(gjson.GetBytes(proof.history, "input"), 0) || + openAIAgentRecoveryInputDigest(proof.history) != proof.input || + openAI409ControlsDigest(proof.history) != proof.controls) { + return openAIWSWireRefusal(ctx, "ws_projection_integrity", source, payload) + } // Recheck the original pointer on the actual selected account before // allowing its HTTP representation to omit that pointer. if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { @@ -383,15 +391,18 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, continue } if r.historicalToolIDsExhausted { - return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r.request) + return openAIToolProvenanceRefusal(ctx, r.request, "bridge_identity_limit") } fingerprint, valid := openAIToolFingerprint(item) observed, found := r.deliveredTools[r.request.model+"\x00"+item.Get("call_id").String()] if !found && acceptsPriorToolPair(r.acceptedHistoryTools, account, r.request.model, item, proof.history) { continue } - if !valid || !found || observed.conflicted || observed.fingerprint != fingerprint || observed.accountID != account.ID || observed.config != openAIAgentRecoveryConfig(account, r.request.model) { - return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r.request) + if !found { + return openAIToolProvenanceRefusal(ctx, r.request, "bridge_delivery_missing") + } + if !valid || observed.conflicted || observed.fingerprint != fingerprint || observed.accountID != account.ID || observed.config != openAIAgentRecoveryConfig(account, r.request.model) { + return openAIToolProvenanceRefusal(ctx, r.request, "bridge_delivery_mismatch") } } handoff := &openAIWSDiscoveryHandoff{scope: *r.request, input: openAIAgentRecoveryInputDigest(proof.history), controls: openAI409ControlsDigest(proof.history), proofs: make(map[string]openAIToolProofSnapshot)} @@ -577,6 +588,7 @@ func (r *openAIWSAgentRecovery) write(payload []byte, write func() error) error } r.acceptedHistoryTools = r.pendingHistoryTools } + r.completedTurnTools = r.pendingTools r.completedResponse, r.completedAccount, r.completedModel = responseID, request.delivery.binding.accountID, request.model r.completedBridge = openAIWSBridgeResponseAnchor{response: responseID, model: request.model, session: request.session, account: request.delivery.binding.accountID, key: request.keyID, user: request.userID, group: request.groupID, config: request.delivery.binding.config} @@ -584,6 +596,7 @@ func (r *openAIWSAgentRecovery) write(payload []byte, write func() error) error r.deliveredTools = make(map[string]openAIWSDeliveredTool) } for key, observed := range r.pendingTools { + // Reuse the delivery's terminal verdict for this manager-local // proof. Shared persisted proofs additionally require encrypted // anchors, which an ordinary plaintext call does not have. @@ -1349,11 +1362,38 @@ func openAIWSToolResultDigest(item gjson.Result) [32]byte { } func acceptedOpenAIWSToolHistory(source []byte, account *Account, model string) map[string]openAIWSAcceptedToolHistory { - if account == nil || !account.IsOpenAIApiKey() || len(source) > 8<<20 || + if !openAIWSPlaintextBridgeAccount(account) || int64(len(source)) > openAIWSClientReadLimitBytesDefault || gjson.GetBytes(source, "previous_response_id").String() != "" || gjson.GetBytes(source, "conversation").Exists() || len(openAIAgentRecoveryItemDigests(source)) != 0 || !openAIEncryptedJSONUnambiguous(source) { return nil } + // Large frames can carry images or long messages unrelated to tool history. + // Bound the tool data we normalize and fingerprint, after validating the + // entire original frame (including ambiguous keys and encrypted items). + if len(source) > 8<<20 { + var tools bytes.Buffer + tools.WriteString(`{"input":[`) + fits := true + gjson.GetBytes(source, "input").ForEach(func(_, item gjson.Result) bool { + switch item.Get("type").String() { + case "function_call", "custom_tool_call", "tool_search_call", "function_call_output", "custom_tool_call_output", "tool_search_output": + if tools.Len()+len(item.Raw)+3 > 8<<20 { + fits = false + return false + } + if tools.Len() > len(`{"input":[`) { + tools.WriteByte(',') + } + tools.WriteString(item.Raw) + } + return true + }) + if !fits { + return nil + } + tools.WriteString("]}") + source = tools.Bytes() + } if _, reason := inspectOpenAIWSCompletedTools(source); reason != "" { return nil } @@ -1397,3 +1437,23 @@ func acceptsPriorToolPair(acceptedTools map[string]openAIWSAcceptedToolHistory, } return false } + +// An OAuth HTTP bridge may consume results of the immediately preceding +// delivered response. Reconnects and independent tasks have a different anchor. +func oauthBridgeDeliveredResults(source []byte, model, previous string, delivered map[string]openAIWSDeliveredTool) bool { + input := gjson.GetBytes(source, "input") + if !input.IsArray() || previous == "" { + return false + } + count := 0 + ok := true + input.ForEach(func(_, item gjson.Result) bool { + count++ + kind := item.Get("type").String() + record, found := delivered[model+"\x00"+item.Get("call_id").String()] + ok = (kind == "function_call_output" || kind == "custom_tool_call_output") && + found && !record.conflicted + return ok + }) + return count > 0 && ok +} diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 03f32ff7fe36..32705266d724 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -575,7 +575,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( // store=false cannot carry a provider-side response pointer over HTTP. // The ingress has reconstructed this same bridge's history; retain an immutable // proof before request construction, rather than trusting final wire bytes. - if !s.openAILegacyCompatibility() && account.IsOpenAIApiKey() && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + if !s.openAILegacyCompatibility() && openAIWSPlaintextBridgeAccount(account) && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { source, _ := ctx.Value(openAIWSAgentSourceKey{}).([]byte) previous := gjson.GetBytes(source, "previous_response_id").String() // The ingress has already stripped invalid item IDs. Derive that one diff --git a/backend/internal/service/openai_ws_http_bridge_account.go b/backend/internal/service/openai_ws_http_bridge_account.go new file mode 100644 index 000000000000..7733853fc447 --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_account.go @@ -0,0 +1,8 @@ +package service + +func openAIWSPlaintextBridgeAccount(account *Account) bool { + return account != nil && (account.IsOpenAIApiKey() || (account.IsOpenAIOAuth() && + !account.HasManagedOpenAIConnections() && account.AuthConnectionID == "" && + !account.IsSIWCEnabled() && !account.IsCopilotSDKEnabled() && !account.IsExcelOAuth() && + !account.IsOpenAIPassthroughEnabled())) +} From 17a9ad6ca01a321ada7b7a29225ad6ecf8aa50da Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 20 Nov 2026 22:53:02 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20=E4=BD=BF=E7=94=A8=E6=9C=89=E7=95=8C?= =?UTF-8?q?=E5=AD=97=E8=8A=82=E5=88=87=E7=89=87=E6=94=B6=E9=9B=86=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E5=B7=A5=E5=85=B7=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/openai_ws_agent_recovery.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index efeb8365fa76..0e4a73b16385 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -1371,28 +1371,27 @@ func acceptedOpenAIWSToolHistory(source []byte, account *Account, model string) // Bound the tool data we normalize and fingerprint, after validating the // entire original frame (including ambiguous keys and encrypted items). if len(source) > 8<<20 { - var tools bytes.Buffer - tools.WriteString(`{"input":[`) + const prefix = `{"input":[` + tools := []byte(prefix) fits := true gjson.GetBytes(source, "input").ForEach(func(_, item gjson.Result) bool { switch item.Get("type").String() { case "function_call", "custom_tool_call", "tool_search_call", "function_call_output", "custom_tool_call_output", "tool_search_output": - if tools.Len()+len(item.Raw)+3 > 8<<20 { + if len(tools)+len(item.Raw)+3 > 8<<20 { fits = false return false } - if tools.Len() > len(`{"input":[`) { - tools.WriteByte(',') + if len(tools) > len(prefix) { + tools = append(tools, ',') } - tools.WriteString(item.Raw) + tools = append(tools, item.Raw...) } return true }) if !fits { return nil } - tools.WriteString("]}") - source = tools.Bytes() + source = append(tools, ']', '}') } if _, reason := inspectOpenAIWSCompletedTools(source); reason != "" { return nil From f0059b9c5319ae60cd58e36a0f4e9dddeacdab41 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 20 Nov 2026 23:11:00 +0800 Subject: [PATCH 3/3] =?UTF-8?q?ci:=20=E5=AF=B9=E9=BD=90=20WebSocket=20?= =?UTF-8?q?=E5=8E=86=E5=8F=B2=E5=9F=BA=E7=BA=BF=E7=9A=84=20Ciallo=20?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/upstream-v0222-red-fixtures.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 41f9232cbb00..c32568127134 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -185,6 +185,9 @@ backend/internal/service/oauth_degradation_429_test.go backend/internal/service/oauth_degradation_validation_test.go backend/internal/service/oauth_degradation_candy_test.go +# Ciallo quality questions were introduced after the WS residual RED baseline. +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