oficina / equipo Public

Usage page, advice card and reading ages; copy for review

/usage: advice at the top, availability with each reading's age, spend
this month with where prices come from (read from the price table's
version), subscriptions as plan and tokens, token use in tabs by
connection, role, project and task. Usage in the sidebar with a dot; the
advice card in the conversation; a hold for headroom says its reading's
age. 51 new strings marked COPY REVIEW REQUIRED (S4 usage) with
inventory rows. Contract and browser tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 71774cfa05b5169b5ddf5a5a1f703c41bb883ca7 parent 5a64ad0
19 files changed, +914 −15
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +51 −0
  • internal/equipo/app.go +3 −0
  • internal/equipo/chat_days.go +1 −1
  • internal/equipo/chat_page.go +15 −0
  • internal/equipo/connections_metered.go +3 −12
  • internal/equipo/copy.go +51 −0
  • internal/equipo/handlers.go +2 −0
  • internal/equipo/icons/icons.go +1 −0
  • internal/equipo/rail.go +7 −0
  • internal/equipo/render.go +1 −1
  • internal/equipo/static/equipo.css +25 −0
  • internal/equipo/templates/chat.html +1 −0
  • internal/equipo/templates/chrome.html +1 −1
  • internal/equipo/templates/usage.html +16 −0
  • internal/equipo/usage_page.go +302 −0
  • internal/equipo/usage_page_test.go +164 −0
  • internal/equipo/work_pages.go +29 −0
  • internal/headless/browser_usage_test.go +81 −0
  • internal/thintest/usage_contract_test.go +160 −0
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index bc3edfee..0a0f2afc 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6157,6 +6157,57 @@ records remain unchanged.
| `chat.held.budget` | %s has reached its budget. Raise it, or wait for the budget to reset. | Scheduler S3: the card for a step held on a budget (Wait only; Raise the budget is on Connections); %s provider | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| `chat.card.wait_reset` | Wait | Scheduler S3: the held card's Wait button | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| `chat.card.run_now` | Run it now | Scheduler S3: the held card's Run it now button | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
+| `nav.usage` | Usage | Usage S4: the sidebar entry beside Needs you (Connections rev 3 §6) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `nav.usage_attention` | Something on Usage needs a look | Usage S4: the sidebar dot's label (screen readers): a connection limited or needing a sign-in, or a metered one paused | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.title` | Usage | Usage S4: the page title | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.lede` | What can run now, what it costs, and where the tokens went. | Usage S4: the page's lede under the title | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.advice` | Advice | Usage S4: the advice card's label at the top of the page (screen readers) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.now` | Available now | Usage S4: heading of the availability part | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.reading.as_of` | as of %s | Usage S4, ruling #7: a Codex reading's age after its meters and on a held step's line; %s is how long ago (2 h ago); Codex refreshes without a model turn | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.reading.last_reported` | as last reported %s | Usage S4, ruling #7: a Claude reading's age; %s is how long ago; Claude reports headroom only on a turn | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.reading.none` | Headroom not reported | Usage S4: a ready subscription whose provider reported no headroom | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.no_connections` | Nothing is connected yet. | Usage S4: availability with nothing connected; followed by the Add a connection link | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.connect` | Add a connection | Usage S4: link to Add a connection when nothing is connected | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.spend` | Spend this month | Usage S4: heading of the spend part (metered connections and subscriptions' plans) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.price_source` | %s prices taken from the public page on %s. | Usage S4, controller's price note: where prices come from, read from the price table's version; %s the provider (TensorX), %s the day its public page was read (12 Nov 2026) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.plan_tokens` | %s tokens this month | Usage S4: a subscription's tokens this month (never a money figure); %s is a token count (1.2M) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.plan` | %s plan | Usage S4: a subscription's plan as its provider names it; %s is the plan (Pro) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.spend_none` | Nothing here spends money: every connection is a subscription. | Usage S4: the spend part when no connection is metered | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.tokens` | Token use | Usage S4: heading of the token use part, and its tabs' label | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.period.day` | Today | Usage S4: token use tab, today in the person's zone | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.period.week` | This week | Usage S4: token use tab, since Monday | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.period.month` | This month | Usage S4: token use tab, since the 1st | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.by.connection` | Connection | Usage S4: token use grouping tab and first column heading | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.by.role` | Role | Usage S4: token use grouping tab and first column heading | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.by.project` | Project | Usage S4: token use grouping tab and first column heading | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.by.task` | Task | Usage S4: token use grouping tab and first column heading | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.col.input` | Input | Usage S4: token table column, every input token read | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.col.cached` | Cached input | Usage S4: token table column, input read from cache | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.col.output` | Output | Usage S4: token table column | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.col.estimate` | Estimate | Usage S4: token table column, the cost a price table gave (metered rows only) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.tokens_empty` | No tokens recorded for this period. | Usage S4: the token table with no rows for the period | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.no_task` | The conversation | Usage S4: the project or task row for usage with no task (coordinator turns) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.role.probe` | Connection checks | Usage S4: the role row for a metered key's one-token checks | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `usage.at_least` | at least %s | Usage S4: a token figure when a row lacked one; %s is the figure | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `work.hold.reading` | %s · %s | Usage S4, ruling #7: a held step's line with its reading's age; the first %s is the hold line, the second usage.reading.as_of or usage.reading.last_reported | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.not_now` | Not now | Advice S4 (spec 9): the second button on a prefer_switch, defer_tasks or held_long card; silences the advice 14 days, then 60 | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.leave_it` | Leave it | Advice S4: the second button on a budget_near card | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.budget_near.day` | %s: %s of today’s %s. | Advice S4, budget_near: %s the provider (TensorX), %s spend today ($0.84), %s today's budget ($1) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.budget_near.month` | %s: %s of this month’s %s. | Advice S4, budget_near: %s the provider, %s spend this month, %s this month's budget | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.budget_near.raise_day` | Raise today’s budget to %s | Advice S4, budget_near's action: doubles today's budget; %s the new figure ($2) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.budget_near.raise_month` | Raise this month’s budget to %s | Advice S4, budget_near's action: doubles this month's budget; %s the new figure | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.prefer_switch` | %s is near its limit until %s. %s has room. Prefer %s until then? | Advice S4, prefer_switch: %s the preferred provider (Claude), %s the day its window resets (Thu 19 Nov), %s and %s the other provider (Codex); the preference is one for every role | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.prefer_switch.act` | Prefer %s until %s | Advice S4, prefer_switch's action: prefers the other provider until the reset; %s the provider, %s the day | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.defer_tasks.one` | One task could wait until %s so the urgent work goes first. Let it wait? | Advice S4, defer_tasks with one normal task: %s the day the urgent work's reset comes (Thu 19 Nov) | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.defer_tasks.many` | %d tasks could wait until %s so the urgent work goes first. Let them wait? | Advice S4, defer_tasks: %d how many normal tasks, %s the day of the reset | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.defer_tasks.one_no_reset` | One task could wait so the urgent work goes first. Let it wait? | Advice S4, defer_tasks with one task, no reset reported | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.defer_tasks.many_no_reset` | %d tasks could wait so the urgent work goes first. Let them wait? | Advice S4, defer_tasks, no reset reported; %d how many | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.defer_tasks.act_one` | Make it low priority | Advice S4, defer_tasks' action for one task | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.defer_tasks.act_many` | Make them low priority | Advice S4, defer_tasks' action | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.held_long.one` | A low-priority task has waited a week. | Advice S4, held_long with one low task held a week | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.held_long.many` | %d low-priority tasks have waited a week. | Advice S4, held_long: %d how many low tasks | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.held_long.act_one` | Make it normal | Advice S4, held_long's action for one task | Runtime; COPY REVIEW REQUIRED (S4 usage) |
+| `advice.held_long.act_many` | Make them normal | Advice S4, held_long's action | Runtime; COPY REVIEW REQUIRED (S4 usage) |
| `work.row.step` | Step %d of %d | Tasks rows redesign (2026-11-12): the stepper's label for screen readers | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| `work.done_more` | Show %d more | Tasks rows redesign (2026-11-12): Done's fold | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| `chat.card.research_for` | For %s | Research task page (R5, 2026-11-12): the sources card; %s is the task's title | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index be3a3abc..e7ed82a6 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -273,6 +273,9 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/conversation/projects/{id}/remove", a.chatProjectRemove)
r.Get("/conversation/notebook", movedTo("/conversation/settings/notebook"))
r.Get("/conversation/settings/notebook", a.chatNotebook)
+ r.Get("/usage", a.usage)
+ r.Post("/usage/advice/{id}/act", a.usageAdvice(true))
+ r.Post("/usage/advice/{id}/dismiss", a.usageAdvice(false))
r.Get("/housekeeping", a.housekeepingPage)
r.Post("/settings/housekeeping/pause", a.housekeepingPause)
r.Post("/settings/housekeeping/quiet", a.housekeepingQuiet)
diff --git a/internal/equipo/chat_days.go b/internal/equipo/chat_days.go
index bf5851e8..5f9c0053 100644
--- a/internal/equipo/chat_days.go
+++ b/internal/equipo/chat_days.go
@@ -357,7 +357,7 @@ func feedLines(msgs []wire.Message, cards []wire.Card, choices []string, tasks m
var loose []chatLine
for _, c := range cards {
v := cardView(c, choices, tasks)
- if c.Kind == wire.CardTask && v.Task == nil {
+ if c.Kind == wire.CardTask && v.Task == nil || c.Kind == wire.CardAdvice && c.State == wire.CardResolved {
continue
}
v.Receipt = receiptKind(c)
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index afe0b6a9..5d70e82d 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -71,6 +71,8 @@ type chatCard struct {
GrantHow string
Open, Remove, Receipt bool
Choices []string
+ // ActLabel and DismissLabel are an advice card's two buttons.
+ ActLabel, DismissLabel string
// Task is a task card's task.
Task *taskLine
}
@@ -183,6 +185,19 @@ func cardView(c wire.Card, choices []string, tasks map[string]wire.Task) chatCar
if c.State == wire.CardAnswered {
v.Line = copyText("chat.card.combined_undone")
}
+ case wire.CardAdvice:
+ // Advice (connectors spec §9): one quiet card, its action and Not
+ // now; once answered, what was chosen; withdrawn, nothing.
+ v.Line, v.Open = c.Question, c.State == wire.CardOpen
+ if c.Advice != nil {
+ v.ActLabel, v.DismissLabel = c.Advice.Act, c.Advice.Dismiss
+ if c.State == wire.CardAnswered {
+ v.Note = c.Advice.Act
+ if c.Choice == wire.ChoiceDismiss {
+ v.Note = c.Advice.Dismiss
+ }
+ }
+ }
case wire.CardHousekeeping:
// The day's digest line: quiet, with the way to the Housekeeping view.
v.Line = c.Question
diff --git a/internal/equipo/connections_metered.go b/internal/equipo/connections_metered.go
index 0fb54cb1..211e978b 100644
--- a/internal/equipo/connections_metered.go
+++ b/internal/equipo/connections_metered.go
@@ -48,18 +48,9 @@ func meteredAdds(refused string) []meteredAdd {
// §2.1's sources).
var providerDocs = map[string]string{wire.ProviderTensorX: "https://docs.tensorx.ai/billing"}
-// money is an amount of micro-units in words: $1, $0.84, $6.20.
-func money(micros int64, currency string) string {
- whole := micros%1_000_000 == 0
- amount := strconv.FormatInt(micros/1_000_000, 10)
- if !whole {
- amount = strconv.FormatFloat(float64(micros)/1e6, 'f', 2, 64)
- }
- if currency == "USD" || currency == "" {
- return "$" + amount
- }
- return amount + " " + currency
-}
+// money is an amount of micro-units in words: $1, $0.84, $6.20 (advice
+// says amounts the same way).
+func money(micros int64, currency string) string { return chat.Money(micros, currency) }
// moneyField is an amount as a form field's value: 1, 0.5, 10.25.
func moneyField(micros int64) string {
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index ec0c4173..9048bde3 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -986,6 +986,57 @@ var pageCopy = map[string]string{
"chat.held.budget": "%s has reached its budget. Raise it, or wait for the budget to reset.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"chat.card.wait_reset": "Wait", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"chat.card.run_now": "Run it now", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
+ "nav.usage": "Usage", // COPY REVIEW REQUIRED (S4 usage)
+ "nav.usage_attention": "Something on Usage needs a look", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.title": "Usage", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.lede": "What can run now, what it costs, and where the tokens went.", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.advice": "Advice", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.now": "Available now", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.reading.as_of": "as of %s", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.reading.last_reported": "as last reported %s", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.reading.none": "Headroom not reported", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.no_connections": "Nothing is connected yet.", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.connect": "Add a connection", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.spend": "Spend this month", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.price_source": "%s prices taken from the public page on %s.", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.plan_tokens": "%s tokens this month", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.plan": "%s plan", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.spend_none": "Nothing here spends money: every connection is a subscription.", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.tokens": "Token use", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.period.day": "Today", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.period.week": "This week", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.period.month": "This month", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.by.connection": "Connection", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.by.role": "Role", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.by.project": "Project", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.by.task": "Task", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.col.input": "Input", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.col.cached": "Cached input", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.col.output": "Output", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.col.estimate": "Estimate", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.tokens_empty": "No tokens recorded for this period.", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.no_task": "The conversation", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.role.probe": "Connection checks", // COPY REVIEW REQUIRED (S4 usage)
+ "usage.at_least": "at least %s", // COPY REVIEW REQUIRED (S4 usage)
+ "work.hold.reading": "%s · %s", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.not_now": "Not now", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.leave_it": "Leave it", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.budget_near.day": "%s: %s of today’s %s.", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.budget_near.month": "%s: %s of this month’s %s.", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.budget_near.raise_day": "Raise today’s budget to %s", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.budget_near.raise_month": "Raise this month’s budget to %s", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.prefer_switch": "%s is near its limit until %s. %s has room. Prefer %s until then?", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.prefer_switch.act": "Prefer %s until %s", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.defer_tasks.one": "One task could wait until %s so the urgent work goes first. Let it wait?", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.defer_tasks.many": "%d tasks could wait until %s so the urgent work goes first. Let them wait?", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.defer_tasks.one_no_reset": "One task could wait so the urgent work goes first. Let it wait?", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.defer_tasks.many_no_reset": "%d tasks could wait so the urgent work goes first. Let them wait?", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.defer_tasks.act_one": "Make it low priority", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.defer_tasks.act_many": "Make them low priority", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.held_long.one": "A low-priority task has waited a week.", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.held_long.many": "%d low-priority tasks have waited a week.", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.held_long.act_one": "Make it normal", // COPY REVIEW REQUIRED (S4 usage)
+ "advice.held_long.act_many": "Make them normal", // COPY REVIEW REQUIRED (S4 usage)
"chat.connections.loading_sub": "This takes a moment.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.codex_sub": "Your ChatGPT account, through Codex.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.claude_sub": "Claude signs in on the machine that runs your runner.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go
index 0993fdb7..dad0f270 100644
--- a/internal/equipo/handlers.go
+++ b/internal/equipo/handlers.go
@@ -42,6 +42,8 @@ type pageData struct {
Thin workView
Notebook []notebookLine
Housekeeping housekeepingView
+ // Usage is the Usage page's (usage_page.go).
+ Usage usageView
// HousekeepingSettings is Settings' Housekeeping section.
HousekeepingSettings *hkSettingsView
HousekeepingStream bool
diff --git a/internal/equipo/icons/icons.go b/internal/equipo/icons/icons.go
index 659b490b..a7f3a244 100644
--- a/internal/equipo/icons/icons.go
+++ b/internal/equipo/icons/icons.go
@@ -42,6 +42,7 @@ var icons = map[string]template.HTML{
"info": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>`,
"git": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><circle cx="12" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><circle cx="18" cy="6" r="3"/><path d="M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9"/><path d="M12 12v3"/></svg>`,
"phone": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/></svg>`,
+ "gauge": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/></svg>`,
"clock": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`,
"kebab": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><circle cx="12" cy="12" r="1"/><circle cx="12" cy="5" r="1"/><circle cx="12" cy="19" r="1"/></svg>`,
"menu": `<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" viewBox="0 0 24 24"><path d="M4 12h16"/><path d="M4 6h16"/><path d="M4 18h16"/></svg>`,
diff --git a/internal/equipo/rail.go b/internal/equipo/rail.go
index 30f6e715..71d5fc35 100644
--- a/internal/equipo/rail.go
+++ b/internal/equipo/rail.go
@@ -21,6 +21,7 @@ var railItems = []NavItem{
{Key: "projects", Href: "/projects", CopyKey: "nav.projects", Icon: "folder"},
{Key: "tasks", Href: "/tasks", CopyKey: "nav.tasks", Icon: "check-circle"},
{Key: "needs-you", Href: "/tasks?needs=you", CopyKey: "nav.needs-you", Icon: "inbox"},
+ {Key: "usage", Href: "/usage", CopyKey: "nav.usage", Icon: "gauge"},
{Key: "people", Group: "team", Href: "/people", CopyKey: "nav.people", Icon: "users"},
{Key: "settings-hub", Group: "team", Href: "/conversation/settings", CopyKey: "nav.settings", Icon: "sliders"},
}
@@ -50,6 +51,9 @@ type railView struct {
Cursor int64
Tasks, Projects, Needs railCount
Specialists []railSpecialist
+ // Usage marks Usage with a dot: a connection limited or needing a
+ // sign-in, or a metered one paused (Connections rev 3 §6).
+ Usage bool
}
// specialistRail are the sidebar's specialist rows.
@@ -97,6 +101,9 @@ func (a *application) rail(ctx context.Context, person string) railView {
v.Needs = railCount{needs, true}
}
}
+ if conns, err := c.Connections(ctx, person); err == nil {
+ v.Usage = usageAttention(conns)
+ }
if p, err := c.Projects(ctx, person); err == nil {
v.Projects = railCount{len(p.Items), true}
}
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index b2e941e3..f7f4fd88 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -42,7 +42,7 @@ var pasteBox = func() chatmarkdown.Labels {
}()
func init() {
- for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team"} {
+ for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team", "usage"} {
page := template.Must(template.New("layout").
Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
Funcs(template.FuncMap{"chatMarkdown": pasteBox.Render, "chatDraft": pasteBox.RenderDraft, "fileSize": fileSize, "loadingLine": loadingLine, "split": strings.Split, "since": sinceMillis, "elapsed": elapsedText, "short": short, "agoData": agoData, "agoText": agoText, "hostOf": hostOf, "deref": deref, "agoFormats": agoFormats, "projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index eec21b75..c074999d 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -1216,6 +1216,31 @@ a[equipo-source]:hover, a[equipo-source]:focus-visible { color: var(--rst-text);
[equipo-set-row]:has(input:checked) { background: var(--rst-tint-hover); }
[equipo-set-row]:has(input:focus-visible) { box-shadow: inset 0 0 0 2px var(--rst-focus-edge); }
+/* Usage (connectors spec S4): advice first, then what is available now,
+ spend this month and token use in tabs. Quiet rows, no left borders. */
+[equipo-usage-advice] { display: grid; gap: var(--rst-sp-2); margin-block: var(--rst-sp-4); padding: var(--rst-sp-3) var(--rst-sp-4); border: 1px solid var(--rst-line); border-radius: var(--rst-radius); background: var(--rst-surface); }
+[equipo-usage-advice-line] { display: flex; gap: .5em; align-items: flex-start; margin: 0; }
+[equipo-usage-advice] [equipo-actions] { display: flex; flex-wrap: wrap; gap: var(--rst-sp-2); }
+[equipo-usage-advice] form { margin: 0; }
+[equipo-usage-part] { margin-block: var(--rst-sp-5); }
+[equipo-usage-part] h2 { margin: 0 0 var(--rst-sp-2); font-size: var(--rst-fs-sm); font-weight: 600; color: var(--rst-text-muted); }
+[equipo-usage-list] { display: grid; margin: 0; padding: 0; list-style: none; }
+[equipo-usage-conn], [equipo-usage-spend] { display: flex; flex-wrap: wrap; gap: .25em var(--rst-sp-4); align-items: baseline; justify-content: space-between; padding-block: var(--rst-sp-2); border-block-start: 1px solid var(--rst-line); }
+[equipo-usage-name] b { font-weight: 600; }
+[equipo-usage-facts] { display: inline-flex; flex-wrap: wrap; gap: .25em var(--rst-sp-4); align-items: center; font-size: var(--rst-fs-sm); font-variant-numeric: tabular-nums; }
+[equipo-usage-age] { color: var(--rst-text-muted); font-size: var(--rst-fs-xs); }
+[equipo-usage-tabs] { display: flex; flex-wrap: wrap; gap: var(--rst-sp-2) var(--rst-sp-4); margin-block-end: var(--rst-sp-2); font-size: var(--rst-fs-sm); }
+[equipo-usage-tabs] > span { display: inline-flex; flex-wrap: wrap; gap: var(--rst-sp-1); }
+[equipo-usage-tabs] a { display: inline-flex; align-items: center; min-block-size: var(--rst-tap); padding-inline: .7em; border-radius: var(--rst-radius-pill); color: var(--rst-text-muted); text-decoration: none; }
+[equipo-usage-tabs] a:hover { background: var(--rst-tint-hover); }
+[equipo-usage-tabs] a[aria-current] { color: var(--rst-text); background: var(--rst-tone-neutral-bg); font-weight: 600; }
+[equipo-usage-table-wrap] { overflow-x: auto; }
+[equipo-usage-table] { inline-size: 100%; border-collapse: collapse; font-size: var(--rst-fs-sm); font-variant-numeric: tabular-nums; }
+[equipo-usage-table] th, [equipo-usage-table] td { padding: .45em .6em; text-align: end; border-block-start: 1px solid var(--rst-line); white-space: nowrap; }
+[equipo-usage-table] th:first-child { text-align: start; font-weight: 500; white-space: normal; }
+[equipo-usage-table] thead th { color: var(--rst-text-muted); font-size: var(--rst-fs-xs); font-weight: 600; border-block-start: 0; }
+[equipo-usage-dot] { display: inline-block; inline-size: .5rem; block-size: .5rem; border-radius: 50%; background: var(--rst-tone-warning-fg); }
+
/* Housekeeping: the view beside the Notebook. What Equipo tidied, quiet
lines with Undo while it can; today's budgets as quiet meters. */
[equipo-hk-head] { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: var(--rst-sp-2) var(--rst-sp-4); }
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 9e93f271..fe944c0f 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -2,6 +2,7 @@
{{define "title"}}{{copy "conversation.title"}}{{end}}
{{define "chat-card"}}<li equipo-card="{{.Kind}}"{{if .Receipt}} equipo-receipt{{end}} data-card="{{.ID}}" data-state="{{.State}}" data-turn-id="{{.TurnID}}">
{{if and .Receipt (eq .Kind "task")}}{{template "work-task-receipt" .}}
+{{else if eq .Kind "advice"}}{{if ne .State "resolved"}}<p equipo-card-line data-advice-card>{{icon "lightbulb"}}<span>{{.Line}}</span></p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" name="choice" value="act" type="submit" data-advice-choice="act">{{.ActLabel}}</button><button rst-btn name="choice" value="dismiss" type="submit" data-advice-choice="dismiss">{{.DismissLabel}}</button></form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}{{end}}
{{else if eq .Kind "housekeeping"}}<p equipo-card-line data-digest>{{icon "list-checks"}}<span>{{.Line}} <a href="/housekeeping" data-digest-link>{{copy "chat.housekeeping.link"}}</a></span></p>
{{else if .Receipt}}<p equipo-card-line>{{icon "folder"}}<span>{{.Line}}</span></p>{{if .Open}}<button type="button" equipo-receipt-more aria-expanded="false" aria-controls="acts-{{.ID}}" aria-label="{{copy "chat.card.more"}}">⋯</button><span equipo-receipt-actions id="acts-{{.ID}}">{{if or (eq .Kind "home") (eq .Kind "combined")}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}"><button equipo-link name="choice" value="undo" type="submit" data-card-undo>{{copy "chat.card.undo"}}</button></form>{{else}}<details equipo-change><summary equipo-link>{{.Change}}</summary><form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}"><select rst-input name="choice" aria-label="{{.Change}}">{{range .Choices}}<option>{{.}}</option>{{end}}</select><button rst-btn="primary" type="submit">{{copy "chat.card.use"}}</button></form></details>{{if .Remove}}<form method="post" action="/conversation/projects/{{.ProjectID}}/remove" data-card-form><button equipo-link type="submit">{{copy "chat.card.remove"}}</button></form>{{end}}{{end}}</span>{{end}}
{{else if eq .Kind "question"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<button rst-btn name="choice" value="{{.}}" type="submit">{{.}}</button>{{else}}<input rst-input name="choice" required maxlength="2000" aria-label="{{copy "chat.card.answer"}}"><button rst-btn="primary" type="submit">{{copy "chat.card.answer"}}</button>{{end}}</form>{{else}}<p equipo-card-note>{{printf (copy "chat.card.answered") .Choice}}</p>{{end}}
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html
index 7f997f36..fb8577cb 100644
--- a/internal/equipo/templates/chrome.html
+++ b/internal/equipo/templates/chrome.html
@@ -9,7 +9,7 @@
{{define "region:rail"}}<nav rst-shell-nav id="rail"{{if and .RailArriving (not .SettingsNav)}} data-arriving{{end}} data-nav-stream data-cursor="{{.Rail.Cursor}}" data-key="{{.Key}}" data-ago-formats="{{agoFormats}}">
<div equipo-team-heading>{{template "brand" .}}</div>
{{$key := .Key}}{{$rail := .Rail}}
-{{$team := false}}{{range .Nav}}{{if and (eq .Group "team") (not $team)}}{{$team = true}}{{template "rail-specialists" $rail}}<p equipo-nav-group>{{copy "nav.team"}}</p>{{end}}<a id="nav-{{.Key}}" href="{{.Href}}"{{if eq .Key $key}} aria-current="page"{{end}}>{{icon .Icon}}<span>{{copy .CopyKey}}</span>{{if eq .Key "tasks"}}{{template "rail-count" $rail.Tasks}}{{else if eq .Key "projects"}}{{template "rail-count" $rail.Projects}}{{else if eq .Key "needs-you"}}{{template "rail-count-attention" $rail.Needs}}{{end}}</a>
+{{$team := false}}{{range .Nav}}{{if and (eq .Group "team") (not $team)}}{{$team = true}}{{template "rail-specialists" $rail}}<p equipo-nav-group>{{copy "nav.team"}}</p>{{end}}<a id="nav-{{.Key}}" href="{{.Href}}"{{if eq .Key $key}} aria-current="page"{{end}}>{{icon .Icon}}<span>{{copy .CopyKey}}</span>{{if eq .Key "tasks"}}{{template "rail-count" $rail.Tasks}}{{else if eq .Key "projects"}}{{template "rail-count" $rail.Projects}}{{else if eq .Key "needs-you"}}{{template "rail-count-attention" $rail.Needs}}{{else if and (eq .Key "usage") $rail.Usage}}<small equipo-count equipo-usage-dot data-usage-dot data-attention role="img" aria-label="{{copy "nav.usage_attention"}}"></small>{{end}}</a>
{{end}}
</nav>{{end}}
{{define "rail-count"}}{{if not .Known}}<small equipo-count data-count>{{copy "counts.unavailable"}}</small>{{else if .N}}<small equipo-count data-count>{{.N}}</small>{{end}}{{end}}
diff --git a/internal/equipo/templates/usage.html b/internal/equipo/templates/usage.html
new file mode 100644
index 00000000..40d558cf
--- /dev/null
+++ b/internal/equipo/templates/usage.html
@@ -0,0 +1,16 @@
+{{define "title"}}{{copy "usage.title"}}{{end}}
+{{define "content"}}{{with .Usage}}
+<section equipo-work equipo-inner equipo-usage data-usage id="usage-view">
+<div equipo-page-head><h1>{{copy "usage.title"}}</h1><p>{{copy "usage.lede"}}</p></div>
+{{with .Advice}}<section equipo-usage-advice data-advice="{{.ID}}" data-advice-kind="{{.Kind}}" aria-label="{{copy "usage.advice"}}"><p equipo-usage-advice-line>{{icon "lightbulb"}}<span data-advice-text>{{.Text}}</span></p><div equipo-actions><form method="post" action="/usage/advice/{{.ID}}/act"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" type="submit" data-advice-act>{{.Act}}</button></form><form method="post" action="/usage/advice/{{.ID}}/dismiss"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn type="submit" data-advice-dismiss>{{.Dismiss}}</button></form></div></section>{{end}}
+<section equipo-usage-part aria-labelledby="usage-now"><h2 id="usage-now">{{copy "usage.now"}}</h2>
+{{if .NoConnections}}<p data-empty-state="usage.no_connections">{{copy "usage.no_connections"}} <a href="/conversation/settings/connections/add">{{copy "usage.connect"}}</a></p>{{else}}<ul equipo-usage-list role="list">{{range .Available}}<li equipo-usage-conn data-available="{{.ID}}" data-provider="{{.Provider}}" data-state="{{.State}}"><span equipo-usage-name><b>{{.Name}}</b> <span equipo-conn-state data-s="{{.State}}">{{.Words}}</span></span><span equipo-usage-facts>{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"{{with .At}} title="{{.}}"{{end}}><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}{{with .Spend}}<span data-available-spend>{{.}}</span>{{end}}{{with .Age}}<span equipo-usage-age data-reading-age>{{.}}</span>{{end}}{{with .Note}}<span equipo-usage-age data-reading-none>{{.}}</span>{{end}}</span></li>{{end}}</ul>{{end}}</section>
+<section equipo-usage-part aria-labelledby="usage-spend"><h2 id="usage-spend">{{copy "usage.spend"}}</h2>
+<ul equipo-usage-list role="list">{{range .Spend}}<li equipo-usage-spend data-spend="{{.ID}}"><span equipo-usage-name><b>{{.Name}}</b>{{with .Paused}} <span equipo-conn-state data-s="limited">{{.}}</span>{{end}}</span><span equipo-usage-facts>{{with .Line}}<span data-spend-line>{{.}}</span>{{end}}{{with .Tail}}<span equipo-usage-age>{{.}}</span>{{end}}{{with .Source}}<span equipo-usage-age data-price-source>{{.}}</span>{{end}}</span></li>{{end}}{{range .Plans}}<li equipo-usage-spend data-plan="{{.ID}}"><span equipo-usage-name><b>{{.Name}}</b>{{with .Plan}} <span equipo-usage-age>{{.}}</span>{{end}}</span><span equipo-usage-facts><span data-plan-tokens>{{.Tokens}}</span></span></li>{{end}}</ul>
+{{if not .Spend}}<p equipo-usage-age data-empty-state="usage.spend_none">{{copy "usage.spend_none"}}</p>{{end}}</section>
+<section equipo-usage-part aria-labelledby="usage-tokens"><h2 id="usage-tokens">{{copy "usage.tokens"}}</h2>
+<nav equipo-usage-tabs aria-label="{{copy "usage.tokens"}}"><span role="list">{{range .Periods}}<a role="listitem" href="{{.Href}}" data-period="{{.Key}}"{{if .On}} aria-current="true"{{end}}>{{.Label}}</a>{{end}}</span><span role="list">{{range .By}}<a role="listitem" href="{{.Href}}" data-by="{{.Key}}"{{if .On}} aria-current="true"{{end}}>{{.Label}}</a>{{end}}</span></nav>
+<div equipo-usage-table-wrap><table equipo-usage-table data-usage-table><thead><tr><th scope="col">{{.Column}}</th><th scope="col">{{copy "usage.col.input"}}</th><th scope="col">{{copy "usage.col.cached"}}</th><th scope="col">{{copy "usage.col.output"}}</th><th scope="col">{{copy "usage.col.estimate"}}</th></tr></thead>
+<tbody>{{range .Rows}}<tr data-usage-row="{{.ID}}"><th scope="row">{{.Label}}</th><td>{{.Input}}</td><td>{{.Cached}}</td><td>{{.Output}}</td><td>{{.Estimate}}</td></tr>{{else}}<tr><td colspan="5" data-empty-state="usage.tokens_empty">{{copy "usage.tokens_empty"}}</td></tr>{{end}}</tbody></table></div>
+{{if .LeftOut}}<p equipo-usage-age>{{copy "work.spend_left_out"}}</p>{{end}}</section>
+</section>{{end}}{{end}}
diff --git a/internal/equipo/usage_page.go b/internal/equipo/usage_page.go
new file mode 100644
index 00000000..16965ac6
--- /dev/null
+++ b/internal/equipo/usage_page.go
@@ -0,0 +1,302 @@
+package equipo
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The Usage page (Connections rev 3 §6, connectors spec rev 3.2 S4):
+// advice at the top, then what is available now (each connection's state
+// and the headroom its provider reported, with the reading's age), spend
+// this month (metered connections against their budgets, with where the
+// prices come from, and subscriptions as their plan and tokens), and
+// token use in tabs (today, this week, this month; by connection, role,
+// project or task).
+
+type usageView struct {
+ Advice *wire.Advice
+ Available []usageConn
+ NoConnections bool
+ Spend []usageSpend
+ Plans []usagePlan
+ Periods, By []usageTab
+ Column string
+ Rows []usageRowView
+ LeftOut bool
+}
+
+// usageConn is one connection's availability: its state in words, the
+// meters its provider reported, and how old that reading is.
+type usageConn struct {
+ ID, Provider, Name, Glyph, State, Words string
+ Meters []connMeter
+ Age, Note, Spend string
+}
+
+// usageSpend is a metered connection's spend line, its tail, its pause
+// and the price table's source.
+type usageSpend struct {
+ ID, Name, Line, Tail, Paused, Source string
+}
+
+// usagePlan is a subscription: its plan and its tokens this month, never
+// a money figure.
+type usagePlan struct {
+ ID, Name, Plan, Tokens string
+}
+
+type usageTab struct {
+ Key, Label, Href string
+ On bool
+}
+
+type usageRowView struct {
+ ID, Label, Input, Cached, Output, Estimate string
+}
+
+// readingAge is a reading's age in words: Codex's is refreshed without a
+// turn ("as of 2 h ago"), Claude's only when a turn reports it ("as last
+// reported 2 h ago"); nothing when the runner did not say when.
+func readingAge(c wire.Connection, now time.Time) string {
+ if c.Headroom == nil || c.Headroom.CheckedAt == nil {
+ return ""
+ }
+ key := "usage.reading.as_of"
+ if c.Provider == wire.ProviderClaude {
+ key = "usage.reading.last_reported"
+ }
+ return fmt.Sprintf(copyText(key), ago(now, *c.Headroom.CheckedAt))
+}
+
+// priceSource says where a price table's prices come from: the provider
+// and the day its public page was read, from the table's version
+// (tensorx-2026-11-12), never a sentence per provider.
+func priceSource(provider, version string) string {
+ if len(version) < 11 {
+ return ""
+ }
+ day, err := time.Parse("2006-01-02", version[len(version)-10:])
+ if err != nil || version[len(version)-11] != '-' {
+ return ""
+ }
+ return fmt.Sprintf(copyText("usage.price_source"), providerName(provider), day.Format("2 Jan 2006"))
+}
+
+// usageLabel is a grouping's row label: a connection by its provider
+// and account, a role by name, a project or task by its own name, and
+// rows with no task as the conversation.
+func usageLabel(by string, row wire.UsageRow, conns map[string]wire.Connection) string {
+ switch by {
+ case wire.UsageByConnection:
+ if c, ok := conns[row.ID]; ok {
+ if c.Label != "" {
+ return fmt.Sprintf(copyText("chat.connections.named"), providerName(c.Provider), c.Label)
+ }
+ return providerName(c.Provider)
+ }
+ return providerName(row.Label)
+ case wire.UsageByRole:
+ switch row.ID {
+ case "coordinator", "":
+ return copyText("conversation.coordinator")
+ case "ask":
+ return copyText("work.spend_questions")
+ case "probe":
+ return copyText("usage.role.probe")
+ }
+ if name := copyText("work.specialist." + row.ID); name != "" {
+ return name
+ }
+ return row.ID
+ }
+ if row.ID == "" {
+ return copyText("usage.no_task")
+ }
+ return row.Label
+}
+
+// tokensWithFloor is a token figure, "at least" when a row lacked one.
+func tokensWithFloor(n int64, partial bool) string {
+ if partial {
+ return fmt.Sprintf(copyText("usage.at_least"), tokenCount(n))
+ }
+ return tokenCount(n)
+}
+
+func usageHref(period, by string) string {
+ return "/usage?" + url.Values{"period": {period}, "by": {by}}.Encode()
+}
+
+// usagePage builds the page from the person's connections, the period's
+// totals, this month's totals by connection and the advice to show.
+func usagePage(conns []wire.Connection, totals, month wire.UsageTotals, advice *wire.Advice, now time.Time) usageView {
+ v := usageView{Advice: advice, LeftOut: totals.LeftOut}
+ byID := map[string]wire.Connection{}
+ prices := map[string]string{}
+ for _, p := range month.Prices {
+ prices[p.Connection] = p.PriceVersion
+ }
+ monthly := map[string]wire.UsageRow{}
+ for _, r := range month.Rows {
+ monthly[r.ID] = r
+ }
+ for _, c := range conns {
+ byID[c.ID] = c
+ if c.State == wire.ConnConnecting || c.LocalID == "" {
+ continue
+ }
+ c = freshen(c, now)
+ u := usageConn{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), State: c.State}
+ if c.Label != "" && c.Kind != wire.KindAPIKey {
+ u.Name = fmt.Sprintf(copyText("chat.connections.named"), u.Name, c.Label)
+ }
+ metered := false
+ if c.Headroom != nil && c.State != wire.ConnSignedOut && c.State != wire.ConnSignInAgain {
+ for _, w := range c.Headroom.Windows {
+ m := meterOf(w, now)
+ metered = metered || m.Resets != ""
+ u.Meters = append(u.Meters, m)
+ }
+ }
+ u.Words = connectionState(c, now, metered)
+ if c.State == wire.ConnError {
+ u.State, u.Words = wire.ConnSignInAgain, copyText("chat.connections.sign_in_again")
+ }
+ switch {
+ case c.Kind == wire.KindAPIKey:
+ // A metered connection's availability is its budget.
+ var row connRow
+ meteredFacts(&row, c, "", now)
+ u.Spend = row.Spend
+ if row.Paused != "" {
+ u.Words = row.Paused
+ }
+ if row.Unknown != "" {
+ u.Words = row.Unknown
+ }
+ s := usageSpend{ID: c.ID, Name: providerName(c.Provider), Line: row.Spend, Tail: row.SpendTail, Paused: row.Paused + row.Unknown, Source: priceSource(c.Provider, prices[c.ID])}
+ v.Spend = append(v.Spend, s)
+ case u.State != wire.ConnSignedOut:
+ if len(u.Meters) > 0 {
+ u.Age = readingAge(c, now)
+ } else if u.State == wire.ConnHealthy {
+ u.Note = copyText("usage.reading.none")
+ }
+ p := usagePlan{ID: c.ID, Name: u.Name, Tokens: fmt.Sprintf(copyText("usage.plan_tokens"), tokenCount(monthly[c.ID].Input+monthly[c.ID].Output))}
+ if c.Plan != "" {
+ p.Plan = fmt.Sprintf(copyText("usage.plan"), strings.ToUpper(c.Plan[:1])+c.Plan[1:])
+ }
+ v.Plans = append(v.Plans, p)
+ }
+ v.Available = append(v.Available, u)
+ }
+ v.NoConnections = len(v.Available) == 0
+ for _, p := range wire.UsagePeriods {
+ v.Periods = append(v.Periods, usageTab{Key: p, Label: copyText("usage.period." + p), Href: usageHref(p, totals.By), On: p == totals.Period})
+ }
+ for _, b := range wire.UsageGroupings {
+ v.By = append(v.By, usageTab{Key: b, Label: copyText("usage.by." + b), Href: usageHref(totals.Period, b), On: b == totals.By})
+ if b == totals.By {
+ v.Column = copyText("usage.by." + b)
+ }
+ }
+ for _, r := range totals.Rows {
+ row := usageRowView{ID: r.ID, Label: usageLabel(totals.By, r, byID), Input: tokensWithFloor(r.Input, r.Partial), Cached: tokenCount(r.CachedInput), Output: tokensWithFloor(r.Output, r.Partial)}
+ if r.Cost != nil {
+ row.Estimate = chat.Money(*r.Cost, r.Currency)
+ }
+ v.Rows = append(v.Rows, row)
+ }
+ return v
+}
+
+// usageAttention is the sidebar's dot: a connection limited or needing a
+// sign-in, or a metered one paused by its budget or its unknown spend.
+func usageAttention(conns []wire.Connection) bool {
+ for _, c := range conns {
+ if c.State == wire.ConnLimited || c.State == wire.ConnSignInAgain {
+ return true
+ }
+ 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) {
+ return true
+ }
+ }
+ return false
+}
+
+// usage is GET /usage.
+func (a *application) usage(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ ctx, address, ok := sessionContext(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ period, by := r.URL.Query().Get("period"), r.URL.Query().Get("by")
+ if !slices.Contains(wire.UsagePeriods, period) {
+ period = wire.UsageMonth
+ }
+ if !slices.Contains(wire.UsageGroupings, by) {
+ by = wire.UsageByConnection
+ }
+ c := a.store.Chat()
+ conns, err := c.Connections(ctx, address)
+ if err == nil {
+ var totals, month wire.UsageTotals
+ if totals, err = c.UsageTotals(ctx, address, period, by); err == nil {
+ if month, err = c.UsageTotals(ctx, address, wire.UsageMonth, wire.UsageByConnection); err == nil {
+ var list wire.AdviceList
+ if list, err = c.Advice(ctx, address); err == nil {
+ data, perr := a.page(r, "usage")
+ if perr != nil {
+ a.failure(w, r, perr)
+ return
+ }
+ var advice *wire.Advice
+ if len(list.Items) > 0 {
+ advice = &list.Items[0]
+ }
+ data.Title = "usage.title"
+ data.Usage = usagePage(conns, totals, month, advice, c.Now())
+ render(w, "usage", data)
+ return
+ }
+ }
+ }
+ }
+ a.failure(w, r, chatError(err))
+}
+
+// usageAdvice is an advice card's action or Not now from the page; a
+// card that moved or was answered elsewhere shows the page as it is.
+func (a *application) usageAdvice(act bool) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ a.chatActionTo(w, r, "/usage", func(ctx context.Context, address string) error {
+ revision, err := strconv.ParseInt(r.FormValue("revision"), 10, 64)
+ if err != nil {
+ return chat.ErrCardConflict
+ }
+ do := a.store.Chat().DismissAdvice
+ if act {
+ do = a.store.Chat().ActAdvice
+ }
+ _, err = do(ctx, address, chi.URLParam(r, "id"), wire.AdviceAction{Revision: revision})
+ if errors.Is(err, chat.ErrConflict) || errors.Is(err, chat.ErrNotFound) {
+ return chat.ErrCardConflict
+ }
+ return err
+ })
+ }
+}
diff --git a/internal/equipo/usage_page_test.go b/internal/equipo/usage_page_test.go
new file mode 100644
index 00000000..8f27084b
--- /dev/null
+++ b/internal/equipo/usage_page_test.go
@@ -0,0 +1,164 @@
+package equipo
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+var usageNow = time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC)
+
+func usageConns() []wire.Connection {
+ week, five := usageNow.Add(70*time.Hour), usageNow.Add(3*time.Hour)
+ codexRead, claudeRead := usageNow.Add(-2*time.Hour), usageNow.Add(-5*time.Hour)
+ return []wire.Connection{
+ {ID: "cn_cx", LocalID: "codex-1", RunnerID: "r1", Provider: wire.ProviderCodex, Kind: wire.KindSubscription, Plan: "pro", State: wire.ConnHealthy, Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "primary", UsedPercent: 42, Minutes: 300, ResetsAt: &five}, {Name: "secondary", UsedPercent: 18, Minutes: 10080, ResetsAt: &week}}, CheckedAt: &codexRead}},
+ {ID: "cn_cl", LocalID: "claude-1", RunnerID: "r1", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "seven_day", UsedPercent: 81, Minutes: 10080, ResetsAt: &week}}, CheckedAt: &claudeRead}},
+ {ID: "cn_old", LocalID: "codex-2", RunnerID: "r1", Provider: wire.ProviderCodex, Kind: wire.KindSubscription, Label: "second@example.com", State: wire.ConnHealthy, Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "primary", UsedPercent: 10, Minutes: 300, ResetsAt: &five}}}},
+ {ID: "cn_tx", LocalID: "tensorx-1", RunnerID: "r1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Harness: wire.HarnessPi, Billing: wire.BillingMetered, State: wire.ConnHealthy, 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"}},
+ {ID: "cn_new", Provider: wire.ProviderCodex, State: wire.ConnConnecting},
+ }
+}
+
+func usageTotals() (wire.UsageTotals, wire.UsageTotals) {
+ cost := int64(6_200_000)
+ month := wire.UsageTotals{Period: wire.UsageMonth, By: wire.UsageByConnection, Rows: []wire.UsageRow{
+ {ID: "cn_cx", Label: "codex", Input: 1_200_000, CachedInput: 800_000, Output: 40_000, Attempts: 20},
+ {ID: "cn_tx", Label: "tensorx", Input: 120_000, Output: 9_000, Cost: &cost, Currency: "USD", Attempts: 7},
+ }, Prices: []wire.PriceSource{{Connection: "cn_tx", PriceVersion: "tensorx-2026-11-12"}}}
+ byRole := wire.UsageTotals{Period: wire.UsageWeek, By: wire.UsageByRole, Rows: []wire.UsageRow{
+ {ID: wire.SpecialistEngineering, Label: wire.SpecialistEngineering, Input: 900_000, Output: 30_000, Partial: true},
+ {ID: "coordinator", Label: "coordinator", Input: 50_000, Output: 2_000},
+ {ID: "probe", Label: "probe", Input: 1, Output: 1, Cost: &cost, Currency: "USD"},
+ }}
+ return byRole, month
+}
+
+// The Usage page from the person's connections and usage: availability
+// with each reading's age (Codex refreshed, Claude as last reported,
+// none from an older runner), spend this month with where the prices
+// come from read from the price table's version, subscriptions as their
+// plan and tokens, and token use in tabs over one dataset.
+func TestUsagePage(t *testing.T) {
+ byRole, month := usageTotals()
+ adv := &wire.Advice{ID: "ad_1", Kind: wire.AdviceBudgetNear, Text: "TensorX: $0.84 of today’s $1.", Act: "Raise today’s budget to $2", Dismiss: "Leave it", Revision: 1}
+ v := usagePage(usageConns(), byRole, month, adv, usageNow)
+ if v.Advice != adv || len(v.Available) != 4 || v.NoConnections {
+ t.Fatalf("view %+v", v)
+ }
+ got := map[string]usageConn{}
+ for _, c := range v.Available {
+ got[c.ID] = c
+ }
+ if c := got["cn_cx"]; c.Age != "as of "+ago(usageNow, usageNow.Add(-2*time.Hour)) || len(c.Meters) != 2 {
+ t.Fatalf("codex %+v", c)
+ }
+ if c := got["cn_cl"]; c.Age != "as last reported "+ago(usageNow, usageNow.Add(-5*time.Hour)) || len(c.Meters) != 1 {
+ t.Fatalf("claude %+v", c)
+ }
+ if c := got["cn_old"]; c.Age != "" || !strings.Contains(c.Name, "second@example.com") {
+ t.Fatalf("a reading from an older runner says no age: %+v", c)
+ }
+ if c := got["cn_tx"]; c.Spend == "" || c.Age != "" || len(c.Meters) != 0 {
+ t.Fatalf("tensorx %+v", c)
+ }
+ if len(v.Spend) != 1 || v.Spend[0].Source != "TensorX prices taken from the public page on 12 Nov 2026." || !strings.Contains(v.Spend[0].Line, "$0.84") {
+ t.Fatalf("spend %+v", v.Spend)
+ }
+ if len(v.Plans) != 3 || v.Plans[0].Plan != "Pro plan" || !strings.HasPrefix(v.Plans[0].Tokens, "1.2M") {
+ t.Fatalf("plans %+v", v.Plans)
+ }
+ month.Prices[0].PriceVersion = "tensorx-2027-01-03"
+ if again := usagePage(usageConns(), byRole, month, adv, usageNow); again.Spend[0].Source != "TensorX prices taken from the public page on 3 Jan 2027." {
+ t.Fatalf("the source does not follow the price table: %q", again.Spend[0].Source)
+ }
+ if v.Column != "Role" || len(v.Rows) != 3 || v.Rows[0].Label != "Engineering" || v.Rows[0].Input != "at least 900k" || v.Rows[1].Label != "Coordinator" || v.Rows[2].Label != "Connection checks" || v.Rows[2].Estimate != "$6.20" || v.Rows[0].Estimate != "" {
+ t.Fatalf("rows %+v", v.Rows)
+ }
+ for _, tab := range append(v.Periods, v.By...) {
+ if tab.On != (tab.Key == wire.UsageWeek || tab.Key == wire.UsageByRole) {
+ t.Fatalf("tab %+v", tab)
+ }
+ }
+ if v.Periods[0].Href != "/usage?by=role&period=day" || v.By[0].Href != "/usage?by=connection&period=week" {
+ t.Fatalf("tabs %+v %+v", v.Periods[0], v.By[0])
+ }
+ // The page renders: the advice first, each part once.
+ data := pageData{Usage: v}
+ var buf bytes.Buffer
+ if err := pages["usage"].ExecuteTemplate(&buf, "content", data); err != nil {
+ t.Fatal(err)
+ }
+ html := buf.String()
+ for _, want := range []string{`data-advice="ad_1"`, `data-advice-act>Raise today’s budget to $2`, `data-reading-age>as of `, `data-price-source>TensorX prices taken from the public page on 12 Nov 2026.`, `data-usage-row="engineering"`, `aria-current="true">This week`} {
+ if !strings.Contains(html, want) {
+ t.Fatalf("page lacks %s", want)
+ }
+ }
+ if strings.Index(html, "data-advice=") > strings.Index(html, "usage-now") {
+ t.Fatal("advice is not at the top")
+ }
+}
+
+// Where prices come from is read from the table's version, never written
+// per provider; a version that names no day says nothing.
+func TestPriceSource(t *testing.T) {
+ for version, want := range map[string]string{
+ "tensorx-2026-11-12": "TensorX prices taken from the public page on 12 Nov 2026.",
+ "tensorx-2027-01-03": "TensorX prices taken from the public page on 3 Jan 2027.",
+ "tensorx": "",
+ "tensorx2026-11-12": "",
+ "": "",
+ } {
+ if got := priceSource(wire.ProviderTensorX, version); got != want {
+ t.Fatalf("%q: %q", version, got)
+ }
+ }
+}
+
+// The sidebar's dot: a connection limited or needing a sign-in, or a
+// metered one paused by a budget or unknown spend; quiet otherwise.
+func TestUsageAttention(t *testing.T) {
+ conns := usageConns()
+ if usageAttention(conns) {
+ t.Fatal("a dot with nothing to look at")
+ }
+ for what, change := range map[string]func([]wire.Connection){
+ "limited": func(cs []wire.Connection) { cs[0].State = wire.ConnLimited },
+ "sign in again": func(cs []wire.Connection) { cs[1].State = wire.ConnSignInAgain },
+ "day's budget": func(cs []wire.Connection) { cs[3].Spend = &wire.Spend{Day: 1_000_000, Month: 6_000_000} },
+ "month's budget": func(cs []wire.Connection) { cs[3].Spend = &wire.Spend{Day: 0, Month: 10_000_000} },
+ "spend unknown": func(cs []wire.Connection) { cs[3].Spend = &wire.Spend{Unknown: true} },
+ } {
+ cs := usageConns()
+ change(cs)
+ if !usageAttention(cs) {
+ t.Fatalf("no dot: %s", what)
+ }
+ }
+}
+
+// The routing line: a step held for headroom says how old the reading it
+// waits on is; a reading with no time says nothing more.
+func TestHoldLineSaysTheReadingsAge(t *testing.T) {
+ reset := usageNow.Add(70 * time.Hour)
+ step := wire.Step{ID: "s1", Hold: &wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}}
+ v := taskLine{Step: &step}
+ v.Hold = holdOf(step, true)
+ v.StageLine = v.Hold.Line
+ holdReading(&v, usageConns(), usageNow)
+ if !strings.HasPrefix(v.Hold.Line, "Waiting for your Claude allowance to reset") || !strings.HasSuffix(v.Hold.Line, " · as last reported "+ago(usageNow, usageNow.Add(-5*time.Hour))) || v.StageLine != v.Hold.Line {
+ t.Fatalf("hold line %q / %q", v.Hold.Line, v.StageLine)
+ }
+ step.Hold.Connection, step.Hold.Provider = "codex-2", wire.ProviderCodex
+ v = taskLine{Step: &step}
+ v.Hold = holdOf(step, true)
+ before := v.Hold.Line
+ holdReading(&v, usageConns(), usageNow)
+ if v.Hold.Line != before {
+ t.Fatalf("a reading with no time: %q", v.Hold.Line)
+ }
+}
diff --git a/internal/equipo/work_pages.go b/internal/equipo/work_pages.go
index 5d857948..4b3b0470 100644
--- a/internal/equipo/work_pages.go
+++ b/internal/equipo/work_pages.go
@@ -471,6 +471,10 @@ func (a *application) richTasks(ctx context.Context, viewer string, list []wire.
if err != nil {
return nil, err
}
+ // The viewer's connections, for the age of the reading a hold for
+ // headroom was decided on (connectors spec rev 3.2 §6). Unread, the
+ // line says no age.
+ conns, _ := a.store.Chat().Connections(ctx, viewer)
now := time.Now()
out := make([]taskLine, 0, len(list))
for _, t := range list {
@@ -482,11 +486,36 @@ func (a *application) richTasks(ctx context.Context, viewer string, list []wire.
v := taskLineOf(t, viewer)
v.MergeDropped = dropped
v.richOf(t, viewer, card, now)
+ holdReading(&v, conns, now)
out = append(out, v)
}
return out, nil
}
+// holdReading adds to a hold for headroom how old the reading it waits on
+// is: "as of 2 h ago" for Codex, "as last reported 2 h ago" for Claude.
+func holdReading(v *taskLine, conns []wire.Connection, now time.Time) {
+ if v.Hold == nil || v.Step == nil || v.Step.Hold == nil || v.Step.Hold.Reason != wire.HoldHeadroom {
+ return
+ }
+ h := v.Step.Hold
+ for _, c := range conns {
+ if c.LocalID != h.Connection || c.Provider != h.Provider {
+ continue
+ }
+ age := readingAge(c, now)
+ if age == "" {
+ return
+ }
+ line := fmt.Sprintf(copyText("work.hold.reading"), v.Hold.Line, age)
+ if v.StageLine == v.Hold.Line {
+ v.StageLine = line
+ }
+ v.Hold.Line = line
+ return
+ }
+}
+
// workTasks is GET /tasks: every team task grouped by what matters
// (Needs you, In progress, Ready to merge, Done), optionally for one
// project (?project=) or person (?person=). ?needs=you is Needs you.
diff --git a/internal/headless/browser_usage_test.go b/internal/headless/browser_usage_test.go
new file mode 100644
index 00000000..ec5cb470
--- /dev/null
+++ b/internal/headless/browser_usage_test.go
@@ -0,0 +1,81 @@
+//go:build browser
+
+package headless
+
+import (
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+
+ "amadan.net/oficina/equipo/internal/browsertest"
+ "amadan.net/oficina/equipo/internal/thintest"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Connectors spec rev 3.2 S4 in a browser: the Usage page at 1280 with a
+// mouse and at 390 with touch. The sidebar leads to it; advice is the one
+// card at the top, its action within reach; what is available shows each
+// reading's age; spend this month says where the prices come from; the
+// token tabs switch without a script; nothing scrolls sideways. Raise
+// today's budget acts through the ordinary call: the runner gets the
+// budget frame at twice the figure, and the card is gone.
+func TestBrowserUsageAndAdvice(t *testing.T) {
+ for _, width := range []int64{1280, 390} {
+ t.Run(strconv.FormatInt(width, 10), func(t *testing.T) {
+ inst := thintest.StartInstance(t)
+ chats := inst.Store.Chat()
+ midday := time.Now().UTC().Truncate(24 * time.Hour).Add(12 * time.Hour)
+ chats.SetHousekeepingClock(func() time.Time { return midday })
+ runner := dialFakeAt(t, inst, wire.ProtocolCurrent)
+ read := time.Now().UTC().Add(-2 * time.Hour)
+ reset := midday.Add(70 * time.Hour)
+ runner.hello(t,
+ wire.HeldConnection{LocalID: "codex-1", Person: thintest.Owner, Provider: wire.ProviderCodex, Kind: wire.KindSubscription, Label: thintest.Owner, State: wire.ConnHealthy, Plan: "pro", Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "primary", UsedPercent: 42, Minutes: 300, ResetsAt: &reset}, {Name: "secondary", UsedPercent: 18, Minutes: 10080, ResetsAt: &reset}}, CheckedAt: &read}},
+ wire.HeldConnection{LocalID: "tensorx-1", Person: thintest.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"}},
+ )
+ client := thintest.NewClient(inst.URL, inst.DeviceToken(t))
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ if list, err := client.Connections(t.Context()); err == nil && len(list.Items) == 2 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the connections did not arrive")
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if err := chats.RefreshAdvice(t.Context(), thintest.Owner); err != nil {
+ t.Fatal(err)
+ }
+ c := inst.Cookie()
+ p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600)
+ t.Cleanup(p.stop)
+
+ p.run(chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('#nav-usage')`))
+ p.check(`document.querySelector('#nav-usage').getAttribute('href')==='/usage'`, "the sidebar does not lead to Usage")
+ p.check(`!!document.querySelector('[data-advice-card]') && document.querySelectorAll('[equipo-card="advice"]').length===1`, "no one quiet advice card in the conversation")
+ p.run(chromedp.Navigate(inst.URL+"/usage"), browsertest.Wait(`!!document.querySelector('[data-usage]')`))
+ p.check(`(()=>{const a=document.querySelector('[data-advice]');const now=document.querySelector('#usage-now');return a&&now&&a.compareDocumentPosition(now)&Node.DOCUMENT_POSITION_FOLLOWING&&a.querySelector('[data-advice-text]').textContent==='TensorX: $0.84 of today’s $1.'})()`, "the advice is not the card at the top")
+ p.check(`(()=>{const b=document.querySelector('[data-advice-act]').getBoundingClientRect();return b.width>0&&b.height>=`+map[bool]string{true: "24", false: "44"}[width > 600]+`&&b.top>=0})()`, "the advice's action is out of reach")
+ p.check(`document.querySelector('[data-available] [data-reading-age]').textContent==='as of 2 h ago'`, "no reading age on Codex's row")
+ p.check(`document.querySelector('[data-spend] [data-spend-line]').textContent.includes('$0.84 of $1 today')`, "no spend line")
+ p.check(`document.documentElement.scrollWidth<=document.documentElement.clientWidth`, "the page scrolls sideways")
+
+ // The tabs are links: by role this week.
+ p.run(chromedp.Navigate(inst.URL+"/usage?period=week&by=role"), browsertest.Wait(`!!document.querySelector('[data-by="role"][aria-current]')`))
+ p.check(`!!document.querySelector('[data-period="week"][aria-current]') && document.querySelector('[data-usage-table] thead th').textContent==='Role'`, "the tabs did not switch")
+
+ // Act: the budget call, at twice today's figure.
+ p.run(chromedp.Navigate(inst.URL+"/usage"), browsertest.Wait(`!!document.querySelector('[data-advice-act]')`))
+ p.check(`(()=>{document.querySelector('[data-advice-act]').click();return true})()`, "act")
+ b := runner.expect(t, wire.FrameBudget).(*wire.BudgetCommand)
+ if b.Budget.Day != 2_000_000 || b.Budget.Month != 10_000_000 || b.Budget.Revision != 2 {
+ t.Fatalf("budget %+v", b.Budget)
+ }
+ p.run(waitLong(`location.pathname==='/usage' && !document.querySelector('[data-advice]')`))
+ connShotOn(t, p, "2026-11-12", "usage", width)
+ })
+ }
+}
diff --git a/internal/thintest/usage_contract_test.go b/internal/thintest/usage_contract_test.go
new file mode 100644
index 00000000..3440e8f1
--- /dev/null
+++ b/internal/thintest/usage_contract_test.go
@@ -0,0 +1,160 @@
+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>as 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 != "Leave it" || a.Text != "TensorX: $0.84 of today’s $1." {
+ 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.") {
+ 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, "Waiting for your Claude allowance to reset") || !strings.Contains(page, " · as 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")
+ }
+}