fix(openai): ignore standalone named delegation in continuation checks and reset WS HTTP bridge on window rollover

This commit is contained in:
dzolv committed 2026-12-02 16:23:39 +08:00
1 parent 380ab13810
commit 905893ca9e
7 files changed
+371 -38

No files matched your search

@@ -50,8 +50,11 @@ func sanitizeOpenAIResponsesOrphanToolOutputs(reqBody map[string]any, input []an
// named function outputs without a preceding function call. Preserve
// their native type, namespace and output instead of silently dropping
// the request that started the turn.
if callID == "" && strings.TrimSpace(firstNonEmptyString(item["type"])) == "function_call_output" &&
strings.TrimSpace(firstNonEmptyString(item["name"])) != "" {
if isStandaloneNamedFunctionCallOutput(
firstNonEmptyString(item["type"]),
callID,
firstNonEmptyString(item["name"]),
) {
normalized = append(normalized, rawItem)
continue
}
@@ -50,6 +50,14 @@ func isCodexToolCallOutputItemType(typ string) bool {
}
}
// isStandaloneNamedFunctionCallOutput 判断是否为 Codex 注入的带名称、无 call_id 的独立输入(如任务派发 create_thread)。
// 此类项属于客户端注入的独立上下文而非需要前置工具调用配对的工具结果。
func isStandaloneNamedFunctionCallOutput(itemType, callID, name string) bool {
return strings.TrimSpace(callID) == "" &&
strings.TrimSpace(itemType) == "function_call_output" &&
strings.TrimSpace(name) != ""
}
// NeedsToolContinuation 判定请求是否需要工具调用续链处理。
// 满足以下任一信号即视为续链:previous_response_id、input 内包含工具输出/item_reference、
// 或显式声明 tools/tool_choice。
@@ -112,9 +120,13 @@ func AnalyzeToolContinuationSignals(reqBody map[string]any) ToolContinuationSign
signals.HasToolCallContext = true
}
case isCodexToolCallOutputItemType(itemType):
signals.HasFunctionCallOutput = true
callID, _ := itemMap["call_id"].(string)
callID = strings.TrimSpace(callID)
name, _ := itemMap["name"].(string)
if isStandaloneNamedFunctionCallOutput(itemType, callID, name) {
continue
}
signals.HasFunctionCallOutput = true
if callID == "" {
signals.HasFunctionCallOutputMissingCallID = true
continue
@@ -175,8 +187,11 @@ func ValidateFunctionCallOutputContextBytes(body []byte) FunctionCallOutputValid
itemType := item.Get("type").String()
switch {
case isCodexToolCallOutputItemType(itemType):
result.HasFunctionCallOutput = true
callID := strings.TrimSpace(item.Get("call_id").String())
if isStandaloneNamedFunctionCallOutput(itemType, callID, item.Get("name").String()) {
return true
}
result.HasFunctionCallOutput = true
if callID == "" {
result.HasFunctionCallOutputMissingCallID = true
return true
@@ -249,8 +264,11 @@ func AnalyzeToolCallOutputContextCoverageBytes(body []byte) ToolCallOutputContex
itemType := item.Get("type").String()
switch {
case isCodexToolCallOutputItemType(itemType):
coverage.HasFunctionCallOutput = true
callID := strings.TrimSpace(item.Get("call_id").String())
if isStandaloneNamedFunctionCallOutput(itemType, callID, item.Get("name").String()) {
return
}
coverage.HasFunctionCallOutput = true
if callID == "" {
missingCallID = true
return
@@ -323,6 +341,11 @@ func ValidateFunctionCallOutputContext(reqBody map[string]any) FunctionCallOutpu
itemType, _ := itemMap["type"].(string)
switch {
case isCodexToolCallOutputItemType(itemType):
callID, _ := itemMap["call_id"].(string)
name, _ := itemMap["name"].(string)
if isStandaloneNamedFunctionCallOutput(itemType, callID, name) {
continue
}
result.HasFunctionCallOutput = true
case isCodexToolCallContextItemType(itemType):
callID, _ := itemMap["call_id"].(string)
@@ -351,6 +374,10 @@ func ValidateFunctionCallOutputContext(reqBody map[string]any) FunctionCallOutpu
case isCodexToolCallOutputItemType(itemType):
callID, _ := itemMap["call_id"].(string)
callID = strings.TrimSpace(callID)
name, _ := itemMap["name"].(string)
if isStandaloneNamedFunctionCallOutput(itemType, callID, name) {
continue
}
if callID == "" {
result.HasFunctionCallOutputMissingCallID = true
continue
@@ -51,6 +51,9 @@ func TestHasFunctionCallOutput(t *testing.T) {
"input": []any{map[string]any{"type": typ}},
}), typ)
}
require.False(t, HasFunctionCallOutput(map[string]any{
"input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}},
}))
require.False(t, HasFunctionCallOutput(map[string]any{
"input": "text",
}))
@@ -100,6 +103,9 @@ func TestHasFunctionCallOutputMissingCallID(t *testing.T) {
require.True(t, HasFunctionCallOutputMissingCallID(map[string]any{
"input": []any{map[string]any{"type": "tool_search_output"}},
}))
require.False(t, HasFunctionCallOutputMissingCallID(map[string]any{
"input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}},
}))
require.False(t, HasFunctionCallOutputMissingCallID(map[string]any{
"input": []any{map[string]any{"type": "tool_search_output", "call_id": "call_1"}},
}))
@@ -134,6 +140,10 @@ func TestValidateFunctionCallOutputContextBytesMatchesMapValidation(t *testing.T
name: "missing_call_id",
body: map[string]any{"input": []any{map[string]any{"type": "function_call_output"}}},
},
{
name: "named_standalone_delegation_without_call_id",
body: map[string]any{"input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}},
},
{
name: "call_id_without_reference",
body: map[string]any{"input": []any{map[string]any{"type": "function_call_output", "call_id": "call_1"}}},
@@ -263,6 +273,34 @@ func TestAnalyzeToolCallOutputContextCoverageBytes(t *testing.T) {
hasOutput: true,
coversAllIDs: false,
},
{
name: "standalone_named_delegation_only_does_not_require_replay",
body: map[string]any{"input": []any{
map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"},
map[string]any{"type": "message", "role": "user", "content": "summary"},
}},
hasOutput: false,
coversAllIDs: false,
},
{
name: "standalone_named_delegation_with_covered_output",
body: map[string]any{"input": []any{
map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"},
map[string]any{"type": "function_call", "call_id": "call_a"},
map[string]any{"type": "function_call_output", "call_id": "call_a"},
}},
hasOutput: true,
coversAllIDs: true,
},
{
name: "standalone_named_delegation_with_unpaired_output_requires_replay",
body: map[string]any{"input": []any{
map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"},
map[string]any{"type": "function_call_output", "call_id": "call_b"},
}},
hasOutput: true,
coversAllIDs: false,
},
{
name: "mixed_context_and_reference_cover_all",
body: map[string]any{"input": []any{
@@ -202,6 +202,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
requestedReasoningEffort *string
}
ingressSessionOriginalModel := ""
activeTurnMetadata := ""
initialHandshakeWindowID := ""
if c != nil {
activeTurnMetadata = strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader))
initialHandshakeWindowID = strings.TrimSpace(c.GetHeader("x-codex-window-id"))
}
applyPayloadMutation := func(current []byte, path string, value any) ([]byte, error) {
next, err := sjson.SetBytes(current, path, value)
@@ -318,8 +324,16 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
nil,
)
}
if turnMetadata := strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader)); turnMetadata != "" {
next, setErr := applyPayloadMutation(normalized, "client_metadata."+openAIWSTurnMetadataHeader, turnMetadata)
frameTurnMetadata := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata."+openAIWSTurnMetadataHeader).String())
frameWindowID := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata.x-codex-window-id").String())
if frameTurnMetadata != "" {
activeTurnMetadata = frameTurnMetadata
} else if frameWindowID != "" {
if activeTurnMetadata != "" && strings.TrimSpace(gjson.Get(activeTurnMetadata, "window_id").String()) != frameWindowID {
activeTurnMetadata = ""
}
} else if activeTurnMetadata != "" {
next, setErr := applyPayloadMutation(normalized, "client_metadata."+openAIWSTurnMetadataHeader, activeTurnMetadata)
if setErr != nil {
return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", setErr)
}
@@ -594,6 +608,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
}
defer history.close()
historyLost := false
lastBridgeWindowID := initialHandshakeWindowID
var bridgeReplayInput []json.RawMessage
bridgeReplayInputExists := false
var bridgeAccountFailoverInput []json.RawMessage
@@ -615,6 +630,40 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
if c != nil && sessionHash != "" {
c.Set(openAIWSIngressSessionHashContextKey, sessionHash)
}
boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary(
currentBridgePayload.payloadRaw,
lastBridgeWindowID,
)
if boundaryErr != nil {
return fmt.Errorf("normalize Codex websocket http bridge context-window boundary: %w", boundaryErr)
}
if contextWindowBoundary.Changed {
if contextWindowBoundary.PreviousResponseIDRemoved {
responsesLite := isOpenAIResponsesLiteWebSocketPayload(boundaryPayload)
if compatBody, compatChanged, compatErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, boundaryPayload, account, responsesLite); compatErr != nil {
return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatErr)
} else if compatChanged {
boundaryPayload = compatBody
}
}
currentBridgePayload.payloadRaw = boundaryPayload
currentBridgePayload.payloadBytes = len(boundaryPayload)
currentBridgePayload.previousResponseID = ""
historyLost = false
bridgeReplayInput = nil
bridgeReplayInputExists = false
bridgeAccountFailoverInput = nil
bridgeAccountFailoverInputExists = false
history.resize(0)
logOpenAIWSModeInfo(
"ingress_ws_http_bridge_context_window_changed account_id=%d turn=%d action=reset_bridge_replay_state previous_window_id=%s current_window_id=%s previous_response_id_removed=%v",
account.ID,
turn,
truncateOpenAIWSLogValue(lastBridgeWindowID, openAIWSIDValueMaxLen),
truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen),
contextWindowBoundary.PreviousResponseIDRemoved,
)
}
// 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。
// 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。
if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, sessionHash); len(invalidDigests) > 0 {
@@ -813,6 +862,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
// publishing it by session hash would leak it to independent bridges.
turnState = bridgeTurnState
}
if contextWindowBoundary.WindowID != "" {
lastBridgeWindowID = contextWindowBoundary.WindowID
}
responseID := strings.TrimSpace(result.RequestID)
if responseID != "" && stateStore != nil {
ttl := s.openAIWSResponseStickyTTL()
@@ -1444,7 +1496,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
turnPrevRecoveryTried := false
lastTurnFinishedAt := time.Time{}
lastTurnResponseID := ""
lastTurnWindowID := ""
lastTurnWindowID := initialHandshakeWindowID
lastTurnPayload := []byte(nil)
var lastTurnStrictState *openAIWSIngressPreviousTurnStrictState
lastTurnReplayInput := []json.RawMessage(nil)
@@ -1576,6 +1628,40 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
}
}
skipBeforeTurn = false
boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary(
currentPayload,
lastTurnWindowID,
)
if boundaryErr != nil {
return fmt.Errorf("normalize Codex websocket context-window boundary: %w", boundaryErr)
}
if contextWindowBoundary.Changed {
if contextWindowBoundary.PreviousResponseIDRemoved {
responsesLite := isOpenAIResponsesLiteWebSocketPayload(boundaryPayload)
if compatBody, compatChanged, compatErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, boundaryPayload, account, responsesLite); compatErr != nil {
return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatErr)
} else if compatChanged {
boundaryPayload = compatBody
}
}
currentPayload = boundaryPayload
currentPayloadBytes = len(boundaryPayload)
lastTurnResponseID = ""
lastTurnPayload = nil
lastTurnStrictState = nil
lastTurnReplayInput = nil
lastTurnReplayInputExists = false
lastTurnReplayInputComplete = false
logOpenAIWSModeInfo(
"ingress_ws_context_window_changed account_id=%d turn=%d conn_id=%s action=break_previous_response_chain previous_window_id=%s current_window_id=%s previous_response_id_removed=%v",
account.ID,
turn,
truncateOpenAIWSLogValue(sessionConnID, openAIWSIDValueMaxLen),
truncateOpenAIWSLogValue(lastTurnWindowID, openAIWSIDValueMaxLen),
truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen),
contextWindowBoundary.PreviousResponseIDRemoved,
)
}
// 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。
// 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。
if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, sessionHash); len(invalidDigests) > 0 {
@@ -1590,33 +1676,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
lastTurnReplayInput, _ = stripOpenAIInvalidEncryptedContentFromReplayItems(lastTurnReplayInput, invalidDigests)
}
}
boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary(
currentPayload,
lastTurnWindowID,
)
if boundaryErr != nil {
return fmt.Errorf("normalize Codex websocket context-window boundary: %w", boundaryErr)
}
if contextWindowBoundary.Changed {
currentPayload = boundaryPayload
currentPayloadBytes = len(boundaryPayload)
logOpenAIWSModeInfo(
"ingress_ws_context_window_changed account_id=%d turn=%d conn_id=%s action=break_previous_response_chain previous_window_id=%s current_window_id=%s previous_response_id_removed=%v",
account.ID,
turn,
truncateOpenAIWSLogValue(sessionConnID, openAIWSIDValueMaxLen),
truncateOpenAIWSLogValue(lastTurnWindowID, openAIWSIDValueMaxLen),
truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen),
contextWindowBoundary.PreviousResponseIDRemoved,
)
}
currentPreviousResponseID := openAIWSPayloadStringFromRaw(currentPayload, "previous_response_id")
expectedPrev := strings.TrimSpace(lastTurnResponseID)
if contextWindowBoundary.Changed {
// A context-window rollover is a new Responses root. Do not infer a
// continuation anchor from the response produced in the old window.
expectedPrev = ""
}
toolSignals := ToolContinuationSignals{
HasFunctionCallOutput: openAIWSRawPayloadHasToolCallOutput(currentPayload),
}
@@ -1024,6 +1024,22 @@ func TestOpenAIWSRawPayloadHasToolCallOutput(t *testing.T) {
payload := []byte(`{"input":[{"type":"input_text","text":"hello"}]}`)
require.False(t, openAIWSRawPayloadHasToolCallOutput(payload))
})
t.Run("standalone_named_delegation_output_ignored", func(t *testing.T) {
t.Parallel()
payload := []byte(`{"input":[{"type":"function_call_output","name":"create_thread","output":"delegated"}]}`)
require.False(t, openAIWSRawPayloadHasToolCallOutput(payload))
items := []json.RawMessage{
json.RawMessage(`{"type":"function_call_output","name":"create_thread","output":"delegated"}`),
}
require.False(t, openAIWSRawItemsHasFunctionCallOutput(items))
pairedItems := []json.RawMessage{
json.RawMessage(`{"type":"function_call_output","name":"create_thread","output":"delegated"}`),
json.RawMessage(`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"}`),
json.RawMessage(`{"type":"function_call_output","call_id":"call_1","output":"ok"}`),
}
require.True(t, openAIWSRawItemsHaveToolCallContextForOutputs(pairedItems))
})
}
func TestSetOpenAIWSPayloadInputSequence(t *testing.T) {
@@ -645,9 +645,18 @@ func openAIWSRawItemsHasPrefix(items []json.RawMessage, prefix []json.RawMessage
func openAIWSRawItemsHasFunctionCallOutput(items []json.RawMessage) bool {
for _, item := range items {
if isCodexToolCallOutputItemType(gjson.GetBytes(item, "type").String()) {
return true
itemType := gjson.GetBytes(item, "type").String()
if !isCodexToolCallOutputItemType(itemType) {
continue
}
if isStandaloneNamedFunctionCallOutput(
itemType,
gjson.GetBytes(item, "call_id").String(),
gjson.GetBytes(item, "name").String(),
) {
continue
}
return true
}
return false
}
@@ -667,6 +676,9 @@ func openAIWSRawItemsHaveToolCallContextForOutputs(items []json.RawMessage) bool
contextCallIDs[callID] = struct{}{}
}
case isCodexToolCallOutputItemType(itemType):
if isStandaloneNamedFunctionCallOutput(itemType, callID, gjson.GetBytes(item, "name").String()) {
continue
}
if callID == "" {
return false
}
@@ -729,14 +741,21 @@ func openAIWSRawPayloadHasToolCallOutput(payload []byte) bool {
}
if input.IsArray() {
for _, item := range input.Array() {
if isCodexToolCallOutputItemType(item.Get("type").String()) {
return true
itemType := item.Get("type").String()
if !isCodexToolCallOutputItemType(itemType) {
continue
}
if isStandaloneNamedFunctionCallOutput(itemType, item.Get("call_id").String(), item.Get("name").String()) {
continue
}
return true
}
return false
}
if input.Type == gjson.JSON {
return isCodexToolCallOutputItemType(input.Get("type").String())
itemType := input.Get("type").String()
return isCodexToolCallOutputItemType(itemType) &&
!isStandaloneNamedFunctionCallOutput(itemType, input.Get("call_id").String(), input.Get("name").String())
}
return false
}
@@ -263,3 +263,172 @@ func TestOpenAIWSHTTPBridgeLaterTurn429RetriesCurrentTurnOnReplacementAccount(t
require.Equal(t, scopeCodexAccountIdentityValue(&nextAccount, 0, "thread", "client-thread"), gjson.GetBytes(upstream.bodies[2], "client_metadata.thread_id").String())
require.Empty(t, upstream.requests[2].Header.Get(openAIWSTurnStateHeader))
}
func TestOpenAIWSHTTPBridgeDelegatedSessionCompactionDoesNotReplayOldWindowHistory(t *testing.T) {
gin.SetMode(gin.TestMode)
cfg := &config.Config{}
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.OAuthEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
upstream := &httpUpstreamRecorder{responses: []*http.Response{
{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_first\",\"output\":[{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"first-ok\"}]},{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"inspect\",\"arguments\":\"{}\"}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n",
)),
},
{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_second\",\"output\":[{\"id\":\"msg_2\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"second-ok\"}]}],\"usage\":{\"input_tokens\":2,\"output_tokens\":1}}}\n\n",
)),
},
{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_third\",\"output\":[{\"id\":\"msg_3\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"third-ok\"}]}],\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n",
)),
},
{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fourth\",\"output\":[{\"id\":\"msg_4\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"fourth-ok\"}]}],\"usage\":{\"input_tokens\":4,\"output_tokens\":1}}}\n\n",
)),
},
}}
svc := &OpenAIGatewayService{
cfg: cfg,
httpUpstream: upstream,
cache: &stubGatewayCache{},
openaiWSResolver: NewOpenAIWSProtocolResolver(cfg),
toolCorrector: NewCodexToolCorrector(),
}
account := &Account{
ID: 131, Name: "bridge-compaction", Platform: PlatformOpenAI, Type: AccountTypeOAuth,
Status: StatusActive, Schedulable: true, Concurrency: 1,
Extra: map[string]any{"openai_oauth_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge},
Credentials: map[string]any{"chatgpt_account_id": "account-a", "chatgpt_user_id": "user-a"},
}
serverErrCh := make(chan error, 1)
wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
if err != nil {
serverErrCh <- err
return
}
defer func() { _ = conn.CloseNow() }()
rec := httptest.NewRecorder()
ginCtx, _ := gin.CreateTestContext(rec)
ginCtx.Request = r.Clone(r.Context())
readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
_, firstMessage, readErr := conn.Read(readCtx)
cancel()
if readErr != nil {
serverErrCh <- readErr
return
}
serverErrCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token-a", firstMessage, nil)
}))
defer wsServer.Close()
dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
clientConn, _, err := websocket.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), &websocket.DialOptions{
HTTPHeader: http.Header{
openAIWSTurnMetadataHeader: []string{`{"window_id":"window-0"}`},
},
})
cancel()
require.NoError(t, err)
defer func() { _ = clientConn.CloseNow() }()
// Turn 1: delegated session starts in window-0 with create_thread (no call_id).
writeCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","input":[{"type":"function_call_output","name":"create_thread","output":"delegated task"},{"role":"user","content":"first-window-msg"}]}`))
cancel()
require.NoError(t, err)
readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_, completed1, err := clientConn.Read(readCtx)
cancel()
require.NoError(t, err)
require.Equal(t, "resp_first", gjson.GetBytes(completed1, "response.id").String())
// Turn 2: normal tool continuation in window-0.
writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","previous_response_id":"resp_first","input":[{"type":"function_call_output","call_id":"call_1","output":"tool-ok"}]}`))
cancel()
require.NoError(t, err)
readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
_, completed2, err := clientConn.Read(readCtx)
cancel()
require.NoError(t, err)
require.Equal(t, "resp_second", gjson.GetBytes(completed2, "response.id").String())
// Turn 3: context compaction replaces history, omits previous_response_id,
// retains create_thread (without call_id), and rotates window_id to window-1.
writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","client_metadata":{"x-codex-turn-metadata":"{\"window_id\":\"window-1\"}"},"input":[{"type":"function_call_output","name":"create_thread","output":"delegated task"},{"role":"user","content":"compacted-summary"}]}`))
cancel()
require.NoError(t, err)
readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
_, completed3, err := clientConn.Read(readCtx)
cancel()
require.NoError(t, err)
require.Equal(t, "resp_third", gjson.GetBytes(completed3, "response.id").String())
// Turn 4: follow-up turn in window-1 omitting client_metadata must stay in window-1
// and stitch only from Turn 3's compacted root.
writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","previous_response_id":"resp_third","input":[{"role":"user","content":"after-compaction"}]}`))
cancel()
require.NoError(t, err)
readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
_, completed4, err := clientConn.Read(readCtx)
cancel()
require.NoError(t, err)
require.Equal(t, "resp_fourth", gjson.GetBytes(completed4, "response.id").String())
_ = clientConn.Close(websocket.StatusNormalClosure, "done")
select {
case proxyErr := <-serverErrCh:
require.NoError(t, proxyErr)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for bridge completion")
}
require.Len(t, upstream.bodies, 4)
// Turn 2 stitched Turn 1 history + call_1 + tool-ok.
require.Contains(t, string(upstream.bodies[1]), "first-window-msg")
require.Contains(t, string(upstream.bodies[1]), "call_1")
// Turn 3 (compacted window-1) must NOT replay old window-0 history ("first-window-msg" or "call_1"),
// and must preserve frame-level window-1 instead of overwriting it with handshake window-0.
scopedWindow1 := scopeCodexAccountIdentityValue(account, 0, "window", "window-1")
require.NotContains(t, string(upstream.bodies[2]), "first-window-msg")
require.NotContains(t, string(upstream.bodies[2]), "call_1")
require.Contains(t, string(upstream.bodies[2]), "compacted-summary")
require.Equal(t, scopedWindow1, gjson.Get(gjson.GetBytes(upstream.bodies[2], "client_metadata.x-codex-turn-metadata").String(), "window_id").String())
// Turn 4 (continuation in window-1) stitches from Turn 3's compacted history and stays on window-1.
require.NotContains(t, string(upstream.bodies[3]), "first-window-msg")
require.NotContains(t, string(upstream.bodies[3]), "call_1")
require.Contains(t, string(upstream.bodies[3]), "compacted-summary")
require.Contains(t, string(upstream.bodies[3]), "after-compaction")
require.Equal(t, scopedWindow1, gjson.Get(gjson.GetBytes(upstream.bodies[3], "client_metadata.x-codex-turn-metadata").String(), "window_id").String())
}