| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "slices" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/go-chi/chi/v5" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // The Usage page (Connections rev 3 §6, connectors spec rev 3.2 S4): |
| 21 | // advice at the top, then what is available now (each connection's state |
| 22 | // and the headroom its provider reported, with the reading's age), spend |
| 23 | // this month (metered connections against their budgets, with where the |
| 24 | // prices come from, and subscriptions as their plan and tokens), and |
| 25 | // token use in tabs (today, this week, this month; by connection, role, |
| 26 | // project or task). |
| 27 | |
| 28 | type usageView struct { |
| 29 | Advice *wire.Advice |
| 30 | // AdviceTag is the connection the advice names, for its mark. |
| 31 | AdviceTag *chat.ConnLabel |
| 32 | Available []usageConn |
| 33 | NoConnections bool |
| 34 | Spend []usageSpend |
| 35 | Plans []usagePlan |
| 36 | Periods, By []usageTab |
| 37 | Column string |
| 38 | Rows []usageRowView |
| 39 | LeftOut bool |
| 40 | } |
| 41 | |
| 42 | // usageConn is one connection's availability: its state in words, the |
| 43 | // meters its provider reported, and how old that reading is. |
| 44 | type usageConn struct { |
| 45 | // Tag is the connection's shared label; Name its Text. |
| 46 | Tag chat.ConnLabel |
| 47 | ID, Provider, Name, Glyph, State, Words string |
| 48 | Meters []connMeter |
| 49 | Age, Note, Spend string |
| 50 | } |
| 51 | |
| 52 | // usageSpend is a metered connection's spend line, its tail, its pause |
| 53 | // and the price table's source. |
| 54 | type usageSpend struct { |
| 55 | Tag chat.ConnLabel |
| 56 | ID, Name, Line, Tail, Paused, Source string |
| 57 | // UnderCount says the connection's harness can under-count a turn's |
| 58 | // spend (wire.Harnesses), beside where its prices come from. |
| 59 | UnderCount string |
| 60 | } |
| 61 | |
| 62 | // usagePlan is a subscription: its plan and its tokens this month, never |
| 63 | // a money figure. |
| 64 | type usagePlan struct { |
| 65 | Tag chat.ConnLabel |
| 66 | ID, Name, Plan, Tokens string |
| 67 | } |
| 68 | |
| 69 | type usageTab struct { |
| 70 | Key, Label, Href string |
| 71 | On bool |
| 72 | } |
| 73 | |
| 74 | type usageRowView struct { |
| 75 | // Tag is a connection row's shared label. |
| 76 | Tag *chat.ConnLabel |
| 77 | ID, Label, Input, Cached, Output, Estimate string |
| 78 | } |
| 79 | |
| 80 | // readingAge uses the reading's source and time, never the row update time. |
| 81 | func readingAge(c wire.Connection, now time.Time) string { |
| 82 | if c.Headroom == nil || c.Headroom.CheckedAt == nil { |
| 83 | return "" |
| 84 | } |
| 85 | key := "usage.reading.as_of" |
| 86 | if c.Provider == wire.ProviderClaude && !c.Headroom.Fetched { |
| 87 | key = "usage.reading.last_reported" |
| 88 | } |
| 89 | return fmt.Sprintf(copyText(key), ago(now, *c.Headroom.CheckedAt)) |
| 90 | } |
| 91 | |
| 92 | // priceSource says where a price table's prices come from: the provider |
| 93 | // and the day its public page was read, from the table's version |
| 94 | // (tensorx-2026-11-12), never a sentence per provider. |
| 95 | func priceSource(provider, version string) string { |
| 96 | if len(version) < 11 { |
| 97 | return "" |
| 98 | } |
| 99 | day, err := time.Parse("2006-01-02", version[len(version)-10:]) |
| 100 | if err != nil || version[len(version)-11] != '-' { |
| 101 | return "" |
| 102 | } |
| 103 | return fmt.Sprintf(copyText("usage.price_source"), providerName(provider), day.Format("2 Jan 2006")) |
| 104 | } |
| 105 | |
| 106 | // tierSource says the tiers that chose a metered connection's models |
| 107 | // are Equipo's own judgement, and when it was made, from the tier |
| 108 | // table's version (tiers-2026-11-12, §16.2). |
| 109 | func tierSource(version string) string { |
| 110 | day, err := time.Parse("2006-01-02", strings.TrimPrefix(version, "tiers-")) |
| 111 | if err != nil || !strings.HasPrefix(version, "tiers-") { |
| 112 | return "" |
| 113 | } |
| 114 | return fmt.Sprintf(copyText("usage.tier_source"), day.Format("2 Jan 2006")) |
| 115 | } |
| 116 | |
| 117 | // joinSources is the source line's sentences, the empty ones left out. |
| 118 | func joinSources(parts ...string) string { |
| 119 | return strings.Join(slices.DeleteFunc(parts, func(s string) bool { return s == "" }), " ") |
| 120 | } |
| 121 | |
| 122 | // usageLabel is a grouping's row label: a connection by its shared |
| 123 | // label, a role by name, a project or task by its own name, and rows |
| 124 | // with no task as the conversation. |
| 125 | func usageLabel(by string, row wire.UsageRow, labels map[string]chat.ConnLabel) string { |
| 126 | switch by { |
| 127 | case wire.UsageByConnection: |
| 128 | if l, ok := labels[row.ID]; ok { |
| 129 | return l.Text |
| 130 | } |
| 131 | return providerName(row.Label) |
| 132 | case wire.UsageByModel: |
| 133 | if row.ID == "" { |
| 134 | return copyText("usage.no_model") |
| 135 | } |
| 136 | return row.ID |
| 137 | case wire.UsageByRole: |
| 138 | switch row.ID { |
| 139 | case "coordinator", "": |
| 140 | return copyText("conversation.coordinator") |
| 141 | case "ask": |
| 142 | return copyText("work.spend_questions") |
| 143 | case "probe": |
| 144 | return copyText("usage.role.probe") |
| 145 | } |
| 146 | if name := copyText("work.specialist." + row.ID); name != "" { |
| 147 | return name |
| 148 | } |
| 149 | if name := makerName(row.ID); name != "" { |
| 150 | return name |
| 151 | } |
| 152 | return row.ID |
| 153 | } |
| 154 | if row.ID == "" { |
| 155 | return copyText("usage.no_task") |
| 156 | } |
| 157 | return row.Label |
| 158 | } |
| 159 | |
| 160 | // tokensWithFloor is a token figure, "at least" when a row lacked one. |
| 161 | func tokensWithFloor(n int64, partial bool) string { |
| 162 | if partial { |
| 163 | return fmt.Sprintf(copyText("usage.at_least"), tokenCount(n)) |
| 164 | } |
| 165 | return tokenCount(n) |
| 166 | } |
| 167 | |
| 168 | func usageHref(period, by string) string { |
| 169 | return "/usage?" + url.Values{"period": {period}, "by": {by}}.Encode() |
| 170 | } |
| 171 | |
| 172 | // usagePage builds the page from the person's connections and their |
| 173 | // shared labels, the period's totals, this month's totals by connection |
| 174 | // and the advice to show. |
| 175 | func usagePage(conns []wire.Connection, labels map[string]chat.ConnLabel, totals, month wire.UsageTotals, advice *wire.Advice, now time.Time) usageView { |
| 176 | v := usageView{Advice: advice, LeftOut: totals.LeftOut} |
| 177 | if advice != nil { |
| 178 | if l, ok := labels[advice.Subject.Connection]; ok { |
| 179 | v.AdviceTag = &l |
| 180 | } |
| 181 | } |
| 182 | prices, tiers := map[string]string{}, map[string]string{} |
| 183 | for _, p := range month.Prices { |
| 184 | prices[p.Connection], tiers[p.Connection] = p.PriceVersion, p.TierVersion |
| 185 | } |
| 186 | monthly := map[string]wire.UsageRow{} |
| 187 | for _, r := range month.Rows { |
| 188 | monthly[r.ID] = r |
| 189 | } |
| 190 | for _, c := range conns { |
| 191 | if c.State == wire.ConnConnecting || c.LocalID == "" { |
| 192 | continue |
| 193 | } |
| 194 | c = freshen(c, now) |
| 195 | tag := chat.LabelOf(labels, c) |
| 196 | u := usageConn{Tag: tag, ID: c.ID, Provider: c.Provider, Name: tag.Text, Glyph: providerGlyph(c.Provider), State: c.State} |
| 197 | metered := false |
| 198 | if c.Headroom != nil && c.State != wire.ConnSignedOut && c.State != wire.ConnSignInAgain { |
| 199 | for _, w := range c.Headroom.Windows { |
| 200 | m := meterOf(w, now) |
| 201 | metered = metered || m.Resets != "" |
| 202 | u.Meters = append(u.Meters, m) |
| 203 | } |
| 204 | } |
| 205 | u.Words = connectionState(c, now, metered) |
| 206 | if c.State == wire.ConnError { |
| 207 | u.State, u.Words = wire.ConnSignInAgain, copyText("chat.connections.sign_in_again") |
| 208 | } |
| 209 | switch { |
| 210 | case c.Kind == wire.KindAPIKey: |
| 211 | // A metered connection's availability is its budget. |
| 212 | var row connRow |
| 213 | meteredFacts(&row, c, "", now) |
| 214 | u.Spend = row.Spend |
| 215 | if row.Paused != "" { |
| 216 | u.Words = row.Paused |
| 217 | } |
| 218 | if row.Unknown != "" { |
| 219 | u.Words = row.Unknown |
| 220 | } |
| 221 | s := usageSpend{Tag: tag, ID: c.ID, Name: tag.Text, Line: row.Spend, Tail: row.SpendTail, Paused: row.Paused + row.Unknown, Source: joinSources(priceSource(c.Provider, prices[c.ID]), tierSource(tiers[c.ID]))} |
| 222 | if wire.Harnesses[c.Harness].PartialUsageUnderCounts { |
| 223 | s.UnderCount = copyText("usage.spend_undercount") |
| 224 | } |
| 225 | v.Spend = append(v.Spend, s) |
| 226 | case u.State != wire.ConnSignedOut: |
| 227 | if len(u.Meters) > 0 { |
| 228 | u.Age = readingAge(c, now) |
| 229 | } else if u.State == wire.ConnHealthy { |
| 230 | u.Note = copyText("usage.reading.none") |
| 231 | } |
| 232 | p := usagePlan{Tag: tag, ID: c.ID, Name: tag.Text, Tokens: fmt.Sprintf(copyText("usage.plan_tokens"), tokenCount(monthly[c.ID].Input+monthly[c.ID].Output))} |
| 233 | p.Plan = planLabel(c.Plan) |
| 234 | if c.Headroom != nil && c.Headroom.Unavailable { |
| 235 | u.Note = copyText("usage.reading.unavailable") |
| 236 | } |
| 237 | v.Plans = append(v.Plans, p) |
| 238 | } |
| 239 | v.Available = append(v.Available, u) |
| 240 | } |
| 241 | v.NoConnections = len(v.Available) == 0 |
| 242 | for _, p := range wire.UsagePeriods { |
| 243 | v.Periods = append(v.Periods, usageTab{Key: p, Label: copyText("usage.period." + p), Href: usageHref(p, totals.By), On: p == totals.Period}) |
| 244 | } |
| 245 | for _, b := range wire.UsageGroupings { |
| 246 | v.By = append(v.By, usageTab{Key: b, Label: copyText("usage.by." + b), Href: usageHref(totals.Period, b), On: b == totals.By}) |
| 247 | if b == totals.By { |
| 248 | v.Column = copyText("usage.by." + b) |
| 249 | } |
| 250 | } |
| 251 | for _, r := range totals.Rows { |
| 252 | row := usageRowView{ID: r.ID, Label: usageLabel(totals.By, r, labels), Input: tokensWithFloor(r.Input, r.Partial), Cached: tokenCount(r.CachedInput), Output: tokensWithFloor(r.Output, r.Partial)} |
| 253 | if l, ok := labels[r.ID]; ok && totals.By == wire.UsageByConnection { |
| 254 | row.Tag = &l |
| 255 | } |
| 256 | if r.Cost != nil { |
| 257 | row.Estimate = chat.Money(*r.Cost, r.Currency) |
| 258 | } |
| 259 | v.Rows = append(v.Rows, row) |
| 260 | } |
| 261 | return v |
| 262 | } |
| 263 | |
| 264 | // usageAttention is the sidebar's dot: a connection limited or needing a |
| 265 | // sign-in, or a metered one paused by its budget or its unknown spend. |
| 266 | func usageAttention(conns []wire.Connection) bool { |
| 267 | for _, c := range conns { |
| 268 | if c.State == wire.ConnLimited || c.State == wire.ConnSignInAgain { |
| 269 | return true |
| 270 | } |
| 271 | if c.Kind == wire.KindAPIKey && c.Spend != nil && c.Budget != nil && (c.Spend.Unknown || c.Spend.Day >= c.Budget.Day || c.Spend.Month >= c.Budget.Month) { |
| 272 | return true |
| 273 | } |
| 274 | } |
| 275 | return false |
| 276 | } |
| 277 | |
| 278 | // usage is GET /usage. |
| 279 | func (a *application) usage(w http.ResponseWriter, r *http.Request) { |
| 280 | w.Header().Set("Cache-Control", "no-store") |
| 281 | ctx, address, ok := sessionContext(r) |
| 282 | if !ok { |
| 283 | a.failure(w, r, ErrForbidden) |
| 284 | return |
| 285 | } |
| 286 | period, by := r.URL.Query().Get("period"), r.URL.Query().Get("by") |
| 287 | if !slices.Contains(wire.UsagePeriods, period) { |
| 288 | period = wire.UsageMonth |
| 289 | } |
| 290 | if !slices.Contains(wire.UsageGroupings, by) { |
| 291 | by = wire.UsageByConnection |
| 292 | } |
| 293 | c := a.store.Chat() |
| 294 | conns, labels, err := c.LabelledConnections(ctx, address) |
| 295 | if err == nil { |
| 296 | var totals, month wire.UsageTotals |
| 297 | if totals, err = c.UsageTotals(ctx, address, period, by); err == nil { |
| 298 | if month, err = c.UsageTotals(ctx, address, wire.UsageMonth, wire.UsageByConnection); err == nil { |
| 299 | var list wire.AdviceList |
| 300 | if list, err = c.Advice(ctx, address); err == nil { |
| 301 | data, perr := a.page(r, "usage") |
| 302 | if perr != nil { |
| 303 | a.failure(w, r, perr) |
| 304 | return |
| 305 | } |
| 306 | var advice *wire.Advice |
| 307 | if len(list.Items) > 0 { |
| 308 | advice = &list.Items[0] |
| 309 | } |
| 310 | data.Title = "usage.title" |
| 311 | data.Usage = usagePage(conns, labels, totals, month, advice, c.Now().In(c.Zone(address))) |
| 312 | render(w, "usage", data) |
| 313 | return |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | a.failure(w, r, chatError(err)) |
| 319 | } |
| 320 | |
| 321 | // usageAdvice is an advice card's action or Not now from the page; a |
| 322 | // card that moved or was answered elsewhere shows the page as it is. |
| 323 | func (a *application) usageAdvice(act bool) http.HandlerFunc { |
| 324 | return func(w http.ResponseWriter, r *http.Request) { |
| 325 | a.chatActionTo(w, r, "/usage", func(ctx context.Context, address string) error { |
| 326 | revision, err := strconv.ParseInt(r.FormValue("revision"), 10, 64) |
| 327 | if err != nil { |
| 328 | return chat.ErrCardConflict |
| 329 | } |
| 330 | do := a.store.Chat().DismissAdvice |
| 331 | if act { |
| 332 | do = a.store.Chat().ActAdvice |
| 333 | } |
| 334 | _, err = do(ctx, address, chi.URLParam(r, "id"), wire.AdviceAction{Revision: revision}) |
| 335 | if errors.Is(err, chat.ErrConflict) || errors.Is(err, chat.ErrNotFound) { |
| 336 | return chat.ErrCardConflict |
| 337 | } |
| 338 | return err |
| 339 | }) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | // planLabel is shared by Connections and Usage. |
| 344 | func planLabel(plan string) string { |
| 345 | if plan == "" { |
| 346 | return "" |
| 347 | } |
| 348 | return fmt.Sprintf(copyText("usage.plan"), strings.ToUpper(plan[:1])+plan[1:]) |
| 349 | } |
| 350 | |