package thintest import ( "context" "net/http" "net/url" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // TestContractModels (connectors spec rev 3.3 §16.1, slice S5b): the // models card lists every model the key listed, the ones that can be // allowed ticked and the rest greyed with Price or tier unavailable; the set goes to // the runner as a durable models frame (revision 1 while connecting); // the row says "Models allowed: 1 of 2" and opens the same list; a change is // revision-checked, pending until the runner's ack, and sent again when // a hello shows the runner behind; the Usage page names the tier // table's date beside the price date. func TestContractModels(t *testing.T) { r := newRig(t) keys := sealKeys(t) runner := dialAt(t, r, wire.ProtocolModels) hello := primaryAt(held(), wire.ProtocolModels) hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString() if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) pages := &toolRig{rig: r} owner := r.inst.Cookie() attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth}}) if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameConnect) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}) choices := []wire.ModelChoice{{ID: "moonshotai/kimi-k3", Eligible: true, Family: "kimi", Tier: "strong"}, {ID: "vendor/unpriced"}, {ID: "z-ai/glm-5.3", Eligible: true, Family: "glm", Tier: "strong"}} runner.Send(r.ctx, "r-models", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: wire.ProviderTensorX, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptModels, Choices: choices}}) r.wait("the models card", func(c *Conversation) bool { p := c.Connections[attempt.ID].Prompt return p != nil && p.Kind == wire.PromptModels && len(p.Choices) == 3 }) got, _ := r.client.Connection(r.ctx, attempt.ID) shape(t, "api/connection-choose-models.json", got) card := pages.get(owner, "/conversation/settings/connections/add", 200) for _, want := range []string{`action="/conversation/connections/` + attempt.ID + `/models"`, `name="model" value="z-ai/glm-5.3" checked`, `name="model" value="moonshotai/kimi-k3" checked`, `name="model" value="vendor/unpriced" disabled`, "Price or tier unavailable", `name="revision" value="0"`} { if !strings.Contains(card, want) { t.Fatalf("the models card lacks %s", want) } } if _, err := r.client.SetModels(r.ctx, attempt.ID, wire.SetModels{Allowed: []string{"vendor/unpriced"}, Revision: 0}); Status(err) != 422 { t.Fatalf("an unpriced model allowed: %v", err) } if _, err := r.client.SetModels(r.ctx, attempt.ID, wire.SetModels{Allowed: []string{}, Revision: 0}); Status(err) != 422 { t.Fatalf("no model allowed: %v", err) } // From the page: GLM only. if status, loc := pages.post(owner, "/conversation/connections/"+attempt.ID+"/models", url.Values{"from": {"add"}, "revision": {"0"}, "model": {"z-ai/glm-5.3"}}); status != http.StatusSeeOther || loc != "/conversation/settings/connections/add" { t.Fatalf("the card's post: %d %q", status, loc) } f, body, err := runner.Expect(r.ctx, wire.FrameModels) if err != nil { t.Fatal(err) } if cmd := body.(*wire.ModelsCommand); cmd.Connection != attempt.ID || cmd.LocalID != "" || cmd.Revision != 1 || strings.Join(cmd.Allowed, ",") != "z-ai/glm-5.3" { t.Fatalf("connect set %+v", cmd) } runner.Send(r.ctx, "a-models-1", wire.FrameAck, wire.Ack{ID: f.ID}) runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: wire.ProviderTensorX, LocalID: "tensorx-1", State: wire.ConnHealthy}) metered := wire.HeldConnection{LocalID: "tensorx-1", Person: Owner, Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}, Spend: &wire.Spend{Currency: "USD"}, Models: []wire.ModelState{{ID: "z-ai/glm-5.3", State: wire.ModelHealthy, Family: "glm", Tier: "strong"}}, ModelsRevision: 1, Choices: choices} hello.Connections = []wire.HeldConnection{metered} runner.Send(r.ctx, "h2", wire.FrameHello, hello) r.wait("healthy with its set", func(c *Conversation) bool { v := c.Connections[attempt.ID] return v.State == wire.ConnHealthy && v.ModelsRevision == 1 && !v.ModelsPending && len(v.Models) == 3 }) list := pages.get(owner, "/conversation/settings/connections", 200) for _, want := range []string{"Models allowed: 1 of 2", `data-models="` + attempt.ID + `"`, `name="model" value="z-ai/glm-5.3" checked`, `name="model" value="moonshotai/kimi-k3">`, `name="model" value="vendor/unpriced" disabled`, `name="revision" value="1"`} { if !strings.Contains(list, want) { t.Fatalf("the row lacks %s", want) } } // A change: revision-checked, pending until the ack. if _, err := r.client.SetModels(r.ctx, attempt.ID, wire.SetModels{Allowed: []string{"z-ai/glm-5.3", "moonshotai/kimi-k3"}, Revision: 0}); Status(err) != 409 { t.Fatalf("a stale revision: %v", err) } changed, err := r.client.SetModels(r.ctx, attempt.ID, wire.SetModels{Allowed: []string{"z-ai/glm-5.3", "moonshotai/kimi-k3"}, Revision: 1}) if err != nil || !changed.ModelsPending || changed.ModelsRevision != 2 { t.Fatalf("changed %+v %v", changed, err) } shape(t, "api/connection-models.json", changed) if page := pages.get(owner, "/conversation/settings/connections", 200); !strings.Contains(page, "Applies when Headless runner confirms") || !strings.Contains(page, "Models allowed: 2 of 2") { t.Fatal("the pending set is not said") } f, body, err = runner.Expect(r.ctx, wire.FrameModels) if err != nil { t.Fatal(err) } shape(t, "frames/models.json", runner.Received[len(runner.Received)-1]) if cmd := body.(*wire.ModelsCommand); cmd.LocalID != "tensorx-1" || cmd.Revision != 2 || len(cmd.Allowed) != 2 { t.Fatalf("models frame %+v", cmd) } // The runner went away before applying it: its hello is behind, so // the set is sent again. runner.Send(r.ctx, "h3", wire.FrameHello, hello) f, body, err = runner.Expect(r.ctx, wire.FrameModels) if err != nil || body.(*wire.ModelsCommand).Revision != 2 { t.Fatalf("not sent again: %+v %v", body, err) } runner.Send(r.ctx, "a-models-2", wire.FrameAck, wire.Ack{ID: f.ID}) // The ack is receipt only (security round #4): still pending until // the runner's hello reports the set applied. time.Sleep(200 * time.Millisecond) if v, _ := r.client.Connection(r.ctx, attempt.ID); !v.ModelsPending { t.Fatalf("an ack showed the set applied: %+v", v) } metered.ModelsRevision = 2 metered.Models = []wire.ModelState{{ID: "z-ai/glm-5.3", State: wire.ModelHealthy}, {ID: "moonshotai/kimi-k3", State: wire.ModelUnprobed}} hello.Connections = []wire.HeldConnection{metered} runner.Send(r.ctx, "h3b", wire.FrameHello, hello) r.wait("the set applied", func(c *Conversation) bool { v := c.Connections[attempt.ID] return !v.ModelsPending && v.ModelsRevision == 2 }) // Check again read the key's list anew: a model it lists now is // offered on the row. metered.Choices = append(choices, wire.ModelChoice{ID: "qwen/qwen3.8-27b", Eligible: true, Family: "qwen", Tier: "standard"}) hello.Connections = []wire.HeldConnection{metered} runner.Send(r.ctx, "h4", wire.FrameHello, hello) waitFor(t, "the new listed model", func() bool { return strings.Contains(pages.get(owner, "/conversation/settings/connections", 200), "Models allowed: 2 of 3") }) // The Usage page: the tier table's date beside the price date. n, cost := int64(10), int64(30) runner.Send(r.ctx, "r-usage", wire.FrameUsage, wire.UsageReport{ProbeID: "probe:st_1:1:moonshotai/kimi-k3", Rows: []wire.Usage{{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "moonshotai/kimi-k3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &n, OutputTokens: &n, CostMicros: &cost, Currency: "USD", PriceVersion: "tensorx-2026-11-12", Family: "kimi", Tier: "strong", TierVersion: "tiers-2026-11-12"}}}) deadline := time.Now().Add(10 * time.Second) for { page := pages.get(owner, "/usage", 200) if strings.Contains(page, "TensorX prices taken from the public page on 12 Nov 2026. Model tiers reflect Equipo’s judgement as of 12 Nov 2026.") { break } if time.Now().After(deadline) { t.Fatal("the Usage page does not name the tier table") } time.Sleep(50 * time.Millisecond) } var tier, version string if err := r.inst.DB.Writer().QueryRow("SELECT tier, tier_version FROM chat_usage WHERE step_id = ?", "probe:st_1:1:moonshotai/kimi-k3").Scan(&tier, &version); err != nil || tier != "strong" || version != "tiers-2026-11-12" { t.Fatalf("usage row %q %q %v", tier, version, err) } if page := pages.get(owner, "/usage?period=month&by=model", 200); !strings.Contains(page, "moonshotai/kimi-k3") { t.Fatal("no row by model") } } // §16.1: a runner below ProtocolModels keeps its connections' one model, // exactly as before; the page says it needs an update to allow more // models, and a change is refused (409 runner_too_old) and never sent. func TestContractModelsOlderRunner(t *testing.T) { r := newRig(t) runner := dialAt(t, r, wire.ProtocolOpenCode) hello := primaryAt(held(wire.HeldConnection{LocalID: "tensorx-1", Person: Owner, Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}, Spend: &wire.Spend{Currency: "USD"}}), wire.ProtocolOpenCode) hello.Generation = runner.Welcome.Generation if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } var id string waitFor(t, "the metered connection", func() bool { list, err := r.client.Connections(r.ctx) for _, c := range list.Items { if c.Kind == wire.KindAPIKey { id = c.ID } } return err == nil && id != "" }) // The S1 connection, migrated: its set is its one model. if _, err := r.inst.DB.Writer().Exec("UPDATE chat_connections SET models = json_array(model), models_revision = 1, models_applied = 1 WHERE id = ?", id); err != nil { t.Fatal(err) } pages := &toolRig{rig: r} page := pages.get(r.inst.Cookie(), "/conversation/settings/connections", 200) if !strings.Contains(page, "Your runner needs an update before you can change the allowed models.") || !strings.Contains(page, "z-ai/glm-5.3") || strings.Contains(page, "data-models-change") { i := strings.Index(page, "data-spend") t.Fatalf("the older runner's row is not as before with its note: %s", page[max(0, i-200):min(len(page), i+800)]) } if _, err := r.client.SetModels(r.ctx, id, wire.SetModels{Allowed: []string{"z-ai/glm-5.3"}, Revision: 1}); Status(err) != 409 { t.Fatalf("a protocol 17 runner: %v", err) } ctx, cancel := context.WithTimeout(r.ctx, 300*time.Millisecond) defer cancel() if f, _, _ := runner.Expect(ctx, wire.FrameModels); f.Type == wire.FrameModels { t.Fatal("a protocol 17 runner was sent a models frame") } } // §16.5: Review's dispatch names the family Engineering's attempt // recorded, read from that step, never from the connection; an older // runner is sent none (Encode drops it below 18). func TestContractReviewNamesEngineeringFamily(t *testing.T) { for _, c := range []struct { protocol int want string }{{wire.ProtocolModels, "claude"}, {wire.ProtocolOpenCode, ""}} { r := newToolRigAt(t, c.protocol) base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) r.pushed("a", "Fix the README typo", base, cand) r.expect(wire.FrameWatchMerge) c1 := r.dispatched(wire.SpecialistChecks, base, cand, 0) r.checks("a-c1", c1, wire.ChecksPassed, exit(0), "", "ok\n") rv := r.dispatched(wire.SpecialistReview, base, cand, 0) if rv.AvoidAccount != "claude-a" || rv.AvoidFamily != c.want { t.Fatalf("protocol %d: review dispatch %+v", c.protocol, rv) } } }