v0.2.58 482b666

provider_test.go RawHistoryFolder

1package provider
2
3import (
4	"context"
5	"net/http"
6	"net/http/httptest"
7	"strings"
8	"testing"
9)
10
11func TestSSEParse(t *testing.T) {
12	r := strings.NewReader("event: foo\ndata: {\"a\":1}\n\ndata: hello\ndata: world\n\n")
13	ch := make(chan sseEvent, 4)
14	go readSSE(r, ch)
15
16	e := <-ch
17	if e.Event != "foo" || e.Data != `{"a":1}` {
18		t.Fatalf("event 1: %+v", e)
19	}
20	e = <-ch
21	if e.Event != "" || e.Data != "hello\nworld" {
22		t.Fatalf("event 2: %+v", e)
23	}
24	if _, ok := <-ch; ok {
25		t.Fatalf("channel not closed")
26	}
27}
28
29func TestModelCatalog(t *testing.T) {
30	if len(Catalog) == 0 {
31		t.Fatal("empty catalog")
32	}
33	if _, err := FindModel("anthropic", "claude-sonnet-4-5"); err != nil {
34		t.Fatal(err)
35	}
36	if _, err := FindModel("openai", "gpt-5"); err != nil {
37		t.Fatal(err)
38	}
39	if _, err := FindModel("", "nope"); err == nil {
40		t.Fatal("expected error")
41	}
42}
43
44func TestComputeCost(t *testing.T) {
45	m, _ := FindModel("anthropic", "claude-sonnet-4-5")
46	cost := ComputeCost(m, Usage{InputTokens: 1_000_000, OutputTokens: 1_000_000})
47	want := m.PriceInput + m.PriceOutput
48	if cost != want {
49		t.Fatalf("cost=%v want=%v", cost, want)
50	}
51}
52
53func TestAnthropicErrorStatus(t *testing.T) {
54	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
55		w.WriteHeader(http.StatusUnauthorized)
56		_, _ = w.Write([]byte(`{"error":{"type":"auth","message":"bad key"}}`))
57	}))
58	defer srv.Close()
59
60	c := NewAnthropic("x", srv.URL)
61	_, err := c.Stream(context.Background(), Request{Model: "claude-sonnet-4-5"})
62	if err == nil || !strings.Contains(err.Error(), "401") {
63		t.Fatalf("want 401 err, got %v", err)
64	}
65}
66
67func TestOpenAIErrorStatus(t *testing.T) {
68	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
69		w.WriteHeader(http.StatusBadRequest)
70		_, _ = w.Write([]byte(`{"error":{"message":"nope"}}`))
71	}))
72	defer srv.Close()
73
74	c := NewOpenAI("x", srv.URL)
75	_, err := c.Stream(context.Background(), Request{Model: "gpt-5"})
76	if err == nil || !strings.Contains(err.Error(), "400") {
77		t.Fatalf("want 400 err, got %v", err)
78	}
79}
80
81func TestAnthropicAdaptiveThinking(t *testing.T) {
82	c := NewAnthropic("x", "").(*anthropicClient)
83	temp := float32(0.7)
84
85	// Opus 4.8 -> adaptive thinking, effort set, no budget, no temperature.
86	wire, err := c.buildRequest(Request{
87		Model:       "claude-opus-4-8",
88		Reasoning:   "high",
89		Temperature: &temp,
90		Messages:    []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
91	})
92	if err != nil {
93		t.Fatal(err)
94	}
95	if wire.Thinking == nil || wire.Thinking.Type != "adaptive" {
96		t.Fatalf("want adaptive thinking, got %+v", wire.Thinking)
97	}
98	if wire.Thinking.BudgetTokens != 0 {
99		t.Fatalf("adaptive must not send budget_tokens, got %d", wire.Thinking.BudgetTokens)
100	}
101	if wire.OutputConfig == nil || wire.OutputConfig.Effort != "high" {
102		t.Fatalf("want effort=high, got %+v", wire.OutputConfig)
103	}
104	if wire.Temperature != nil {
105		t.Fatalf("adaptive must drop temperature, got %v", *wire.Temperature)
106	}
107
108	// maximum -> xhigh effort.
109	wire, err = c.buildRequest(Request{
110		Model:     "claude-opus-4-8",
111		Reasoning: "maximum",
112		Messages:  []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
113	})
114	if err != nil {
115		t.Fatal(err)
116	}
117	if wire.OutputConfig == nil || wire.OutputConfig.Effort != "xhigh" {
118		t.Fatalf("want effort=xhigh, got %+v", wire.OutputConfig)
119	}
120
121	// Opus 4.5 -> budget-based thinking, no output_config, temperature kept.
122	wire, err = c.buildRequest(Request{
123		Model:       "claude-opus-4-5",
124		Reasoning:   "high",
125		Temperature: &temp,
126		Messages:    []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
127	})
128	if err != nil {
129		t.Fatal(err)
130	}
131	if wire.Thinking == nil || wire.Thinking.Type != "enabled" || wire.Thinking.BudgetTokens <= 0 {
132		t.Fatalf("want budget thinking, got %+v", wire.Thinking)
133	}
134	if wire.OutputConfig != nil {
135		t.Fatalf("budget models must not send output_config, got %+v", wire.OutputConfig)
136	}
137	if wire.Temperature == nil || *wire.Temperature != temp {
138		t.Fatalf("budget model should keep temperature, got %v", wire.Temperature)
139	}
140}
141
142func TestAnthropicBuildRequestStripsAssistantImages(t *testing.T) {
143	c := NewAnthropic("x", "").(*anthropicClient)
144	wire, err := c.buildRequest(Request{
145		Model: "claude-sonnet-4-5",
146		Messages: []Message{
147			{Role: RoleUser, Content: []Content{TextBlock{Text: "make an image"}}},
148			{Role: RoleAssistant, Content: []Content{
149				TextBlock{Text: "done"},
150				ImageBlock{MimeType: "image/png", Data: []byte("png")},
151				TextBlock{Text: "Saved image: `zot-gemini-image-x.png`"},
152			}},
153			{Role: RoleUser, Content: []Content{TextBlock{Text: "hello"}}},
154		},
155	})
156	if err != nil {
157		t.Fatal(err)
158	}
159	if len(wire.Messages) != 3 {
160		t.Fatalf("messages=%d", len(wire.Messages))
161	}
162	assistant := wire.Messages[1]
163	if assistant.Role != "assistant" {
164		t.Fatalf("role=%q", assistant.Role)
165	}
166	if len(assistant.Content) != 2 {
167		t.Fatalf("assistant content=%+v", assistant.Content)
168	}
169	for _, b := range assistant.Content {
170		if _, ok := b.(anthImageBlock); ok {
171			t.Fatalf("assistant image block was not stripped: %+v", assistant.Content)
172		}
173	}
174}
175
176func TestAnthropicStreamHappyPath(t *testing.T) {
177	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
178		w.Header().Set("content-type", "text/event-stream")
179		w.WriteHeader(http.StatusOK)
180		fl, _ := w.(http.Flusher)
181		write := func(s string) {
182			_, _ = w.Write([]byte(s))
183			if fl != nil {
184				fl.Flush()
185			}
186		}
187		write("event: message_start\ndata: {\"message\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n")
188		write("event: content_block_start\ndata: {\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n")
189		write("event: content_block_delta\ndata: {\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n")
190		write("event: content_block_stop\ndata: {\"index\":0}\n\n")
191		write("event: message_delta\ndata: {\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5}}\n\n")
192		write("event: message_stop\ndata: {}\n\n")
193	}))
194	defer srv.Close()
195
196	c := NewAnthropic("x", srv.URL)
197	evs, err := c.Stream(context.Background(), Request{Model: "claude-sonnet-4-5"})
198	if err != nil {
199		t.Fatal(err)
200	}
201	var gotText string
202	var done EventDone
203	for ev := range evs {
204		switch e := ev.(type) {
205		case EventTextDelta:
206			gotText += e.Delta
207		case EventDone:
208			done = e
209		}
210	}
211	if gotText != "hi" {
212		t.Fatalf("text=%q", gotText)
213	}
214	if done.Stop != StopEnd {
215		t.Fatalf("stop=%v", done.Stop)
216	}
217}
218
219func TestOpenAICompatAnthropicReasoningEffort(t *testing.T) {
220	c := NewOpenRouter("token", "").(*openaiClient)
221	wire, err := c.buildRequest(Request{
222		Model:     "anthropic/claude-opus-4.8",
223		Reasoning: "maximum",
224		Messages:  []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
225	})
226	if err != nil {
227		t.Fatal(err)
228	}
229	if wire.ReasoningEffort != "xhigh" {
230		t.Fatalf("want xhigh for adaptive Anthropic model over OpenAI-compatible wire, got %q", wire.ReasoningEffort)
231	}
232
233	wire, err = c.buildRequest(Request{
234		Model:     "gpt-5.1",
235		Reasoning: "maximum",
236		Messages:  []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
237	})
238	if err != nil {
239		t.Fatal(err)
240	}
241	if wire.ReasoningEffort != "high" {
242		t.Fatalf("want generic OpenAI-compatible maximum clamped to high, got %q", wire.ReasoningEffort)
243	}
244}
245
246func TestOpenAIBuildRequestSkipsReasoningOnlyAssistantMessages(t *testing.T) {
247	c := NewKimi("token", "").(*openaiClient)
248	wire, err := c.buildRequest(Request{
249		Model: "kimi-for-coding",
250		Messages: []Message{
251			{Role: RoleUser, Content: []Content{TextBlock{Text: "first"}}},
252			{Role: RoleAssistant, Content: []Content{ReasoningBlock{Summary: "thinking only"}}},
253			{Role: RoleUser, Content: []Content{TextBlock{Text: "second"}}},
254		},
255	})
256	if err != nil {
257		t.Fatal(err)
258	}
259	for i, msg := range wire.Messages {
260		if msg.Role == "assistant" && msg.Content == nil && len(msg.ToolCalls) == 0 {
261			t.Fatalf("message %d is empty assistant: %+v", i, msg)
262		}
263	}
264	if got := len(wire.Messages); got != 2 {
265		t.Fatalf("messages=%d want 2 after skipping reasoning-only assistant", got)
266	}
267}
268
269func TestOpenAIStreamHappyPath(t *testing.T) {
270	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
271		w.Header().Set("content-type", "text/event-stream")
272		w.WriteHeader(http.StatusOK)
273		fl, _ := w.(http.Flusher)
274		write := func(s string) {
275			_, _ = w.Write([]byte(s))
276			if fl != nil {
277				fl.Flush()
278			}
279		}
280		write("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hel\"},\"finish_reason\":null}]}\n\n")
281		write("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"},\"finish_reason\":\"stop\"}]}\n\n")
282		write("data: {\"choices\":[],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":2}}\n\n")
283		write("data: [DONE]\n\n")
284	}))
285	defer srv.Close()
286
287	c := NewOpenAI("x", srv.URL)
288	evs, err := c.Stream(context.Background(), Request{Model: "gpt-5"})
289	if err != nil {
290		t.Fatal(err)
291	}
292	var gotText string
293	var done EventDone
294	for ev := range evs {
295		switch e := ev.(type) {
296		case EventTextDelta:
297			gotText += e.Delta
298		case EventDone:
299			done = e
300		}
301	}
302	if gotText != "hello" {
303		t.Fatalf("text=%q", gotText)
304	}
305	if done.Stop != StopEnd {
306		t.Fatalf("stop=%v", done.Stop)
307	}
308}
309
310func TestDiscoverOpenRouter(t *testing.T) {
311	const body = `{"data":[
312		{"id":"x/full","pricing":{"prompt":"0.000003","completion":"0.000015"},
313		 "context_length":200000,"top_provider":{"max_completion_tokens":64000},
314		 "supported_parameters":["reasoning"]},
315		{"id":"x/fallback","top_provider":{"context_length":128000}},
316		{"id":""}]}`
317	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
318		_, _ = w.Write([]byte(body))
319	}))
320	defer srv.Close()
321
322	models, err := DiscoverOpenRouter(context.Background(), srv.URL)
323	if err != nil {
324		t.Fatal(err)
325	}
326	if len(models) != 2 { // empty id dropped
327		t.Fatalf("want 2 models, got %d", len(models))
328	}
329	// per-token USD -> per-1M; reasoning from supported_parameters.
330	if m := models[0]; m.Provider != "openrouter" || m.ContextWindow != 200000 ||
331		m.MaxOutput != 64000 || !m.Reasoning || m.PriceInput != 3 || m.PriceOutput != 15 {
332		t.Errorf("model[0]: %+v", m)
333	}
334	// context falls back to top_provider; no reasoning.
335	if m := models[1]; m.ContextWindow != 128000 || m.MaxOutput != 0 || m.Reasoning {
336		t.Errorf("model[1]: %+v", m)
337	}
338}
339
340// TestOpenAIOmitsZeroMaxTokens guards against sending max_tokens: 0 for
341// discovered models that don't advertise an output cap (MaxOutput == 0).
342func TestOpenAIOmitsZeroMaxTokens(t *testing.T) {
343	SetLiveModels([]Model{
344		{Provider: "openrouter", ID: "vendor/no-cap", DisplayName: "No Cap"},
345		{Provider: "openrouter", ID: "vendor/reason-no-cap", DisplayName: "Reason No Cap", Reasoning: true},
346		{Provider: "openrouter", ID: "vendor/capped", DisplayName: "Capped", MaxOutput: 4096},
347	})
348	defer SetLiveModels(nil)
349
350	c := NewOpenAI("x", "").(*openaiClient)
351
352	got, err := c.buildRequest(Request{Model: "vendor/no-cap"})
353	if err != nil {
354		t.Fatal(err)
355	}
356	if got.MaxTokens != nil {
357		t.Errorf("expected max_tokens omitted, got %d", *got.MaxTokens)
358	}
359
360	got, err = c.buildRequest(Request{Model: "vendor/reason-no-cap"})
361	if err != nil {
362		t.Fatal(err)
363	}
364	if got.MaxCompletionTok != nil {
365		t.Errorf("expected max_completion_tokens omitted, got %d", *got.MaxCompletionTok)
366	}
367
368	got, err = c.buildRequest(Request{Model: "vendor/capped"})
369	if err != nil {
370		t.Fatal(err)
371	}
372	if got.MaxTokens == nil || *got.MaxTokens != 4096 {
373		t.Errorf("expected max_tokens 4096, got %v", got.MaxTokens)
374	}
375}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close