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