1package provider
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "io"
8 "net/http"
9 "strings"
10 "testing"
11)
12
13// An image-only tool result must not serialize to an empty
14// function_call_output (the Responses API may reject it) and a
15// following user-message image must serialize as input_image so the
16// model actually receives the bytes.
17func TestCodexImageToolResultMirror(t *testing.T) {
18 c := NewOpenAICodex("token", "acct", "").(*codexClient)
19
20 wire, err := c.buildRequest(Request{
21 Model: "gpt-5.5",
22 Messages: []Message{
23 {Role: RoleUser, Content: []Content{TextBlock{Text: "look at this"}}},
24 {Role: RoleAssistant, Content: []Content{
25 ToolCallBlock{ID: "call_1", Name: "read", Arguments: []byte(`{"path":"x.png"}`)},
26 }},
27 {Role: RoleTool, Content: []Content{
28 ToolResultBlock{CallID: "call_1", Content: []Content{
29 ImageBlock{MimeType: "image/png", Data: []byte("png-bytes")},
30 }},
31 }},
32 // The agent loop appends this mirror after an image tool result.
33 {Role: RoleUser, Content: []Content{
34 TextBlock{Text: "Tool output included the following image content:"},
35 ImageBlock{MimeType: "image/png", Data: []byte("png-bytes")},
36 }},
37 },
38 })
39 if err != nil {
40 t.Fatal(err)
41 }
42
43 var sawFnOutput, sawInputImage bool
44 for _, item := range wire.Input {
45 switch v := item.(type) {
46 case codexFunctionCallOutput:
47 sawFnOutput = true
48 if strings.TrimSpace(v.Output) == "" {
49 t.Fatalf("image-only tool result produced empty function_call_output")
50 }
51 if !strings.Contains(strings.ToLower(v.Output), "image") {
52 t.Fatalf("placeholder should mention image, got %q", v.Output)
53 }
54 case codexInputMessage:
55 for _, ct := range v.Content {
56 if img, ok := ct.(codexInputImage); ok && img.Type == "input_image" {
57 sawInputImage = true
58 }
59 }
60 }
61 }
62 if !sawFnOutput {
63 t.Fatalf("no function_call_output emitted")
64 }
65 if !sawInputImage {
66 t.Fatalf("mirrored user image was not serialized as input_image")
67 }
68}
69
70type roundTripFunc func(*http.Request) (*http.Response, error)
71
72func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
73
74func TestCodexPreviewModelUsesCodexCLIShape(t *testing.T) {
75 c := NewOpenAICodex("token", "acct", "https://example.test/backend-api/codex/responses").(*codexClient)
76 var gotReq *http.Request
77 var gotBody codexRequest
78 c.http.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) {
79 gotReq = r
80 if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
81 t.Fatal(err)
82 }
83 return &http.Response{
84 StatusCode: http.StatusOK,
85 Header: http.Header{"Content-Type": []string{"text/event-stream"}},
86 Body: io.NopCloser(strings.NewReader("")),
87 }, nil
88 })
89
90 events, err := c.Stream(context.Background(), Request{
91 Model: "gpt-5.6-terra",
92 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
93 })
94 if err != nil {
95 t.Fatal(err)
96 }
97 for range events {
98 }
99
100 if gotReq == nil {
101 t.Fatal("request was not sent")
102 }
103 if gotReq.Header.Get("originator") != "codex_cli_rs" {
104 t.Fatalf("originator = %q", gotReq.Header.Get("originator"))
105 }
106 if gotReq.Header.Get("user-agent") != "codex_cli_rs/0.0.0" {
107 t.Fatalf("user-agent = %q", gotReq.Header.Get("user-agent"))
108 }
109 if gotBody.PromptCacheKey == "" {
110 t.Fatal("prompt_cache_key was not set")
111 }
112 if gotReq.Header.Get("session-id") != gotBody.PromptCacheKey {
113 t.Fatalf("session-id = %q, prompt_cache_key = %q", gotReq.Header.Get("session-id"), gotBody.PromptCacheKey)
114 }
115}
116
117func TestGPT56UsesNativeMaxReasoningEffort(t *testing.T) {
118 c := NewOpenAICodex("token", "acct", "").(*codexClient)
119 wire, err := c.buildRequest(Request{Model: "gpt-5.6-sol", Reasoning: "max"})
120 if err != nil {
121 t.Fatal(err)
122 }
123 if wire.Reasoning == nil || wire.Reasoning.Effort != "max" {
124 t.Fatalf("reasoning = %+v", wire.Reasoning)
125 }
126}
127
128func TestXAIResponsesUsesNamedProviderCatalogAndEndpoint(t *testing.T) {
129 named := NewOpenAIResponsesNamed("token", "https://api.x.ai/v1", "xai").(*renamedClient)
130 c := named.inner.(*codexClient)
131
132 if c.baseURL != "https://api.x.ai/v1/responses" {
133 t.Fatalf("base URL = %q", c.baseURL)
134 }
135 for _, model := range []string{"grok-4.5", "grok-build-0.1"} {
136 if _, err := c.buildRequest(Request{Model: model}); err != nil {
137 t.Errorf("build request for %s: %v", model, err)
138 }
139 }
140}
141
142func TestOpenAIGPT56DoesNotUseCodexCLIRouting(t *testing.T) {
143 named := NewOpenAIResponsesNamed("token", "https://example.test/v1/responses", "openai").(*renamedClient)
144 c := named.inner.(*codexClient)
145 var gotReq *http.Request
146 var gotBody codexRequest
147 c.http.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) {
148 gotReq = r
149 if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
150 t.Fatal(err)
151 }
152 return &http.Response{
153 StatusCode: http.StatusOK,
154 Header: http.Header{"Content-Type": []string{"text/event-stream"}},
155 Body: io.NopCloser(strings.NewReader("")),
156 }, nil
157 })
158
159 events, err := c.Stream(context.Background(), Request{
160 Model: "gpt-5.6-sol",
161 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
162 })
163 if err != nil {
164 t.Fatal(err)
165 }
166 for range events {
167 }
168
169 if gotReq == nil {
170 t.Fatal("request was not sent")
171 }
172 if gotReq.Header.Get("session-id") != "" {
173 t.Fatalf("session-id = %q", gotReq.Header.Get("session-id"))
174 }
175 if gotBody.PromptCacheKey != "" {
176 t.Fatalf("prompt_cache_key = %q", gotBody.PromptCacheKey)
177 }
178}
179
180func TestCodexNestedStreamError(t *testing.T) {
181 c := NewOpenAICodex("token", "acct", "").(*codexClient)
182 resp := &http.Response{
183 Body: io.NopCloser(strings.NewReader("data: {\"type\":\"error\",\"error\":{\"code\":\"model_not_available\",\"message\":\"limited preview\"}}\n\n")),
184 }
185 out := make(chan Event, 16)
186 go c.runStream(context.Background(), resp, Request{Model: "gpt-5.6-sol"}, out)
187
188 var got error
189 for ev := range out {
190 if done, ok := ev.(EventDone); ok {
191 got = done.Err
192 }
193 }
194 if got == nil || got.Error() != "codex error: limited preview" {
195 t.Fatalf("error = %v", got)
196 }
197}
198
199// TestCodexSubscriptionAlwaysUsesCodexCLIShape pins the ChatGPT
200// subscription backend to the Codex CLI request identity for every
201// model. The backend load-sheds unrecognized originator/user-agent
202// pairs with "Our servers are currently overloaded" stream errors
203// even when capacity is fine, so the CLI shape is required for
204// reliable service, not just for preview-model admission.
205func TestCodexSubscriptionAlwaysUsesCodexCLIShape(t *testing.T) {
206 c := NewOpenAICodex("token", "acct", "https://example.test/backend-api/codex/responses").(*codexClient)
207 var gotReq *http.Request
208 var body bytes.Buffer
209 c.http.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) {
210 gotReq = r
211 _, _ = body.ReadFrom(r.Body)
212 return &http.Response{
213 StatusCode: http.StatusOK,
214 Header: http.Header{"Content-Type": []string{"text/event-stream"}},
215 Body: io.NopCloser(strings.NewReader("")),
216 }, nil
217 })
218
219 events, err := c.Stream(context.Background(), Request{
220 Model: "gpt-5.6-sol",
221 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
222 })
223 if err != nil {
224 t.Fatal(err)
225 }
226 for range events {
227 }
228
229 if gotReq == nil {
230 t.Fatal("request was not sent")
231 }
232 if gotReq.Header.Get("originator") != "codex_cli_rs" {
233 t.Fatalf("originator = %q", gotReq.Header.Get("originator"))
234 }
235 if gotReq.Header.Get("user-agent") != "codex_cli_rs/0.0.0" {
236 t.Fatalf("user-agent = %q", gotReq.Header.Get("user-agent"))
237 }
238 if gotReq.Header.Get("session-id") == "" {
239 t.Fatal("session-id header missing")
240 }
241 if !strings.Contains(body.String(), "prompt_cache_key") {
242 t.Fatalf("request missing prompt_cache_key: %s", body.String())
243 }
244}