package thintest import ( "context" "net/http" "net/url" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) // canaryKey is an obviously fake TensorX key: sealed in the test, never // seen by the instance. const canaryKey = "tx-CANARY-not-a-real-key-CANARY" // TestContractMeteredConnection (connectors spec S1, §§2.1 to 2.3, §10): // an API-key connection is refused without its confirmations or its // budget and on a runner before protocol 12; with them it goes to the // runner as connect (kind api_key, billing, budget); its key is sealed // to the runner and bound to TensorX's origin; the person picks the // model from the runner's list; the probe's usage is recorded with role // probe and its cost; hello brings the budget and spend; a budget change // is pending until the runner acks its frame; Resume is bound to the // pause it saw. The canary key appears nowhere the instance can read. func TestContractMeteredConnection(t *testing.T) { budget := &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth} good := wire.Connect{Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: budget} // An older runner is refused a metered connection, not downgraded. { old := newRig(t) runner := dialAt(t, old, wire.ProtocolPreviewHost) hello := primaryAt(held(), wire.ProtocolPreviewHost) hello.Generation, hello.SealKey = runner.Welcome.Generation, sealKeys(t).PublicString() if err := runner.Send(old.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } old.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) if _, err := old.client.Connect(old.ctx, good); Status(err) != 409 { t.Fatalf("a protocol 11 runner: %v", err) } ctx, cancel := context.WithTimeout(old.ctx, 300*time.Millisecond) if f, _, _ := runner.Expect(ctx, wire.FrameConnect); f.Type == wire.FrameConnect { t.Fatal("a protocol 11 runner was sent a connect") } cancel() } r := newRig(t) keys := sealKeys(t) runner := dialAt(t, r, wire.ProtocolMetered) hello := primaryAt(held(), wire.ProtocolMetered) 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 }) var runnerID string waitFor(t, "the runner listed", func() bool { list, err := r.client.Runners(r.ctx) if err != nil || len(list.Items) != 1 { return false } runnerID = list.Items[0].ID return true }) for name, bad := range map[string]wire.Connect{ "no limit confirmation": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Budget: budget}, "pay-as-you-go off on a per-token provider": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, PaygOffConfirmed: true, Budget: budget}, "no budget": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true}, "a day over a month": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: &wire.Budget{Day: 5, Month: 4}}, "an unknown provider": {Provider: "elsewhere", Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: budget}, "a confirmation on a subscription": {Provider: "codex", Kind: wire.KindSubscription, LimitConfirmed: true}, } { if _, err := r.client.Connect(r.ctx, bad); Status(err) != 422 { t.Fatalf("%s: %v", name, err) } } // The Add page: TensorX with its required confirmation, what it // means, and the budget pre-filled; posted without the confirmation // it is refused and says so. pages := &toolRig{rig: r} owner := r.inst.Cookie() add := pages.get(owner, "/conversation/settings/connections/add", 200) for _, want := range []string{`data-add-metered="tensorx"`, `name="limit_confirmed" value="1" required`, "This key has a spending limit at TensorX", "I can’t see this limit.", `name="budget_day" inputmode="decimal" value="1"`, `name="budget_month" inputmode="decimal" value="10"`} { if !strings.Contains(add, want) { t.Fatalf("the Add page lacks %s", want) } } if status, loc := pages.post(owner, "/conversation/connections", url.Values{"provider": {"tensorx"}, "kind": {"api_key"}, "budget_day": {"1"}, "budget_month": {"10"}}); status != http.StatusSeeOther || loc != "/conversation/settings/connections/add?refused=confirm" { t.Fatalf("unconfirmed add: %d %q", status, loc) } if page := pages.get(owner, "/conversation/settings/connections/add?refused=confirm", 200); !strings.Contains(page, "Confirm the spending limit and check both budget amounts before continuing.") { t.Fatal("the refusal is not said") } attempt, err := r.client.Connect(r.ctx, good) if err != nil || attempt.State != wire.ConnConnecting || attempt.Kind != wire.KindAPIKey || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptAPIKey || attempt.Billing != wire.BillingMetered || attempt.Harness != wire.HarnessPi || attempt.Upstream != "https://api.tensorx.ai" || attempt.LimitConfirmedAt == nil || attempt.PaygOffConfirmedAt != nil { t.Fatalf("attempt %+v %v", attempt, err) } f, body, err := runner.Expect(r.ctx, wire.FrameConnect) if err != nil { t.Fatal(err) } shape(t, "frames/connect-api-key.json", runner.Received[len(runner.Received)-1]) if cmd := body.(*wire.ConnectCommand); cmd.Connection != attempt.ID || cmd.Kind != wire.KindAPIKey || cmd.Provider != wire.ProviderTensorX || cmd.Billing != wire.BillingMetered || cmd.Budget == nil || cmd.Budget.Day != wire.DefaultBudgetDay || cmd.Budget.Currency != "USD" || cmd.Budget.Revision != 1 { t.Fatalf("connect %+v", cmd) } runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}) if card := pages.get(owner, "/conversation/settings/connections/add", 200); !strings.Contains(card, `data-kind="api_key" data-runner="`+runnerID+`" data-endpoint="https://api.tensorx.ai:443" data-seal-key="`) || !strings.Contains(card, "data-key-form") || !strings.Contains(card, "Paste your TensorX API key") { t.Fatal("the key card is not sealed to the runner for TensorX's origin") } // The key, sealed to the runner and bound to TensorX's origin. endpoint := wire.APIKeyProviders[wire.ProviderTensorX].Endpoint expires := time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second) sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryKey, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: wire.ProviderTensorX, Endpoint: endpoint, Attempt: 1, ExpiresAt: expires}) if err != nil { t.Fatal(err) } for name, change := range map[string]func(*wire.Sealed){ "Claude's endpoint": func(s *wire.Sealed) { s.Endpoint = wire.EndpointAnthropic }, "Claude": func(s *wire.Sealed) { s.Provider = wire.ProviderClaude }, "attempt 2": func(s *wire.Sealed) { s.Attempt = 2 }, } { bad := sealed change(&bad) if _, err := r.client.Secret(r.ctx, attempt.ID, bad); Status(err) != 422 { t.Fatalf("%s: %v", name, err) } } if posted, err := r.client.Secret(r.ctx, attempt.ID, sealed); err != nil || posted.Prompt != nil { t.Fatalf("secret %+v %v", posted, err) } f, body, err = runner.Expect(r.ctx, wire.FrameSecret) if err != nil { t.Fatal(err) } if opened, err := keys.Open(body.(*wire.SecretCommand).Sealed, time.Now()); err != nil || opened.Secret != canaryKey || opened.Endpoint != endpoint { t.Fatalf("the runner could not open the box: %v", err) } runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}) // The runner's model list; the person picks one of them. if _, err := r.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); Status(err) != 409 { t.Fatalf("a model before the list: %v", err) } 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.PromptModel, Models: []string{"moonshotai/kimi-k3.1-pro", "z-ai/glm-5.3"}}}) r.wait("the model card", func(c *Conversation) bool { p := c.Connections[attempt.ID].Prompt return p != nil && p.Kind == wire.PromptModel && len(p.Models) == 2 }) got, _ := r.client.Connection(r.ctx, attempt.ID) shape(t, "api/connection-choose-model.json", got) if card := pages.get(owner, "/conversation/settings/connections/add", 200); !strings.Contains(card, `action="/conversation/connections/`+attempt.ID+`/model"`) || !strings.Contains(card, `value="z-ai/glm-5.3"`) { t.Fatal("the model card does not list the runner's models") } if _, err := r.client.ChooseModel(r.ctx, attempt.ID, "vendor/unlisted"); Status(err) != 422 { t.Fatalf("an unlisted model: %v", err) } if picked, err := r.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); err != nil || picked.Model != "z-ai/glm-5.3" || len(picked.Prompt.Models) != 0 { t.Fatalf("picked %+v %v", picked, err) } f, body, err = runner.Expect(r.ctx, wire.FrameModel) if err != nil { t.Fatal(err) } shape(t, "frames/model.json", runner.Received[len(runner.Received)-1]) if cmd := body.(*wire.ModelCommand); cmd.Connection != attempt.ID || cmd.Model != "z-ai/glm-5.3" || cmd.Person != Owner { t.Fatalf("model %+v", cmd) } runner.Send(r.ctx, "a-model", wire.FrameAck, wire.Ack{ID: f.ID}) // The probe: healthy, its usage charged with role probe. cost, in, out := int64(21), int64(9), int64(1) probe := wire.UsageReport{ProbeID: "pr_" + attempt.ID, Rows: []wire.Usage{{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, OutputTokens: &out, CostMicros: &cost, Currency: "USD", PriceVersion: "tensorx-2026-11-12"}}} for i := 0; i < 2; i++ { // Resent: recorded once. if err := runner.Send(r.ctx, "r-probe", wire.FrameUsage, probe); err != nil { t.Fatal(err) } } 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{Day: 840_000, Month: 6_200_000, Currency: "USD"}} hello.Connections = []wire.HeldConnection{metered} runner.Send(r.ctx, "h3", wire.FrameHello, hello) r.wait("healthy with its spend", func(c *Conversation) bool { v := c.Connections[attempt.ID] return v.State == wire.ConnHealthy && v.Spend != nil && v.Spend.Day == 840_000 && v.Model == "z-ai/glm-5.3" }) // The spend line (spec §2.3). list := pages.get(owner, "/conversation/settings/connections", 200) for _, want := range []string{"$0.84 of $1 today · $6.20 of $10 this month", "Reported by Pi. Spending can exceed the budget by one step.", "z-ai/glm-5.3", `data-budget-form="` + attempt.ID + `"`} { if !strings.Contains(list, want) { t.Fatalf("the row lacks %q", want) } } var rows int var role string var charged int64 if err := r.inst.DB.Writer().QueryRow("SELECT count(*), max(role), max(cost_micros) FROM chat_usage WHERE step_id = ?", "pr_"+attempt.ID).Scan(&rows, &role, &charged); err != nil || rows != 1 || role != wire.UsageProbe || charged != 21 { t.Fatalf("probe usage: %d %s %d %v", rows, role, charged, err) } // A budget change: pending until the runner acks the frame. if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 0}); Status(err) != 409 { t.Fatalf("a stale budget revision: %v", err) } if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 20_000_000, Month: 10_000_000, Revision: 1}); Status(err) != 422 { t.Fatalf("a day over its month: %v", err) } changed, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 1}) if err != nil || !changed.BudgetPending || changed.Budget.Revision != 2 || changed.Budget.Day != 2_000_000 { t.Fatalf("budget %+v %v", changed, err) } shape(t, "api/connection-metered.json", changed) if page := pages.get(owner, "/conversation/settings/connections", 200); !strings.Contains(page, "Applies when Headless runner confirms") { t.Fatal("the pending budget is not said") } f, body, err = runner.Expect(r.ctx, wire.FrameBudget) if err != nil { t.Fatal(err) } shape(t, "frames/budget.json", runner.Received[len(runner.Received)-1]) if cmd := body.(*wire.BudgetCommand); cmd.LocalID != "tensorx-1" || cmd.Budget.Revision != 2 || cmd.Budget.Currency != "USD" { t.Fatalf("budget frame %+v", cmd) } runner.Send(r.ctx, "a-budget", wire.FrameAck, wire.Ack{ID: f.ID}) r.wait("the budget applied", func(c *Conversation) bool { v := c.Connections[attempt.ID] return !v.BudgetPending && v.Budget != nil && v.Budget.Revision == 2 }) // Resume is bound to the pause the person saw. if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); Status(err) != 409 { t.Fatalf("a resume with nothing paused: %v", err) } metered.Spend = &wire.Spend{Day: 840_000, Month: 6_200_000, Currency: "USD", Unknown: true, PauseRevision: 3} metered.Budget = &wire.Budget{Day: 2_000_000, Month: 10_000_000, Currency: "USD", Revision: 2} hello.Connections = []wire.HeldConnection{metered} runner.Send(r.ctx, "h4", wire.FrameHello, hello) r.wait("spend unknown", func(c *Conversation) bool { v := c.Connections[attempt.ID] return v.Spend != nil && v.Spend.Unknown }) if page := pages.get(owner, "/conversation/settings/connections", 200); !strings.Contains(page, "Paused: spend unknown. Check your spending at TensorX, then choose Resume") || !strings.Contains(page, `name="pause_revision" value="3"`) { t.Fatal("spend unknown is not said with its Resume") } if err := r.client.ResumeSpend(r.ctx, attempt.ID, 2); Status(err) != 409 { t.Fatalf("a stale resume: %v", err) } if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); err != nil { t.Fatal(err) } _, body, err = runner.Expect(r.ctx, wire.FrameResumeSpend) if err != nil { t.Fatal(err) } shape(t, "frames/resume_spend.json", runner.Received[len(runner.Received)-1]) if cmd := body.(*wire.ResumeSpendCommand); cmd.PauseRevision != 3 || cmd.LocalID != "tensorx-1" { t.Fatalf("resume frame %+v", cmd) } // Security round finding 8: a teammate's model pick, budget change // or Resume on this connection finds nothing; once the owner is off // the roster, theirs changes nothing either. commands := func() int { var n int r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE person = ?", Owner).Scan(&n) return n } before, rev := commands(), r.conv.Connections[attempt.ID].Revision mate := personToolRig(t, pages, "mate@example.com", equipo.RoleOwner) if _, err := mate.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); Status(err) != 404 { t.Fatalf("a teammate's model pick: %v", err) } if _, err := mate.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 1, Month: 1, Revision: 2}); Status(err) != 404 { t.Fatalf("a teammate's budget: %v", err) } if err := mate.client.ResumeSpend(r.ctx, attempt.ID, 3); Status(err) != 404 { t.Fatalf("a teammate's resume: %v", err) } if _, err := r.inst.DB.Writer().Exec("UPDATE members SET active = 0 WHERE address = ?", Owner); err != nil { t.Fatal(err) } if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 3_000_000, Month: 10_000_000, Revision: 2}); err == nil { t.Fatal("a removed person's budget change went through") } if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); err == nil { t.Fatal("a removed person's resume went through") } var after int64 r.inst.DB.Writer().QueryRow("SELECT revision FROM chat_connections WHERE id = ?", attempt.ID).Scan(&after) if commands() != before || after != rev { t.Fatalf("the owner's commands %d (was %d), revision %d (was %d)", commands(), before, after, rev) } if _, err := r.inst.DB.Writer().Exec("UPDATE members SET active = 1 WHERE address = ?", Owner); err != nil { t.Fatal(err) } // The key is nowhere on the instance. var found int for _, q := range []string{"SELECT count(*) FROM runner_commands WHERE body LIKE ?", "SELECT count(*) FROM chat_connections WHERE coalesce(prompt,'') || coalesce(budget,'') || coalesce(spend,'') LIKE ?", "SELECT count(*) FROM chat_events WHERE body LIKE ?"} { var n int if err := r.inst.DB.Writer().QueryRow(q, "%"+canaryKey+"%").Scan(&n); err != nil && !strings.Contains(err.Error(), "no such") { t.Fatal(err) } found += n } if found != 0 { t.Fatalf("the key is on the instance (%d)", found) } } // dialAt connects a fake runner whose first hello speaks protocol. func dialAt(t *testing.T, r *rig, protocol int) *FakeRunner { t.Helper() f, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, primaryAt(held(), protocol)) if err != nil { t.Fatal(err) } t.Cleanup(f.Close) return f }