package thintest import ( "encoding/json" "net/url" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/wiretest" ) // usageHello is the runner's hello with Claude's reading two hours old // (its window near its limit) and TensorX at 84% of today's budget. func usageHello(r *toolRig, protocol int, read *time.Time) wire.Hello { reset := time.Now().Add(70 * time.Hour).UTC().Truncate(time.Second) h := primaryAt(toolHello(r.runner.Welcome.Generation), protocol) h.Connections = []wire.HeldConnection{ {LocalID: "claude-a", Person: Owner, Provider: wire.ProviderClaude, Kind: wire.KindSubscription, Label: Owner, Plan: "max", State: wire.ConnHealthy, Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "seven_day", UsedPercent: 85, Minutes: 10080, ResetsAt: &reset}}, CheckedAt: read}}, {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: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1}, Spend: &wire.Spend{Day: 840_000, Month: 6_200_000, Currency: "USD"}}, } return h } // sayHello sends h and waits for both connections to show. func (r *toolRig) sayHello(key string, h wire.Hello) { r.t.Helper() if err := r.runner.Send(r.ctx, key, wire.FrameHello, h); err != nil { r.t.Fatal(err) } deadline := time.Now().Add(10 * time.Second) for { list, err := r.client.Connections(r.ctx) if err == nil && len(list.Items) >= 2 { return } if time.Now().After(deadline) { r.t.Fatalf("connections %+v %v", list, err) } time.Sleep(50 * time.Millisecond) } } // TestContractUsage (connectors spec rev 3.2 S4, §9, §10; Connections // rev 3 §6; the controller's ruling #7): the Usage page shows what is // available with each reading's age and the spend this month; advice // comes as one card at the top of Usage and one quiet card in the // conversation, never Needs you; GET /api/v1/advice lists it; its action // from the page is the ordinary budget call, reaching the runner; a step // held for headroom says how old its reading is; the sidebar has Usage, // with a dot once a connection needs a look. func TestContractUsage(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) read := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second) r.sayHello("h-usage", usageHello(r, wire.ProtocolCurrent, &read)) owner := r.inst.Cookie() page := r.get(owner, "/usage", 200) for _, want := range []string{`id="nav-usage"`, `data-available=`, `data-reading-age>last reported 2 h ago`, `data-spend-line>$0.84 of $1 today · $6.20 of $10 this month`, `data-usage-table`} { if !strings.Contains(page, want) { t.Fatalf("usage page lacks %s", want) } } if strings.Contains(page, "data-usage-dot") || strings.Contains(page, "data-advice=") { t.Fatal("a dot or advice before anything needs it") } // The loop's minute: today's one card. if err := r.inst.Store.Chat().HousekeepingTick(r.ctx); err != nil { t.Fatal(err) } raw, _ := r.fetch(r.client.Token, "/api/v1/advice", 200) var list wire.AdviceList if err := wire.Strict(raw, &list); err != nil || len(list.Items) != 1 { t.Fatalf("advice %s %v", raw, err) } if err := wiretest.SameShape(wiretest.Fixture("api/advice.json"), raw); err != nil { t.Fatal(err) } a := list.Items[0] if a.Kind != wire.AdviceBudgetNear || a.Act != "Raise today’s budget to $2" || a.Dismiss != "Not now" || a.Text != "TensorX: $0.84 of today’s $1 budget used." { t.Fatalf("advice %+v", a) } page = r.get(owner, "/usage", 200) if !strings.Contains(page, `data-advice="`+a.ID+`"`) || strings.Index(page, "data-advice=") > strings.Index(page, `id="usage-now"`) { t.Fatal("the advice is not at the top of Usage") } if conv := r.get(owner, "/conversation", 200); !strings.Contains(conv, `data-advice-choice="act"`) || !strings.Contains(conv, "TensorX: $0.84 of today’s $1 budget used.") { t.Fatal("no quiet advice card in the conversation") } if needs, err := r.client.NeedsYou(r.ctx); err != nil || len(needs.Items) != 0 { t.Fatalf("advice was Needs you: %+v %v", needs, err) } // A stale form acts on nothing; the current one raises today's budget // through the ordinary call. if code, _ := r.post(owner, "/usage/advice/"+a.ID+"/act", url.Values{"revision": {"9"}}); code != 303 || r.frames(wire.FrameBudget) != 0 { t.Fatalf("a stale act: %d, %d budget frames", code, r.frames(wire.FrameBudget)) } if code, at := r.post(owner, "/usage/advice/"+a.ID+"/act", url.Values{"revision": {"1"}}); code != 303 || at != "/usage" { t.Fatalf("act: %d %s", code, at) } _, body := r.expect(wire.FrameBudget) if b := body.(*wire.BudgetCommand); b.Budget.Day != 2_000_000 || b.Budget.Month != 10_000_000 || b.Budget.Revision != 2 { t.Fatalf("budget %+v", b) } if raw, _ = r.fetch(r.client.Token, "/api/v1/advice", 200); !strings.Contains(string(raw), `"items":[]`) { t.Fatalf("advice after acting: %s", raw) } // A step held for headroom on Claude says how old the reading is. id := taskID(t, r.call("u1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Tidy the README", "brief": "b"})) if res := r.call("u2", wire.ToolStartTask, map[string]string{"task": id, "brief": "go"}); res.IsError { t.Fatalf("start: %+v", res) } _, d := r.expect(wire.FrameDispatch) reset := time.Now().Add(70 * time.Hour).UTC().Truncate(time.Second) r.hold("uh", d.(*wire.DispatchCommand), wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-a", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}) if page := r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, "your Claude allowance is 85% used, so Equipo is keeping the rest for urgent work.") || !strings.Contains(page, "It carries on by itself then. · last reported 2 h ago") { t.Fatal("the hold line does not say the reading's age") } // The usage resource, strictly decoded. raw, _ = r.fetch(r.client.Token, "/api/v1/usage?period=week&by=role", 200) var totals wire.UsageTotals if err := wire.Strict(raw, &totals); err != nil || totals.Period != wire.UsageWeek || totals.By != wire.UsageByRole { t.Fatalf("usage %s %v", raw, err) } r.fetch(r.client.Token, "/api/v1/usage?period=year", 422) // Claude limited: Usage has its dot. h := usageHello(r, wire.ProtocolCurrent, &read) h.Connections[0].State = wire.ConnLimited if err := r.runner.Send(r.ctx, "h-limited", wire.FrameHello, h); err != nil { t.Fatal(err) } deadline := time.Now().Add(10 * time.Second) for !strings.Contains(r.get(owner, "/usage", 200), "data-usage-dot") { if time.Now().After(deadline) { t.Fatal("no dot on Usage for a limited connection") } time.Sleep(50 * time.Millisecond) } } // TestContractUsageOlderRunner: a protocol 14 runner says no reading // time; the page shows its readings without an age, and nothing breaks. func TestContractUsageOlderRunner(t *testing.T) { r := newToolRigAt(t, wire.ProtocolScheduler) r.sayHello("h-usage", usageHello(r, wire.ProtocolScheduler, nil)) page := r.get(r.inst.Cookie(), "/usage", 200) if !strings.Contains(page, `data-available=`) || strings.Contains(page, "data-reading-age") { t.Fatal("an older runner's reading showed an age, or nothing showed") } raw, _ := json.Marshal(usageHello(r, wire.ProtocolScheduler, nil)) if strings.Contains(string(raw), "checked_at") { t.Fatal("the older hello carried a reading time") } }