Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cyclops-cs): redesign billing usage breakdown (#7141)
r33drichardsb0ab95af2e45
diff --git a/libs/fleet/backend/auth/policy_characterization_test.go b/libs/fleet/backend/auth/policy_characterization_test.goindex 4f583dee89..eb02b64e0c 100644--- a/libs/fleet/backend/auth/policy_characterization_test.go+++ b/libs/fleet/backend/auth/policy_characterization_test.go@@ -163,6 +163,7 @@ func characterizationCases() map[string][]routeCase {simple("/api/usage/pool", "/api/usage/pool")simple("/api/chat/conversations", "/api/chat/conversations")simple("/api/billing/summary", "/api/billing/summary")+ simple("/api/billing/usage", "/api/billing/usage")simple("/api/billing/setup-session", "/api/billing/setup-session")simple("/api/billing/portal-session", "/api/billing/portal-session")simple("/api/keys", "/api/keys")diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.goindex 433b13a246..5d46e519c9 100644--- a/libs/fleet/backend/auth/policy_routes.go+++ b/libs/fleet/backend/auth/policy_routes.go@@ -286,6 +286,7 @@ var routeSurfaces = map[string]string{"/api/chat/conversations/{id}/turns": "chat","/api/billing/summary": "billing",+ "/api/billing/usage": "billing","/api/billing/setup-session": "billing","/api/billing/portal-session": "billing",diff --git a/libs/fleet/backend/auth/testdata/route-authorization-table.txt b/libs/fleet/backend/auth/testdata/route-authorization-table.txtindex 189ba24bdf..b5ec4f3605 100644--- a/libs/fleet/backend/auth/testdata/route-authorization-table.txt+++ b/libs/fleet/backend/auth/testdata/route-authorization-table.txt@@ -273,6 +273,61 @@/api/billing/summary | plain | QUERY | spa = allow/api/billing/summary | plain | QUERY | user-key = deny/api/billing/summary | plain | QUERY | user-key-verified = deny+/api/billing/usage | plain | DELETE | admin-spa = allow+/api/billing/usage | plain | DELETE | cua-cli = deny+/api/billing/usage | plain | DELETE | dcr-client = deny+/api/billing/usage | plain | DELETE | empty-sub = deny+/api/billing/usage | plain | DELETE | github-oidc = deny+/api/billing/usage | plain | DELETE | oauth2-proxy = deny+/api/billing/usage | plain | DELETE | per-key-other-ns = deny+/api/billing/usage | plain | DELETE | per-key-owned-ns = deny+/api/billing/usage | plain | DELETE | spa = allow+/api/billing/usage | plain | DELETE | user-key = deny+/api/billing/usage | plain | DELETE | user-key-verified = deny+/api/billing/usage | plain | GET | admin-spa = allow+/api/billing/usage | plain | GET | cua-cli = deny+/api/billing/usage | plain | GET | dcr-client = deny+/api/billing/usage | plain | GET | empty-sub = deny+/api/billing/usage | plain | GET | github-oidc = deny+/api/billing/usage | plain | GET | oauth2-proxy = deny+/api/billing/usage | plain | GET | per-key-other-ns = deny+/api/billing/usage | plain | GET | per-key-owned-ns = deny+/api/billing/usage | plain | GET | spa = allow+/api/billing/usage | plain | GET | user-key = deny+/api/billing/usage | plain | GET | user-key-verified = deny+/api/billing/usage | plain | PATCH | admin-spa = allow+/api/billing/usage | plain | PATCH | cua-cli = deny+/api/billing/usage | plain | PATCH | dcr-client = deny+/api/billing/usage | plain | PATCH | empty-sub = deny+/api/billing/usage | plain | PATCH | github-oidc = deny+/api/billing/usage | plain | PATCH | oauth2-proxy = deny+/api/billing/usage | plain | PATCH | per-key-other-ns = deny+/api/billing/usage | plain | PATCH | per-key-owned-ns = deny+/api/billing/usage | plain | PATCH | spa = allow+/api/billing/usage | plain | PATCH | user-key = deny+/api/billing/usage | plain | PATCH | user-key-verified = deny+/api/billing/usage | plain | POST | admin-spa = allow+/api/billing/usage | plain | POST | cua-cli = deny+/api/billing/usage | plain | POST | dcr-client = deny+/api/billing/usage | plain | POST | empty-sub = deny+/api/billing/usage | plain | POST | github-oidc = deny+/api/billing/usage | plain | POST | oauth2-proxy = deny+/api/billing/usage | plain | POST | per-key-other-ns = deny+/api/billing/usage | plain | POST | per-key-owned-ns = deny+/api/billing/usage | plain | POST | spa = allow+/api/billing/usage | plain | POST | user-key = deny+/api/billing/usage | plain | POST | user-key-verified = deny+/api/billing/usage | plain | QUERY | admin-spa = allow+/api/billing/usage | plain | QUERY | cua-cli = deny+/api/billing/usage | plain | QUERY | dcr-client = deny+/api/billing/usage | plain | QUERY | empty-sub = deny+/api/billing/usage | plain | QUERY | github-oidc = deny+/api/billing/usage | plain | QUERY | oauth2-proxy = deny+/api/billing/usage | plain | QUERY | per-key-other-ns = deny+/api/billing/usage | plain | QUERY | per-key-owned-ns = deny+/api/billing/usage | plain | QUERY | spa = allow+/api/billing/usage | plain | QUERY | user-key = deny+/api/billing/usage | plain | QUERY | user-key-verified = deny/api/chat/conversations | plain | DELETE | admin-spa = allow/api/chat/conversations | plain | DELETE | cua-cli = deny/api/chat/conversations | plain | DELETE | dcr-client = denydiff --git a/libs/fleet/backend/billing/service.go b/libs/fleet/backend/billing/service.goindex 1d9f06335c..2a6701c152 100644--- a/libs/fleet/backend/billing/service.go+++ b/libs/fleet/backend/billing/service.go@@ -6,6 +6,9 @@ import ("crypto/sha256""encoding/hex""errors"+ "sort"+ "strings"+ "time")const (@@ -54,6 +57,54 @@ type Gateway interface {SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error)CreateSetupSession(ctx context.Context, request SetupSessionRequest) (string, error)CreatePortalSession(ctx context.Context, request PortalSessionRequest) (string, error)+ PreviewInvoice(ctx context.Context, customerID string) (*Invoice, error)+ ListInvoices(ctx context.Context, customerID string, createdAfter time.Time) ([]Invoice, error)+}++type InvoiceLine struct {+ Description string+ Amount int64+ Quantity int64+ PeriodStart time.Time+ PeriodEnd time.Time+}++type Invoice struct {+ ID string+ Currency string+ Total int64+ Status string+ PeriodStart time.Time+ PeriodEnd time.Time+ Created time.Time+ Lines []InvoiceLine+}++type UsagePoint struct {+ PeriodStart time.Time `json:"period_start"`+ PeriodEnd time.Time `json:"period_end"`+ Amount int64 `json:"amount"`+ Estimate bool `json:"estimate"`+}++type UsageBreakdownItem struct {+ Name string `json:"name"`+ Amount int64 `json:"amount"`+ Quantity int64 `json:"quantity"`+ PeriodStart time.Time `json:"period_start"`+ PeriodEnd time.Time `json:"period_end"`+}++type Usage struct {+ Currency string `json:"currency"`+ RangeStart time.Time `json:"range_start"`+ RangeEnd time.Time `json:"range_end"`+ CurrentPeriodStart *time.Time `json:"current_period_start"`+ CurrentPeriodEnd *time.Time `json:"current_period_end"`+ CurrentEstimate int64 `json:"current_estimate"`+ PreviousPeriodAmount int64 `json:"previous_period_amount"`+ Trend []UsagePoint `json:"trend"`+ Breakdown []UsageBreakdownItem `json:"breakdown"`}type Service struct {@@ -181,6 +232,115 @@ func (s *Service) Summary(ctx context.Context, subject string) (Summary, error)}, nil}+func (s *Service) Usage(ctx context.Context, subject string, months int, now time.Time) (Usage, error) {+ end := now.UTC()+ start := end.AddDate(0, -months, 0)+ empty := Usage{+ Currency: "usd",+ RangeStart: start,+ RangeEnd: end,+ Trend: []UsagePoint{},+ Breakdown: []UsageBreakdownItem{},+ }++ customer, err := s.findCustomerReadOnly(ctx, subject)+ if errors.Is(err, ErrCustomerNotFound) {+ return empty, nil+ }+ if err != nil {+ return Usage{}, err+ }++ invoices, err := s.gateway.ListInvoices(ctx, customer.ID, start)+ if err != nil {+ return Usage{}, err+ }+ preview, err := s.gateway.PreviewInvoice(ctx, customer.ID)+ if err != nil {+ return Usage{}, err+ }++ currency := ""+ if preview != nil {+ currency = preview.Currency+ }+ if currency == "" && len(invoices) > 0 {+ currency = invoices[0].Currency+ }+ if currency == "" {+ currency = empty.Currency+ }++ usage := empty+ usage.Currency = strings.ToLower(currency)+ for _, invoice := range invoices {+ if !strings.EqualFold(invoice.Currency, usage.Currency) || invoice.Status == "draft" || invoice.Status == "void" {+ continue+ }+ usage.Trend = append(usage.Trend, UsagePoint{+ PeriodStart: invoice.PeriodStart,+ PeriodEnd: invoice.PeriodEnd,+ Amount: invoice.Total,+ })+ }+ sort.Slice(usage.Trend, func(i, j int) bool {+ return usage.Trend[i].PeriodStart.Before(usage.Trend[j].PeriodStart)+ })+ if len(usage.Trend) > 0 {+ usage.PreviousPeriodAmount = usage.Trend[len(usage.Trend)-1].Amount+ }++ if preview == nil || !strings.EqualFold(preview.Currency, usage.Currency) {+ return usage, nil+ }+ usage.CurrentPeriodStart = &preview.PeriodStart+ usage.CurrentPeriodEnd = &preview.PeriodEnd+ usage.CurrentEstimate = preview.Total+ usage.Trend = append(usage.Trend, UsagePoint{+ PeriodStart: preview.PeriodStart,+ PeriodEnd: preview.PeriodEnd,+ Amount: preview.Total,+ Estimate: true,+ })++ byName := map[string]UsageBreakdownItem{}+ for _, line := range preview.Lines {+ name := strings.TrimSpace(line.Description)+ if name == "" {+ name = "Usage"+ }+ item := byName[name]+ item.Name = name+ item.Amount += line.Amount+ item.Quantity += line.Quantity+ if item.PeriodStart.IsZero() || line.PeriodStart.Before(item.PeriodStart) {+ item.PeriodStart = line.PeriodStart+ }+ if line.PeriodEnd.After(item.PeriodEnd) {+ item.PeriodEnd = line.PeriodEnd+ }+ byName[name] = item+ }+ for _, item := range byName {+ usage.Breakdown = append(usage.Breakdown, item)+ }+ sort.Slice(usage.Breakdown, func(i, j int) bool {+ left := usage.Breakdown[i].Amount+ if left < 0 {+ left = -left+ }+ right := usage.Breakdown[j].Amount+ if right < 0 {+ right = -right+ }+ if left == right {+ return usage.Breakdown[i].Name < usage.Breakdown[j].Name+ }+ return left > right+ })+ return usage, nil+}+type SetupOptions struct {SuccessURL stringCancelURL stringdiff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.goindex b38cc8fc53..a42b97f92c 100644--- a/libs/fleet/backend/billing/service_test.go+++ b/libs/fleet/backend/billing/service_test.go@@ -7,6 +7,7 @@ import ("reflect""strings""testing"+ "time")type fakeGateway struct {@@ -33,6 +34,12 @@ type fakeGateway struct {defaultApplied boolsetupRequest SetupSessionRequestportalRequest PortalSessionRequest+ previewInvoice *Invoice+ previewErr error+ invoices []Invoice+ invoicesErr error+ invoiceCustomerID string+ invoiceCreatedAfter time.Time}func (f *fakeGateway) SearchCustomers(_ context.Context, subject string) ([]Customer, error) {@@ -91,6 +98,68 @@ func (f *fakeGateway) CreatePortalSession(_ context.Context, request PortalSessireturn "https://billing.stripe.test/session", nil}+func (f *fakeGateway) PreviewInvoice(_ context.Context, customerID string) (*Invoice, error) {+ f.invoiceCustomerID = customerID+ return f.previewInvoice, f.previewErr+}++func (f *fakeGateway) ListInvoices(_ context.Context, customerID string, createdAfter time.Time) ([]Invoice, error) {+ f.invoiceCustomerID = customerID+ f.invoiceCreatedAfter = createdAfter+ return f.invoices, f.invoicesErr+}++func TestUsageAggregatesInvoiceHistoryAndPreviewLines(t *testing.T) {+ now := time.Date(2026, time.August, 22, 12, 0, 0, 0, time.UTC)+ previousStart := time.Date(2026, time.July, 1, 0, 0, 0, 0, time.UTC)+ currentStart := time.Date(2026, time.August, 1, 0, 0, 0, 0, time.UTC)+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ invoices: []Invoice{{+ ID: "in_previous", Currency: "usd", Total: 3200, Status: "paid",+ PeriodStart: previousStart, PeriodEnd: currentStart,+ }},+ previewInvoice: &Invoice{+ ID: "upcoming", Currency: "usd", Total: 2500, Status: "draft",+ PeriodStart: currentStart, PeriodEnd: currentStart.AddDate(0, 1, 0),+ Lines: []InvoiceLine{+ {Description: "Linux runtime", Amount: 1500, Quantity: 20, PeriodStart: currentStart, PeriodEnd: currentStart.AddDate(0, 1, 0)},+ {Description: "Linux runtime", Amount: 500, Quantity: 5, PeriodStart: currentStart, PeriodEnd: currentStart.AddDate(0, 1, 0)},+ {Description: "Storage", Amount: 500, Quantity: 10, PeriodStart: currentStart, PeriodEnd: currentStart.AddDate(0, 1, 0)},+ },+ },+ }++ usage, err := NewService(gateway).Usage(context.Background(), "subject-123", 6, now)+ if err != nil {+ t.Fatalf("Usage() error = %v", err)+ }+ if usage.CurrentEstimate != 2500 || usage.PreviousPeriodAmount != 3200 {+ t.Fatalf("amounts = current %d previous %d", usage.CurrentEstimate, usage.PreviousPeriodAmount)+ }+ if len(usage.Trend) != 2 || !usage.Trend[1].Estimate {+ t.Fatalf("trend = %#v", usage.Trend)+ }+ if len(usage.Breakdown) != 2 || usage.Breakdown[0].Name != "Linux runtime" || usage.Breakdown[0].Amount != 2000 || usage.Breakdown[0].Quantity != 25 {+ t.Fatalf("breakdown = %#v", usage.Breakdown)+ }+ wantStart := now.AddDate(0, -6, 0)+ if !gateway.invoiceCreatedAfter.Equal(wantStart) {+ t.Fatalf("created after = %v, want %v", gateway.invoiceCreatedAfter, wantStart)+ }+}++func TestUsageReturnsEmptyDataWithoutBillingCustomer(t *testing.T) {+ now := time.Date(2026, time.August, 22, 12, 0, 0, 0, time.UTC)+ usage, err := NewService(&fakeGateway{}).Usage(context.Background(), "subject-123", 3, now)+ if err != nil {+ t.Fatalf("Usage() error = %v", err)+ }+ if usage.Currency != "usd" || len(usage.Trend) != 0 || len(usage.Breakdown) != 0 {+ t.Fatalf("usage = %#v", usage)+ }+}+func TestFindOrCreateCustomerUsesExactControlledMetadata(t *testing.T) {gateway := &fakeGateway{customers: []Customer{{diff --git a/libs/fleet/backend/billing/stripe_gateway.go b/libs/fleet/backend/billing/stripe_gateway.goindex b657d6f235..8ecfcd1dcf 100644--- a/libs/fleet/backend/billing/stripe_gateway.go+++ b/libs/fleet/backend/billing/stripe_gateway.go@@ -2,8 +2,10 @@ package billingimport ("context"+ "errors""fmt""strings"+ "time""github.com/stripe/stripe-go/v85")@@ -191,3 +193,78 @@ func (g *StripeGateway) CreatePortalSession(ctx context.Context, request PortalS}return session.URL, nil}++func stripeTime(timestamp int64) time.Time {+ if timestamp == 0 {+ return time.Time{}+ }+ return time.Unix(timestamp, 0).UTC()+}++func invoiceFromStripe(source *stripe.Invoice) Invoice {+ invoice := Invoice{+ ID: source.ID,+ Currency: string(source.Currency),+ Total: source.Total,+ Status: string(source.Status),+ PeriodStart: stripeTime(source.PeriodStart),+ PeriodEnd: stripeTime(source.PeriodEnd),+ Created: stripeTime(source.Created),+ Lines: []InvoiceLine{},+ }+ if source.Lines == nil {+ return invoice+ }+ for _, sourceLine := range source.Lines.Data {+ if sourceLine == nil {+ continue+ }+ line := InvoiceLine{+ Description: sourceLine.Description,+ Amount: sourceLine.Amount,+ Quantity: sourceLine.Quantity,+ }+ if sourceLine.Period != nil {+ line.PeriodStart = stripeTime(sourceLine.Period.Start)+ line.PeriodEnd = stripeTime(sourceLine.Period.End)+ }+ invoice.Lines = append(invoice.Lines, line)+ }+ return invoice+}++func (g *StripeGateway) PreviewInvoice(ctx context.Context, customerID string) (*Invoice, error) {+ invoice, err := g.client.V1Invoices.CreatePreview(ctx, &stripe.InvoiceCreatePreviewParams{+ Customer: stripe.String(customerID),+ })+ if err != nil {+ var stripeErr *stripe.Error+ if errors.As(err, &stripeErr) && stripeErr.Code == stripe.ErrorCodeInvoiceUpcomingNone {+ return nil, nil+ }+ return nil, err+ }+ normalized := invoiceFromStripe(invoice)+ return &normalized, nil+}++func (g *StripeGateway) ListInvoices(ctx context.Context, customerID string, createdAfter time.Time) ([]Invoice, error) {+ params := &stripe.InvoiceListParams{+ ListParams: stripe.ListParams{Limit: stripe.Int64(100)},+ Customer: stripe.String(customerID),+ CreatedRange: &stripe.RangeQueryParams{+ GreaterThanOrEqual: createdAfter.Unix(),+ },+ }+ invoices := make([]Invoice, 0)+ for invoice, err := range g.client.V1Invoices.List(ctx, params).All(ctx) {+ if err != nil {+ return nil, err+ }+ if invoice == nil {+ continue+ }+ invoices = append(invoices, invoiceFromStripe(invoice))+ }+ return invoices, nil+}diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.goindex 228c169480..306cfc41db 100644--- a/libs/fleet/backend/docs/docs.go+++ b/libs/fleet/backend/docs/docs.go@@ -548,6 +548,90 @@ const docTemplate = `{}}},+ "/api/billing/usage": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns Stripe-backed invoice spend, trend, and current-period line-item breakdown for the authenticated Fleet subject.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Billing usage",+ "parameters": [+ {+ "enum": [+ 3,+ 6,+ 12+ ],+ "type": "integer",+ "default": 6,+ "description": "History window in months",+ "name": "months",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/billing.Usage"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },"/api/billing/webhook": {"post": {"description": "Verifies a Stripe-signed raw webhook body and configures the default payment method for completed fleet setup intents.",@@ -1487,6 +1571,81 @@ const docTemplate = `{}}},+ "billing.Usage": {+ "type": "object",+ "properties": {+ "breakdown": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/billing.UsageBreakdownItem"+ }+ },+ "currency": {+ "type": "string"+ },+ "current_estimate": {+ "type": "integer"+ },+ "current_period_end": {+ "type": "string"+ },+ "current_period_start": {+ "type": "string"+ },+ "previous_period_amount": {+ "type": "integer"+ },+ "range_end": {+ "type": "string"+ },+ "range_start": {+ "type": "string"+ },+ "trend": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/billing.UsagePoint"+ }+ }+ }+ },+ "billing.UsageBreakdownItem": {+ "type": "object",+ "properties": {+ "amount": {+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "period_end": {+ "type": "string"+ },+ "period_start": {+ "type": "string"+ },+ "quantity": {+ "type": "integer"+ }+ }+ },+ "billing.UsagePoint": {+ "type": "object",+ "properties": {+ "amount": {+ "type": "integer"+ },+ "estimate": {+ "type": "boolean"+ },+ "period_end": {+ "type": "string"+ },+ "period_start": {+ "type": "string"+ }+ }+ },"chat.Conversation": {"type": "object","properties": {@@ -1695,6 +1854,9 @@ const docTemplate = `{},"chat": {"type": "boolean"+ },+ "usage": {+ "type": "boolean"}}},diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.jsonindex a5f9fa0484..ace231cb3f 100644--- a/libs/fleet/backend/docs/swagger.json+++ b/libs/fleet/backend/docs/swagger.json@@ -541,6 +541,90 @@}}},+ "/api/billing/usage": {+ "get": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Returns Stripe-backed invoice spend, trend, and current-period line-item breakdown for the authenticated Fleet subject.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Billing usage",+ "parameters": [+ {+ "enum": [+ 3,+ 6,+ 12+ ],+ "type": "integer",+ "default": 6,+ "description": "History window in months",+ "name": "months",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/billing.Usage"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },"/api/billing/webhook": {"post": {"description": "Verifies a Stripe-signed raw webhook body and configures the default payment method for completed fleet setup intents.",@@ -1480,6 +1564,81 @@}}},+ "billing.Usage": {+ "type": "object",+ "properties": {+ "breakdown": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/billing.UsageBreakdownItem"+ }+ },+ "currency": {+ "type": "string"+ },+ "current_estimate": {+ "type": "integer"+ },+ "current_period_end": {+ "type": "string"+ },+ "current_period_start": {+ "type": "string"+ },+ "previous_period_amount": {+ "type": "integer"+ },+ "range_end": {+ "type": "string"+ },+ "range_start": {+ "type": "string"+ },+ "trend": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/billing.UsagePoint"+ }+ }+ }+ },+ "billing.UsageBreakdownItem": {+ "type": "object",+ "properties": {+ "amount": {+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "period_end": {+ "type": "string"+ },+ "period_start": {+ "type": "string"+ },+ "quantity": {+ "type": "integer"+ }+ }+ },+ "billing.UsagePoint": {+ "type": "object",+ "properties": {+ "amount": {+ "type": "integer"+ },+ "estimate": {+ "type": "boolean"+ },+ "period_end": {+ "type": "string"+ },+ "period_start": {+ "type": "string"+ }+ }+ },"chat.Conversation": {"type": "object","properties": {@@ -1688,6 +1847,9 @@},"chat": {"type": "boolean"+ },+ "usage": {+ "type": "boolean"}}},diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yamlindex e5833152c7..b87eb60f16 100644--- a/libs/fleet/backend/docs/swagger.yaml+++ b/libs/fleet/backend/docs/swagger.yaml@@ -23,6 +23,55 @@ definitions:- card- payment_method_presenttype: object+ billing.Usage:+ properties:+ breakdown:+ items:+ $ref: '#/definitions/billing.UsageBreakdownItem'+ type: array+ currency:+ type: string+ current_estimate:+ type: integer+ current_period_end:+ type: string+ current_period_start:+ type: string+ previous_period_amount:+ type: integer+ range_end:+ type: string+ range_start:+ type: string+ trend:+ items:+ $ref: '#/definitions/billing.UsagePoint'+ type: array+ type: object+ billing.UsageBreakdownItem:+ properties:+ amount:+ type: integer+ name:+ type: string+ period_end:+ type: string+ period_start:+ type: string+ quantity:+ type: integer+ type: object+ billing.UsagePoint:+ properties:+ amount:+ type: integer+ estimate:+ type: boolean+ period_end:+ type: string+ period_start:+ type: string+ type: objectchat.Conversation:properties:created_at:@@ -169,6 +218,8 @@ definitions:type: booleanchat:type: boolean+ usage:+ type: booleantype: objecthandlers.CreateFeatureFlagRequest:properties:@@ -687,6 +738,62 @@ paths:summary: Billing summarytags:- billing+ /api/billing/usage:+ get:+ description: Returns Stripe-backed invoice spend, trend, and current-period+ line-item breakdown for the authenticated Fleet subject.+ parameters:+ - default: 6+ description: History window in months+ enum:+ - 3+ - 6+ - 12+ in: query+ name: months+ type: integer+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/billing.Usage'+ "400":+ description: Bad Request+ schema:+ additionalProperties:+ type: string+ type: object+ "401":+ description: Unauthorized+ schema:+ additionalProperties:+ type: string+ type: object+ "403":+ description: Forbidden+ schema:+ additionalProperties:+ type: string+ type: object+ "502":+ description: Bad Gateway+ schema:+ additionalProperties:+ type: string+ type: object+ "503":+ description: Service Unavailable+ schema:+ additionalProperties:+ type: string+ type: object+ security:+ - BearerAuth: []+ summary: Billing usage+ tags:+ - billing/api/billing/webhook:post:consumes:diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.goindex c01de7e1c2..0f55bd6c46 100644--- a/libs/fleet/backend/handlers/billing.go+++ b/libs/fleet/backend/handlers/billing.go@@ -6,7 +6,9 @@ import ("io""log/slog""net/http"+ "strconv""strings"+ "time""cyclops-cs-backend/auth""cyclops-cs-backend/billing"@@ -20,6 +22,10 @@ type BillingService interface {SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error)}+type BillingUsageService interface {+ Usage(ctx context.Context, subject string, months int, now time.Time) (billing.Usage, error)+}+type BillingSessionResponse struct {URL string `json:"url"`}@@ -99,6 +105,47 @@ func (h Handlers) GetBillingSummary(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, summary)}+// GetBillingUsage godoc+// @Summary Billing usage+// @Description Returns Stripe-backed invoice spend, trend, and current-period line-item breakdown for the authenticated Fleet subject.+// @Tags billing+// @Produce json+// @Param months query int false "History window in months" Enums(3, 6, 12) default(6)+// @Success 200 {object} billing.Usage+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 502 {object} map[string]string+// @Failure 503 {object} map[string]string+// @Security BearerAuth+// @Router /api/billing/usage [get]+func (h Handlers) GetBillingUsage(w http.ResponseWriter, r *http.Request) {+ user, ok := requireBillingEnabled(w, r)+ if !ok || !h.billingAvailable(w) {+ return+ }+ months := 6+ if raw := r.URL.Query().Get("months"); raw != "" {+ parsed, err := strconv.Atoi(raw)+ if err != nil || (parsed != 3 && parsed != 6 && parsed != 12) {+ writeErr(w, http.StatusBadRequest, "months must be 3, 6, or 12")+ return+ }+ months = parsed+ }+ usageService, ok := h.Billing.(BillingUsageService)+ if !ok {+ writeErr(w, http.StatusServiceUnavailable, "billing usage is not configured")+ return+ }+ usage, err := usageService.Usage(r.Context(), user.ID, months, time.Now())+ if err != nil {+ writeErr(w, http.StatusBadGateway, "could not load billing usage")+ return+ }+ writeJSON(w, http.StatusOK, usage)+}+// CreateBillingSetupSession godoc// @Summary Create Stripe card setup Session// @Description Creates a Stripe-hosted Checkout Session in setup mode for reusable off-session card collection.diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.goindex 1596db3af0..c5456389db 100644--- a/libs/fleet/backend/handlers/billing_test.go+++ b/libs/fleet/backend/handlers/billing_test.go@@ -7,6 +7,7 @@ import ("net/http/httptest""strings""testing"+ "time""cyclops-cs-backend/auth""cyclops-cs-backend/billing"@@ -30,6 +31,10 @@ type fakeBillingService struct {defaultApplied booldefaultCalls intdefaultErr error+ usageMonths int+ usageSubject string+ usageResponse billing.Usage+ usageErr error}func (f *fakeBillingService) AttachedCards(context.Context, string) ([]billing.SavedCard, error) {@@ -64,6 +69,12 @@ func (f *fakeBillingService) CreatePortalSession(_ context.Context, subject, retreturn "https://billing.stripe.test/session", nil}+func (f *fakeBillingService) Usage(_ context.Context, subject string, months int, _ time.Time) (billing.Usage, error) {+ f.usageSubject = subject+ f.usageMonths = months+ return f.usageResponse, f.usageErr+}+var billingAlice = &auth.User{ID: "user-alice"}func newBillingRequest(method, target, body string, user *auth.User) *http.Request {@@ -91,6 +102,38 @@ func setBillingFlag(t *testing.T, enabled bool) {}}+func TestGetBillingUsageUsesValidatedHistoryWindow(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{usageResponse: billing.Usage{Currency: "usd", Trend: []billing.UsagePoint{}, Breakdown: []billing.UsageBreakdownItem{}}}+ h := Handlers{Billing: service, Stripe: config.StripeConfiguration{SecretKey: "sk_test"}}+ w := httptest.NewRecorder()++ h.GetBillingUsage(w, newBillingRequest(http.MethodGet, "/api/billing/usage?months=12", "", billingAlice))++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())+ }+ if service.usageSubject != billingAlice.ID || service.usageMonths != 12 {+ t.Fatalf("usage call = subject %q months %d", service.usageSubject, service.usageMonths)+ }+}++func TestGetBillingUsageRejectsUnsupportedHistoryWindow(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{Billing: service, Stripe: config.StripeConfiguration{SecretKey: "sk_test"}}+ w := httptest.NewRecorder()++ h.GetBillingUsage(w, newBillingRequest(http.MethodGet, "/api/billing/usage?months=9", "", billingAlice))++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())+ }+ if service.usageMonths != 0 {+ t.Fatalf("usage months = %d, want no call", service.usageMonths)+ }+}+func TestBillingSummaryReturns503WithoutStripeConfiguration(t *testing.T) {setBillingFlag(t, true)service := &fakeBillingService{}diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex a7429e2c9b..f52576269d 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -161,6 +161,8 @@ func setupRouter(c handlers.Handlers) http.Handler {// webhook uses Stripe signature verification as its authentication boundary.r.Handle("GET /api/billing/summary",withAuthenticatedMiddlewares("/api/billing/summary", c.GetBillingSummary))+ r.Handle("GET /api/billing/usage",+ withAuthenticatedMiddlewares("/api/billing/usage", c.GetBillingUsage))r.Handle("POST /api/billing/setup-session",withAuthenticatedMiddlewares("/api/billing/setup-session", c.CreateBillingSetupSession))r.Handle("POST /api/billing/portal-session",diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.goindex d7e739e4e6..867f7394d4 100644--- a/libs/fleet/backend/main_test.go+++ b/libs/fleet/backend/main_test.go@@ -203,6 +203,9 @@ func TestSwaggerUsesBillingSetupSessionRoute(t *testing.T) {if _, ok := spec.Paths["/api/billing/setup-session"]; !ok {t.Fatal("swagger.json missing /api/billing/setup-session")}+ if _, ok := spec.Paths["/api/billing/usage"]; !ok {+ t.Fatal("swagger.json missing /api/billing/usage")+ }if _, ok := spec.Paths["/api/billing/checkout-session"]; ok {t.Fatal("swagger.json still contains /api/billing/checkout-session")}@@ -370,6 +373,10 @@ func (routerBillingService) Summary(context.Context, string) (billing.Summary, ereturn billing.Summary{}, nil}+func (routerBillingService) Usage(context.Context, string, int, time.Time) (billing.Usage, error) {+ return billing.Usage{Currency: "usd", Trend: []billing.UsagePoint{}, Breakdown: []billing.UsageBreakdownItem{}}, nil+}+func (routerBillingService) CreateSetupSession(context.Context, string, billing.SetupOptions) (string, error) {return "https://checkout.stripe.test/session", nil}@@ -407,6 +414,18 @@ func TestBillingRouterAuthorizationBoundaries(t *testing.T) {t.Fatalf("authenticated summary status = %d, want 200; body = %s", authorized.Code, authorized.Body.String())}+ unauthorizedUsage := httptest.NewRecorder()+ router.ServeHTTP(unauthorizedUsage, httptest.NewRequest(http.MethodGet, "/api/billing/usage", nil))+ if unauthorizedUsage.Code != http.StatusUnauthorized {+ t.Fatalf("unauthenticated usage status = %d, want 401; body = %s", unauthorizedUsage.Code, unauthorizedUsage.Body.String())+ }++ authorizedUsage := httptest.NewRecorder()+ router.ServeHTTP(authorizedUsage, authorizedRequest(t, http.MethodGet, "/api/billing/usage", nil))+ if authorizedUsage.Code != http.StatusOK {+ t.Fatalf("authenticated usage status = %d, want 200; body = %s", authorizedUsage.Code, authorizedUsage.Body.String())+ }+for _, tc := range []struct {name stringpath stringdiff --git a/libs/fleet/backend/usage/datafusion.go b/libs/fleet/backend/usage/datafusion.goindex b97bebd080..f9e2bc84ef 100644--- a/libs/fleet/backend/usage/datafusion.go+++ b/libs/fleet/backend/usage/datafusion.go@@ -259,7 +259,7 @@ func allocationSQL(namespaces []string) string {for index, namespace := range namespaces {literals[index] = "'" + namespace + "'"}- return "SELECT window_start, window_end, namespace, pod, cpu_usage_core_hours, cpu_request_core_hours, ram_usage_byte_hours, ram_request_byte_hours " ++ return "SELECT window_start, window_end, namespace, pod, cpu_usage_core_hours, cpu_request_core_hours, ram_usage_byte_hours, ram_request_byte_hours, total_cost_usd " +"FROM allocation WHERE namespace IN (" + strings.Join(literals, ",") + ") " +"ORDER BY window_start, namespace, pod LIMIT 100001"}@@ -334,7 +334,7 @@ func parseDataFusionAllocations(contents []byte, requestedStart, requestedEnd tiif err != nil {return nil, time.Time{}, 0, false, newSanitizedError("decode allocation query result", err)}- wantHeader := []string{"window_start", "window_end", "namespace", "pod", "cpu_usage_core_hours", "cpu_request_core_hours", "ram_usage_byte_hours", "ram_request_byte_hours"}+ wantHeader := []string{"window_start", "window_end", "namespace", "pod", "cpu_usage_core_hours", "cpu_request_core_hours", "ram_usage_byte_hours", "ram_request_byte_hours", "total_cost_usd"}if len(header) != len(wantHeader) {return nil, time.Time{}, 0, false, fmt.Errorf("decode allocation query result: unexpected columns")}@@ -366,7 +366,7 @@ func parseDataFusionAllocations(contents []byte, requestedStart, requestedEnd tiif parsedRows > maxDataFusionAllocationRows {return nil, time.Time{}, 0, false, fmt.Errorf("allocation query row limit exceeded")}- if record[3] == "NULL" || record[4] == "NULL" || record[5] == "NULL" || record[6] == "NULL" || record[7] == "NULL" {+ if record[3] == "NULL" || record[4] == "NULL" || record[5] == "NULL" || record[6] == "NULL" || record[7] == "NULL" || record[8] == "NULL" {legacyPartial = truecontinue}@@ -402,7 +402,7 @@ func parseDataFusionAllocation(record []string, requestedStart, requestedEnd timif len(pod) > 253 || !queryPodName.MatchString(pod) {return Allocation{}, fmt.Errorf("invalid pod")}- values := make([]float64, 4)+ values := make([]float64, 5)for index := range values {value, parseErr := strconv.ParseFloat(record[index+4], 64)if parseErr != nil {@@ -424,6 +424,7 @@ func parseDataFusionAllocation(record []string, requestedStart, requestedEnd timCPURequestAverage: values[1] / hours,RAMUsageAverageBytes: values[2] / hours,RAMRequestAverageBytes: values[3] / hours,+ CostUSD: values[4],}, nil}diff --git a/libs/fleet/backend/usage/datafusion_test.go b/libs/fleet/backend/usage/datafusion_test.goindex 4dd1f7ddab..81b7cd6bb7 100644--- a/libs/fleet/backend/usage/datafusion_test.go+++ b/libs/fleet/backend/usage/datafusion_test.go@@ -76,8 +76,8 @@ func TestDataFusionAllocationClientQueriesBoundedParquetAndMapsSemantics(t *teststart := time.Date(2026, 8, 19, 9, 0, 0, 0, time.UTC)store := &fakeQueryObjectStore{status: [][]byte{[]byte(`{"status":"succeeded","rows":1,"partitions_expanded":1,"partitions_matched":1,"partitions_missing":0}`)},- result: []byte("window_start,window_end,namespace,pod,cpu_usage_core_hours,cpu_request_core_hours,ram_usage_byte_hours,ram_request_byte_hours\n" +- "2026-08-19 09:00:00,2026-08-19 10:00:00,ns-a,virt-launcher-vm-a-x,2,4,3221225472,6442450944\n"),+ result: []byte("window_start,window_end,namespace,pod,cpu_usage_core_hours,cpu_request_core_hours,ram_usage_byte_hours,ram_request_byte_hours,total_cost_usd\n" ++ "2026-08-19 09:00:00,2026-08-19 10:00:00,ns-a,virt-launcher-vm-a-x,2,4,3221225472,6442450944,1.25\n"),}client, err := NewDataFusionAllocationClient(server.URL, secret, "results-bucket", "cyclops/usage-query", "kopf-k3s", "production", time.Second, time.Millisecond, 1<<20, store)if err != nil {@@ -88,13 +88,13 @@ func TestDataFusionAllocationClientQueriesBoundedParquetAndMapsSemantics(t *testt.Fatalf("allocations=%#v asOf=%s partial=%t err=%v", allocations, asOf, partial, err)}allocation := allocations[0]- if allocation.Minutes != 60 || allocation.CPUUsageAverage != 2 || allocation.CPURequestAverage != 4 || allocation.RAMUsageAverageBytes != 3*gibibyte || allocation.RAMRequestAverageBytes != 6*gibibyte {+ if allocation.Minutes != 60 || allocation.CPUUsageAverage != 2 || allocation.CPURequestAverage != 4 || allocation.RAMUsageAverageBytes != 3*gibibyte || allocation.RAMRequestAverageBytes != 6*gibibyte || allocation.CostUSD != 1.25 {t.Fatalf("allocation = %#v", allocation)}if payload.Dataset != "allocation" || payload.Cluster != "kopf-k3s" || payload.Environment != "production" || payload.SchemaVersion != "v2" || payload.OutputFormat != "csv" {t.Fatalf("payload = %#v", payload)}- for _, fragment := range []string{"namespace IN ('ns-a','ns-b')", "LIMIT 100001", "cpu_usage_core_hours", "cpu_request_core_hours", "ram_usage_byte_hours", "ram_request_byte_hours"} {+ for _, fragment := range []string{"namespace IN ('ns-a','ns-b')", "LIMIT 100001", "cpu_usage_core_hours", "cpu_request_core_hours", "ram_usage_byte_hours", "ram_request_byte_hours", "total_cost_usd"} {if !strings.Contains(payload.Query, fragment) {t.Fatalf("query %q does not contain %q", payload.Query, fragment)}@@ -180,7 +180,7 @@ func TestDataFusionAllocationClientPreservesCancellationAndMissingPartitions(t *defer server.Close()store := &fakeQueryObjectStore{status: [][]byte{[]byte(`{"status":"succeeded","rows":0,"partitions_expanded":2,"partitions_matched":1,"partitions_missing":1}`)},- result: []byte("window_start,window_end,namespace,pod,cpu_usage_core_hours,cpu_request_core_hours,ram_usage_byte_hours,ram_request_byte_hours\n"),+ result: []byte("window_start,window_end,namespace,pod,cpu_usage_core_hours,cpu_request_core_hours,ram_usage_byte_hours,ram_request_byte_hours,total_cost_usd\n"),}client, err := NewDataFusionAllocationClient(server.URL, "secret", "bucket", "cyclops/usage-query", "kopf-k3s", "production", time.Second, time.Millisecond, 1<<20, store)if err != nil {@@ -208,8 +208,8 @@ func TestDataFusionAllocationClientMarksLegacyParquetRowsPartial(t *testing.T) {defer server.Close()store := &fakeQueryObjectStore{status: [][]byte{[]byte(`{"status":"succeeded","table":"allocation","rows":1,"partitions_expanded":1,"partitions_matched":1,"partitions_missing":0}`)},- result: []byte("window_start,window_end,namespace,pod,cpu_usage_core_hours,cpu_request_core_hours,ram_usage_byte_hours,ram_request_byte_hours\n" +- "2026-08-19T09:00:00Z,2026-08-19T10:00:00Z,ns-a,NULL,NULL,NULL,NULL,NULL\n"),+ result: []byte("window_start,window_end,namespace,pod,cpu_usage_core_hours,cpu_request_core_hours,ram_usage_byte_hours,ram_request_byte_hours,total_cost_usd\n" ++ "2026-08-19T09:00:00Z,2026-08-19T10:00:00Z,ns-a,NULL,NULL,NULL,NULL,NULL,NULL\n"),}client, err := NewDataFusionAllocationClient(server.URL, "secret", "bucket", "cyclops/usage-query", "kopf-k3s", "production", time.Second, time.Millisecond, 1<<20, store)if err != nil {diff --git a/libs/fleet/backend/usage/provider.go b/libs/fleet/backend/usage/provider.goindex 4992d64edc..10460b2fca 100644--- a/libs/fleet/backend/usage/provider.go+++ b/libs/fleet/backend/usage/provider.go@@ -49,7 +49,7 @@ func (p *provider) Overview(ctx context.Context, query Query) (OverviewResponse,}response := OverviewResponse{DataAsOf: data.asOf, Partial: data.partial, Pools: make([]PoolSummary, 0)}for _, pool := range data.pools {- response.Pools = append(response.Pools, PoolSummary{ID: pool.id, Name: pool.name, CPU: MetricTotals{Consumed: pool.cpuConsumed, Provisioned: pool.cpuProvisioned}, Memory: MetricTotals{Consumed: pool.memoryConsumed, Provisioned: pool.memoryProvisioned}})+ response.Pools = append(response.Pools, PoolSummary{ID: pool.id, Name: pool.name, CPU: MetricTotals{Consumed: pool.cpuConsumed, Provisioned: pool.cpuProvisioned}, Memory: MetricTotals{Consumed: pool.memoryConsumed, Provisioned: pool.memoryProvisioned}, CostUSD: pool.costUSD})}return response, nil}@@ -101,6 +101,7 @@ type usageTotals struct {cpuProvisioned float64memoryConsumed float64memoryProvisioned float64+ costUSD float64}type bucketKey struct {@@ -391,7 +392,7 @@ func findPool(pools []usageTotals, id string) (usageTotals, bool) {}func (totals usageTotals) isZero() bool {- return totals.cpuConsumed == 0 && totals.cpuProvisioned == 0 && totals.memoryConsumed == 0 && totals.memoryProvisioned == 0+ return totals.cpuConsumed == 0 && totals.cpuProvisioned == 0 && totals.memoryConsumed == 0 && totals.memoryProvisioned == 0 && totals.costUSD == 0}func disambiguatePoolNames(pools []usageTotals) {@@ -438,6 +439,7 @@ func attributeAllocation(allocation Allocation, segments []liveSegment, windowStcpuProvisioned := allocation.CPURequestAverage * minutes / 60memoryConsumed := allocation.RAMUsageAverageBytes * minutes / 60 / gibibytememoryProvisioned := allocation.RAMRequestAverageBytes * minutes / 60 / gibibyte+ costUSD := allocation.CostUSD * fractionid := match.namespace + ":" + match.poolpool := pools[id]pool.id, pool.name = id, match.pool@@ -445,6 +447,7 @@ func attributeAllocation(allocation Allocation, segments []liveSegment, windowStpool.cpuProvisioned += cpuProvisionedpool.memoryConsumed += memoryConsumedpool.memoryProvisioned += memoryProvisioned+ pool.costUSD += costUSDpools[id] = poolkey := bucketKey{namespace: match.namespace, pool: match.pool, start: bucketStart}bucket := buckets[key]diff --git a/libs/fleet/backend/usage/provider_test.go b/libs/fleet/backend/usage/provider_test.goindex a5af3b7b09..a886ded87c 100644--- a/libs/fleet/backend/usage/provider_test.go+++ b/libs/fleet/backend/usage/provider_test.go@@ -53,7 +53,7 @@ func TestProviderOverviewAggregatesTenantLauncherUsage(t *testing.T) {allocations := &fakeAllocationClient{asOf: cutoff, allocations: []Allocation{{Start: cutoff.Add(-time.Hour), End: cutoff, Namespace: "ns-a", Pod: "virt-launcher-vm-a-abc",Minutes: 60, CPUUsageAverage: 2, CPURequestAverage: 4,- RAMUsageAverageBytes: 3 * gibibyte, RAMRequestAverageBytes: 6 * gibibyte,+ RAMUsageAverageBytes: 3 * gibibyte, RAMRequestAverageBytes: 6 * gibibyte, CostUSD: 1.25,}}}provider := NewProvider(events, allocations, func() time.Time { return cutoff })@@ -71,7 +71,7 @@ func TestProviderOverviewAggregatesTenantLauncherUsage(t *testing.T) {t.Fatalf("overview = %#v", got)}pool := got.Pools[0]- if pool.ID != "ns-a:pool-a" || pool.Name != "pool-a" || pool.CPU.Consumed != 2 || pool.CPU.Provisioned != 4 || pool.Memory.Consumed != 3 || pool.Memory.Provisioned != 6 {+ if pool.ID != "ns-a:pool-a" || pool.Name != "pool-a" || pool.CPU.Consumed != 2 || pool.CPU.Provisioned != 4 || pool.Memory.Consumed != 3 || pool.Memory.Provisioned != 6 || pool.CostUSD != 1.25 {t.Fatalf("pool = %#v", pool)}}@@ -169,9 +169,9 @@ func TestProviderMarksPartiallyUncoveredAllocationPartial(t *testing.T) {t.Parallel()cutoff := time.Date(2026, 8, 19, 10, 0, 0, 0, time.UTC)event := SandboxEvent{EventID: mustUUID("00000000-0000-0000-0000-000000000040"), Namespace: "ns-a", SandboxName: "sandbox", SandboxUID: "uid", PoolName: "pool-a", Runtime: "kubevirt", VMName: "vm", EventType: "Added", ObservedAt: cutoff.Add(-30 * time.Minute)}- allocation := Allocation{Start: cutoff.Add(-time.Hour), End: cutoff, Namespace: "ns-a", Pod: "virt-launcher-vm-a", Minutes: 60, CPUUsageAverage: 1, CPURequestAverage: 1, RAMUsageAverageBytes: gibibyte, RAMRequestAverageBytes: gibibyte}+ allocation := Allocation{Start: cutoff.Add(-time.Hour), End: cutoff, Namespace: "ns-a", Pod: "virt-launcher-vm-a", Minutes: 60, CPUUsageAverage: 1, CPURequestAverage: 1, RAMUsageAverageBytes: gibibyte, RAMRequestAverageBytes: gibibyte, CostUSD: 2}got, err := NewProvider(&fakeEventStore{events: []SandboxEvent{event}}, &fakeAllocationClient{asOf: cutoff, allocations: []Allocation{allocation}}, func() time.Time { return cutoff }).Overview(context.Background(), Query{Subject: "alice", Timeframe: Timeframe24H})- if err != nil || !got.Partial || len(got.Pools) != 1 || got.Pools[0].CPU.Consumed != 0.5 {+ if err != nil || !got.Partial || len(got.Pools) != 1 || got.Pools[0].CPU.Consumed != 0.5 || got.Pools[0].CostUSD != 1 {t.Fatalf("overview=%#v err=%v", got, err)}}diff --git a/libs/fleet/backend/usage/types.go b/libs/fleet/backend/usage/types.goindex 48f95630a4..d8bd0464fe 100644--- a/libs/fleet/backend/usage/types.go+++ b/libs/fleet/backend/usage/types.go@@ -38,10 +38,11 @@ type MetricTotals struct {}type PoolSummary struct {- ID string `json:"id"`- Name string `json:"name"`- CPU MetricTotals `json:"cpu"`- Memory MetricTotals `json:"memory"`+ ID string `json:"id"`+ Name string `json:"name"`+ CPU MetricTotals `json:"cpu"`+ Memory MetricTotals `json:"memory"`+ CostUSD float64 `json:"cost_usd"`}type OverviewResponse struct {@@ -103,6 +104,7 @@ type Allocation struct {CPURequestAverage float64RAMUsageAverageBytes float64RAMRequestAverageBytes float64+ CostUSD float64}type AllocationClient interface {diff --git a/libs/fleet/docs/screenshots/usage-page-desktop.png b/libs/fleet/docs/screenshots/usage-page-desktop.pngnew file mode 100644index 0000000000..05bc42a2f1Binary files /dev/null and b/libs/fleet/docs/screenshots/usage-page-desktop.png differdiff --git a/libs/fleet/docs/screenshots/usage-page-mobile.png b/libs/fleet/docs/screenshots/usage-page-mobile.pngnew file mode 100644index 0000000000..9c8a2b07e2Binary files /dev/null and b/libs/fleet/docs/screenshots/usage-page-mobile.png differdiff --git a/libs/fleet/e2e/billing.spec.ts b/libs/fleet/e2e/billing.spec.tsindex e65db0db71..a78cca421f 100644--- a/libs/fleet/e2e/billing.spec.ts+++ b/libs/fleet/e2e/billing.spec.ts@@ -15,32 +15,85 @@ test.beforeEach(async ({ page }) => {await mockAuth(page);});-test("billing has no navigation link even when the flag is on", async ({+const usageOverview = {+ data_as_of: "2026-08-22T12:00:00Z",+ partial: false,+ pools: [+ {+ id: "preview:prod-web-fleet",+ name: "prod-web-fleet",+ cpu: { consumed: 120.5, provisioned: 240 },+ memory: { consumed: 480, provisioned: 960 },+ cost_usd: 2.75,+ },+ {+ id: "preview:batch-jobs-fleet",+ name: "batch-jobs-fleet",+ cpu: { consumed: 60, provisioned: 90 },+ memory: { consumed: 220, provisioned: 330 },+ cost_usd: 0.89,+ },+ ],+};++async function mockResourceUsage(page: Page) {+ await page.route("**/api/usage/overview**", (route) =>+ route.fulfill({ json: usageOverview }),+ );+}++test("usage appears in navigation when billing is enabled", async ({page,}) => {await setBillingFlag(page, true);- await page.route("**/api/billing/summary", (route) =>- route.fulfill({- contentType: "application/json",- body: JSON.stringify({ payment_method_present: false, card: null }),- }),- );await page.goto("/pools");await expect(page.getByRole("link", { name: "User API keys" })).toBeVisible();- await expect(page.getByRole("link", { name: "Billing" })).toHaveCount(0);+ await expect(page.getByRole("link", { name: "Usage", exact: true })).toBeVisible();});-test("the old /billing route redirects to settings", async ({ page }) => {+test("usage shows pool costs in a two-column table", async ({ page }) => {await setBillingFlag(page, true);- await page.route("**/api/billing/summary", (route) =>+ await mockResourceUsage(page);+ await page.goto("/usage");+ await expect(page.getByRole("button", { name: "Usage history range Last 24 hours" })).toBeVisible();+ await expect(page.getByText("Cost incurred", { exact: true }).first()).toBeVisible();+ const summary = page.getByLabel("Usage summary");+ await expect(summary.getByText("$3.64")).toBeVisible();+ await expect(summary.getByText("Timeframe", { exact: true })).toHaveCount(0);+ await expect(summary.getByText("Data status", { exact: true })).toHaveCount(0);+ await expect(page.getByRole("columnheader")).toHaveCount(2);+ await expect(page.getByRole("cell", { name: "prod-web-fleet" })).toBeVisible();+ await expect(page.getByRole("cell", { name: "$2.75" })).toBeVisible();+ await expect(page.locator(".usage-trend")).toHaveCount(0);+});++test("visual preview shows resource usage without authentication", async ({ page }) => {+ await page.goto("/usage?cua-visual-preview");+ await expect(page.getByLabel("Usage summary").getByText("$37.47")).toBeVisible();+ await expect(page.getByRole("button", { name: "Usage history range Last 24 hours" })).toBeVisible();+ await expect(page.getByRole("cell", { name: "browser-agent-fleet" })).toBeVisible();+});++test("usage has a useful empty state", async ({ page }) => {+ await setBillingFlag(page, true);+ await page.route("**/api/usage/overview**", (route) =>route.fulfill({- contentType: "application/json",- body: JSON.stringify({ payment_method_present: false, card: null }),+ json: { data_as_of: usageOverview.data_as_of, partial: false, pools: [] },}),);- await page.goto("/billing");- await expect(page.getByRole("heading", { name: "Account" })).toBeVisible();- await expect(page).toHaveURL(/\/settings$/);+ await page.goto("/usage");+ await expect(page.getByText("No resource usage yet")).toBeVisible();+ await expect(page.getByText(/pools begin reporting resource activity/i)).toBeVisible();+});++test("usage can retry a failed load", async ({ page }) => {+ await setBillingFlag(page, true);+ await page.route("**/api/usage/overview**", (route) =>+ route.fulfill({ status: 502, json: { error: "unavailable" } }),+ );+ await page.goto("/usage");+ await expect(page.getByText("Usage is temporarily unavailable")).toBeVisible();+ await expect(page.getByRole("button", { name: "Try again" })).toBeVisible();});test("settings hides billing when the flag is off", async ({ page }) => {diff --git a/libs/fleet/e2e/usage.spec.ts b/libs/fleet/e2e/usage.spec.tsdeleted file mode 100644index 11497baf35..0000000000--- a/libs/fleet/e2e/usage.spec.ts+++ /dev/null@@ -1,116 +0,0 @@-import { expect, test, type Page } from "@playwright/test"-import { mockAuth, type MockFeatureFlags } from "./fixtures/mock-api"-import { expectSharedPageShell } from "./fixtures/shell-geometry"-const overview = {- data_as_of: "2026-08-13T10:00:00Z",- partial: true,- pools: [- {- id: "ns-a:pool-a",- name: "Pool A",- cpu: { consumed: 12, provisioned: 24 },- memory: { consumed: 48, provisioned: 96 },- },- {- id: "ns-b:pool-b",- name: "Pool B",- cpu: { consumed: 6, provisioned: 12 },- memory: { consumed: 20, provisioned: 40 },- },- ],-}-const detail = {- data_as_of: "2026-08-13T10:00:00Z",- partial: false,- pool: { id: "ns-b:pool-b", name: "Pool B" },- buckets: [- {- start: "2026-08-13T08:00:00Z",- end: "2026-08-13T09:00:00Z",- cpu_consumed: 0.5,- cpu_provisioned: 1,- memory_consumed: 2,- memory_provisioned: 4,- },- ],-}-async function mockUsage(- p: Page,- flags: MockFeatureFlags = { admin: false, usage: true },-) {- await mockAuth(p, flags)- await p.route("**/api/usage/overview**", (r) => r.fulfill({ json: overview }))- await p.route("**/api/usage/pool**", (r) => r.fulfill({ json: detail }))-}-test("usage navigation is feature flagged", async ({ page }) => {- await mockUsage(page, { admin: false, usage: false })- await page.goto("/pools")- await expect(page.getByRole("link", { name: "Usage" })).toHaveCount(0)- await page.goto("/usage")- await expect(page).toHaveURL(/\/pools$/)-})-test("renders usage totals and forwards opaque pool IDs to drilldown", async ({- page,-}) => {- await mockUsage(page)- await page.goto("/usage")- await expect(page).toHaveTitle("Usage · Cua")- await expectSharedPageShell(page)- await expect(page.getByText("Admin", { exact: true })).toBeVisible()- await expect(- page.getByRole("heading", { name: "Usage preview" }),- ).toBeVisible()- await expect(- page.getByText("Pool A: 12 consumed, 24 provisioned, 50% utilization"),- ).toBeVisible()- await expect(- page.getByText(- "Consumed values use measured usage; provisioned values use Kubernetes requests observed by OpenCost, grouped by pool for the selected timeframe.",- ),- ).toBeVisible()- await page.getByRole("button", { name: "Memory" }).click()- await page.getByLabel("Pool drilldown").click()- const poolRequest = page.waitForRequest((request) => {- const url = new URL(request.url())- return (- url.pathname === "/api/usage/pool" &&- url.searchParams.get("pool") === "ns-b:pool-b"- )- })- await page.getByRole("option", { name: "Pool B" }).click()- expect((await poolRequest).url()).toContain("pool=ns-b%3Apool-b")- await expect(- page.getByRole("heading", { name: "CPU core-hours per bucket" }),- ).toBeVisible()- await expect(- page.getByRole("heading", { name: "Memory GiB-hours per bucket" }),- ).toBeVisible()-})-test("admin view-as persists", async ({ page }) => {- await mockUsage(page, { admin: true, usage: true })- await page.goto("/usage")- await page.getByLabel("View usage for subject").fill("customer")- await page.getByRole("button", { name: "View usage" }).click()- await expect(page).toHaveURL(/subject=customer/)- await expect(page.getByText("Viewing usage for customer")).toBeVisible()-})-test("shows loading empty error and stale states", async ({ page }) => {- await mockAuth(page, { admin: false, usage: true })- let releaseOverview!: () => void- const overviewBlocked = new Promise<void>((resolve) => {- releaseOverview = resolve- })- await page.route("**/api/usage/overview**", async (r) => {- await overviewBlocked- await r.fulfill({- json: { data_as_of: "2026-08-10T00:00:00Z", partial: false, pools: [] },- })- })- await page.goto("/usage")- await expect(page.getByText("Loading usage data")).toBeVisible()- releaseOverview()- await expect(- page.getByText("No usage data is available for this timeframe."),- ).toBeVisible()- await expect(page.getByText("Usage data may be stale")).toBeVisible()-})diff --git a/libs/fleet/src/App.tsx b/libs/fleet/src/App.tsxindex 3c21a403f4..eed4c3db30 100644--- a/libs/fleet/src/App.tsx+++ b/libs/fleet/src/App.tsx@@ -23,7 +23,7 @@ import { PoolNew } from "./pages/PoolNew"import { UserApiKeys } from "./pages/UserApiKeys"import { Settings } from "./pages/Settings"import { AgentChat } from "./pages/AgentChat"-import { Usage } from "./pages/Usage"+import { BillingUsagePage } from "./pages/BillingUsage"import { PageShell } from "./components/PageShell"import { FeatureFlags } from "./pages/FeatureFlags"import { FeatureFlagProvider, useFeatureFlags } from "./components/FeatureFlagContext"@@ -112,7 +112,7 @@ function Shell() {setNavigationOpen(tabletOrWider)}, [tabletOrWider])const user = userInfo()- const { admin, chat, usage } = useFeatureFlags()+ const { admin, billing, chat } = useFeatureFlags()useEffect(() => {const path = location.pathnameconst pageTitle = path === "/usage"@@ -200,7 +200,11 @@ function Shell() {}}items={[{ type: "link", text: "Pools", href: "#/pools" },- ...(usage++ ...(chat+ ? [{ type: "link" as const, text: "Chat", href: "#/agent" }]+ : []),+ ...(billing? [{type: "link" as const,@@ -210,9 +214,6 @@ function Shell() {},]: []),- ...(chat- ? [{ type: "link" as const, text: "Chat", href: "#/agent" }]- : []),{ type: "link", text: "User API keys", href: "#/user-keys" },{ type: "link", text: "Settings", href: "#/settings" },...(admin@@ -278,9 +279,8 @@ export function App() {<Route path="/pools/:namespace/:name" element={<PoolDetail />} /><Route path="/user-keys" element={<UserApiKeys />} /><Route path="/settings" element={<Settings />} />- <Route path="/usage" element={<UsageRoute />} />+ <Route path="/usage" element={<BillingUsageRoute />} /><Route path="/agent" element={<ChatRoute />} />- <Route path="/billing" element={<Navigate to="/settings" replace />} /><Route element={<AdminRoute />}><Route path="/admin/feature-flags" element={<FeatureFlags />} /></Route>@@ -320,14 +320,14 @@ function ChatRoute() {return chat ? <AgentChat /> : <Navigate to="/pools" replace />}-function UsageRoute() {- const { usage, resolved } = useFeatureFlags()+function BillingUsageRoute() {+ const { billing, resolved } = useFeatureFlags()if (!resolved) {return (- <PageShell eyebrow="Resources" title="Usage preview">- <div />+ <PageShell eyebrow="Billing" title="Usage">+ <div className="usage-layout" /></PageShell>)}- return usage ? <Usage /> : <Navigate to="/pools" replace />+ return billing ? <BillingUsagePage /> : <Navigate to="/settings" replace />}diff --git a/libs/fleet/src/local-visual-preview.ts b/libs/fleet/src/local-visual-preview.tsindex 8594c1e5dc..d7d6d4e654 100644--- a/libs/fleet/src/local-visual-preview.ts+++ b/libs/fleet/src/local-visual-preview.ts@@ -1,4 +1,9 @@import type { PoolData, PoolSummary } from "./sdk/models"+import type {+ BillingUsage,+ UsagePoint,+ UsageRangeMonths,+} from "./sdk/billing"import type {ChatMessage,Conversation,@@ -207,3 +212,54 @@ export async function streamLocalVisualPreviewTurn(conversation.updated_at = timestampreturn assistant}+++export async function getLocalVisualPreviewBillingUsage(+ months: UsageRangeMonths,+): Promise<BillingUsage> {+ const state = new URLSearchParams(window.location.search).get(+ "cua-preview-state",+ )+ if (state === "error") throw new Error("Preview usage is unavailable")+ if (state === "loading") {+ await new Promise(resolve => window.setTimeout(resolve, 2_000))+ }+ if (state === "empty") {+ return {+ currency: "usd",+ range_start: "2026-02-01T00:00:00Z",+ range_end: "2026-08-22T00:00:00Z",+ current_period_start: null,+ current_period_end: null,+ current_estimate: 0,+ previous_period_amount: 0,+ trend: [],+ breakdown: [],+ }+ }++ const allTrend: UsagePoint[] = [+ { period_start: "2026-03-01T00:00:00Z", period_end: "2026-04-01T00:00:00Z", amount: 18420, estimate: false },+ { period_start: "2026-04-01T00:00:00Z", period_end: "2026-05-01T00:00:00Z", amount: 22780, estimate: false },+ { period_start: "2026-05-01T00:00:00Z", period_end: "2026-06-01T00:00:00Z", amount: 21410, estimate: false },+ { period_start: "2026-06-01T00:00:00Z", period_end: "2026-07-01T00:00:00Z", amount: 28640, estimate: false },+ { period_start: "2026-07-01T00:00:00Z", period_end: "2026-08-01T00:00:00Z", amount: 31920, estimate: false },+ { period_start: "2026-08-01T00:00:00Z", period_end: "2026-09-01T00:00:00Z", amount: 24680, estimate: true },+ ]+ return {+ currency: "usd",+ range_start: "2026-02-22T00:00:00Z",+ range_end: "2026-08-22T00:00:00Z",+ current_period_start: "2026-08-01T00:00:00Z",+ current_period_end: "2026-09-01T00:00:00Z",+ current_estimate: 24680,+ previous_period_amount: 31920,+ trend: allTrend.slice(-months),+ breakdown: [+ { name: "Linux desktop runtime", amount: 13240, quantity: 368, period_start: "2026-08-01T00:00:00Z", period_end: "2026-09-01T00:00:00Z" },+ { name: "Windows desktop runtime", amount: 6860, quantity: 98, period_start: "2026-08-01T00:00:00Z", period_end: "2026-09-01T00:00:00Z" },+ { name: "Android emulator runtime", amount: 3890, quantity: 81, period_start: "2026-08-01T00:00:00Z", period_end: "2026-09-01T00:00:00Z" },+ { name: "Persistent storage", amount: 690, quantity: 230, period_start: "2026-08-01T00:00:00Z", period_end: "2026-09-01T00:00:00Z" },+ ],+ }+}diff --git a/libs/fleet/src/pages/BillingUsage.css b/libs/fleet/src/pages/BillingUsage.cssnew file mode 100644index 0000000000..f2056a59e2--- /dev/null+++ b/libs/fleet/src/pages/BillingUsage.css@@ -0,0 +1,210 @@+.usage-layout {+ display: grid;+ gap: 20px;+}++.usage-summary {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ border-block: 1px solid var(--cua-color-border-subtle, rgba(255, 255, 255, 0.14));+}++.usage-summary__metric {+ display: grid;+ grid-column: 3;+ gap: 5px;+ min-width: 0;+ padding: 22px 0 22px 24px;+ border-inline-start: 1px solid var(--cua-color-border-subtle, rgba(255, 255, 255, 0.14));+}++.usage-summary__label,+.usage-panel__eyebrow,+.usage-breakdown__header {+ color: var(--cua-color-text-muted, rgba(224, 230, 238, 0.68));+ font-family: var(--cua-dashboard-font-mono, monospace);+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+}++.usage-summary__metric strong {+ color: var(--cua-dashboard-text, #f6f8fb);+ font-family: var(--cua-dashboard-font-display, Georgia, serif);+ font-size: clamp(28px, 4vw, 43px);+ font-weight: 400;+ font-variant-numeric: tabular-nums;+ letter-spacing: -0.035em;+ line-height: 1;+}++.usage-summary__metric > span:last-child {+ color: var(--cua-color-text-muted, rgba(224, 230, 238, 0.68));+ font-size: 13px;+}++.usage-panel {+ min-width: 0;+ padding: 22px 24px 18px;+ overflow: hidden;+ border: 1px solid var(--cua-color-border-subtle, rgba(255, 255, 255, 0.14));+ border-radius: var(--cua-radius-container, 12px);+ background:+ linear-gradient(145deg, rgba(255, 255, 255, 0.035), transparent 45%),+ var(--cua-color-surface-raised, #181818);+}++.usage-panel__heading {+ margin-block-end: 20px;+}++.usage-panel__heading h2,+.usage-panel__heading p {+ margin: 0;+}++.usage-panel__heading h2 {+ margin-block-start: 5px;+ color: var(--cua-dashboard-text, #f6f8fb);+ font-size: 19px;+ font-weight: 600;+ letter-spacing: -0.01em;+}++.usage-breakdown {+ display: block;+ min-width: 0;+ width: 100%;+ border-collapse: collapse;+}++.usage-breakdown thead,+.usage-breakdown tbody {+ display: block;+}++.usage-breakdown__header,+.usage-breakdown__row {+ display: grid;+ grid-template-columns: minmax(220px, 1fr) minmax(120px, auto);+ gap: 24px;+ align-items: center;+}++.usage-breakdown__header {+ padding: 0 12px 9px;+ border-block-end: 1px solid rgba(255, 255, 255, 0.18);+}++.usage-breakdown__header th {+ padding: 0;+ font: inherit;+ text-align: start;+}++.usage-breakdown__header th:last-child,+.usage-breakdown__row > :last-child {+ text-align: end;+}++.usage-breakdown__row {+ min-height: 58px;+ padding: 10px 12px;+ border-block-end: 1px solid rgba(255, 255, 255, 0.08);+ color: var(--cua-color-text-body, #f6f8fb);+ font-size: 14px;+}++.usage-breakdown__row:last-child {+ border-block-end: 0;+}++.usage-breakdown__row strong {+ font-variant-numeric: tabular-nums;+}++.usage-empty {+ padding: 48px 0;+ border-block: 1px solid var(--cua-color-border-subtle, rgba(255, 255, 255, 0.14));+}++.usage-skeleton {+ display: grid;+ gap: 20px;+}++.usage-skeleton__summary {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 1px;+ overflow: hidden;+ background: rgba(255, 255, 255, 0.12);+}++.usage-skeleton__block,+.usage-skeleton__row {+ background:+ linear-gradient(100deg, transparent 30%, rgba(255, 255, 255, 0.07) 48%, transparent 66%) 0 0 / 250% 100%,+ var(--cua-color-surface-raised, #181818);+ animation: usage-skeleton-shift 1.6s ease-in-out infinite;+}++.usage-skeleton__block {+ grid-column: 3;+ height: 112px;+}++.usage-skeleton__rows {+ display: grid;+ gap: 1px;+ overflow: hidden;+ border: 1px solid var(--cua-color-border-subtle, rgba(255, 255, 255, 0.14));+ border-radius: var(--cua-radius-container, 12px);+ background: rgba(255, 255, 255, 0.08);+}++.usage-skeleton__row {+ height: 58px;+}++@keyframes usage-skeleton-shift {+ to { background-position: -180% 0; }+}++@media (max-width: 760px) {+ .usage-summary {+ grid-template-columns: 1fr;+ }++ .usage-summary__metric {+ grid-column: 1;+ padding: 18px 0;+ border-inline-start: 0;+ }++ .usage-panel {+ padding: 18px 14px 12px;+ }++ .usage-breakdown__header,+ .usage-breakdown__row {+ grid-template-columns: minmax(0, 1fr) auto;+ padding-inline: 0;+ }++ .usage-skeleton__summary {+ grid-template-columns: 1fr;+ }++ .usage-skeleton__block {+ grid-column: 1;+ }+}++@media (prefers-reduced-motion: reduce) {+ .usage-skeleton__block,+ .usage-skeleton__row {+ animation: none;+ }+}diff --git a/libs/fleet/src/pages/BillingUsage.tsx b/libs/fleet/src/pages/BillingUsage.tsxnew file mode 100644index 0000000000..678ab069ce--- /dev/null+++ b/libs/fleet/src/pages/BillingUsage.tsx@@ -0,0 +1,135 @@+import Select from "@cloudscape-design/components/select"+import { useCallback, useEffect, useMemo, useState } from "react"+import { CuaButton } from "../components/CuaButton"+import { PageEmpty, PageError } from "../components/PageState"+import { PageShell } from "../components/PageShell"+import {+ usageApi,+ type UsageOverviewResponse,+ type UsageTimeframe,+} from "../sdk/usage"+import "./BillingUsage.css"++const rangeOptions = [+ { label: "Last 24 hours", value: "24h" },+ { label: "Last 7 days", value: "7d" },+ { label: "Last 30 days", value: "30d" },+]++const moneyFormatter = new Intl.NumberFormat(undefined, {+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+})+function UsageSkeleton() {+ return (+ <div className="usage-skeleton" role="status" aria-label="Loading usage">+ <div className="usage-skeleton__summary" aria-hidden="true">+ <div className="usage-skeleton__block" />+ </div>+ <div className="usage-skeleton__rows" aria-hidden="true">+ {Array.from({ length: 4 }, (_, index) => (+ <div className="usage-skeleton__row" key={index} />+ ))}+ </div>+ </div>+ )+}++export function BillingUsagePage() {+ const [timeframe, setTimeframe] = useState<UsageTimeframe>("24h")+ const [overview, setOverview] = useState<UsageOverviewResponse | null>(null)+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState(false)++ const load = useCallback(async () => {+ setLoading(true)+ setError(false)+ try {+ setOverview(await usageApi.overview(timeframe))+ } catch {+ setOverview(null)+ setError(true)+ } finally {+ setLoading(false)+ }+ }, [timeframe])++ useEffect(() => {+ load()+ }, [load])++ const pools = useMemo(+ () => [...(overview?.pools ?? [])].sort((left, right) => right.cost_usd - left.cost_usd),+ [overview],+ )+ const totalCost = useMemo(+ () => pools.reduce((total, pool) => total + pool.cost_usd, 0),+ [pools],+ )++ return (+ <PageShell+ eyebrow="Billing"+ title="Usage"+ description="See OpenCost allocation spend by pool for the selected timeframe."+ actions={+ <Select+ ariaLabel="Usage history range"+ selectedOption={rangeOptions.find(option => option.value === timeframe) ?? rangeOptions[0]}+ onChange={({ detail }) => setTimeframe(detail.selectedOption.value as UsageTimeframe)}+ options={rangeOptions}+ />+ }+ >+ {loading ? <UsageSkeleton /> : error ? (+ <PageError title="Usage is temporarily unavailable" action={<CuaButton tone="secondary" onClick={load}>Try again</CuaButton>}>+ We could not load resource cost data. Try again in a moment.+ </PageError>+ ) : !overview || pools.length === 0 ? (+ <div className="usage-empty">+ <PageEmpty title="No resource usage yet">+ Costs appear here after pools begin reporting resource activity.+ </PageEmpty>+ </div>+ ) : (+ <div className="usage-layout">+ <section className="usage-summary" aria-label="Usage summary">+ <div className="usage-summary__metric">+ <span className="usage-summary__label">Cost incurred</span>+ <strong>{moneyFormatter.format(totalCost)}</strong>+ <span>Across {pools.length} {pools.length === 1 ? "pool" : "pools"}</span>+ </div>+ </section>++ <section className="usage-panel" aria-labelledby="usage-breakdown-title">+ <div className="usage-panel__heading">+ <div>+ <p className="usage-panel__eyebrow">Breakdown</p>+ <h2 id="usage-breakdown-title">Cost by pool</h2>+ </div>+ </div>+ <table className="usage-breakdown">+ <caption className="cua-visually-hidden">Resource cost by pool</caption>+ <thead>+ <tr className="usage-breakdown__header">+ <th scope="col">Pool name</th>+ <th scope="col">Cost incurred</th>+ </tr>+ </thead>+ <tbody>+ {pools.map(pool => (+ <tr className="usage-breakdown__row" key={pool.id}>+ <td>{pool.name}</td>+ <td><strong>{moneyFormatter.format(pool.cost_usd)}</strong></td>+ </tr>+ ))}+ </tbody>+ </table>+ </section>+ </div>+ )}+ </PageShell>+ )+}diff --git a/libs/fleet/src/pages/Usage.tsx b/libs/fleet/src/pages/Usage.tsxdeleted file mode 100644index be14c0b2ef..0000000000--- a/libs/fleet/src/pages/Usage.tsx+++ /dev/null@@ -1,352 +0,0 @@-import Alert from "@cloudscape-design/components/alert"-import BarChart from "@cloudscape-design/components/bar-chart"-import Box from "@cloudscape-design/components/box"-import Button from "@cloudscape-design/components/button"-import Container from "@cloudscape-design/components/container"-import FormField from "@cloudscape-design/components/form-field"-import Header from "@cloudscape-design/components/header"-import Input from "@cloudscape-design/components/input"-import LineChart from "@cloudscape-design/components/line-chart"-import SegmentedControl from "@cloudscape-design/components/segmented-control"-import Select from "@cloudscape-design/components/select"-import SpaceBetween from "@cloudscape-design/components/space-between"-import Spinner from "@cloudscape-design/components/spinner"-import StatusIndicator from "@cloudscape-design/components/status-indicator"-import { useEffect, useMemo, useState } from "react"-import { useSearchParams } from "react-router-dom"-import { useFeatureFlags } from "../components/FeatureFlagContext"-import { PageShell } from "../components/PageShell"-import {- usageApi,- type UsageOverviewResponse,- type UsagePoolDetailResponse,- type UsageTimeframe,-} from "../sdk/usage"-type Metric = "cpu" | "memory"-const opts = [- { id: "24h", text: "24 hours" },- { id: "7d", text: "7 days" },- { id: "30d", text: "30 days" },-]-const i18n = {- filterLabel: "Filter displayed data",- filterPlaceholder: "Filter data",- filterSelectedAriaLabel: "selected",- detailPopoverDismissAriaLabel: "Dismiss",- legendAriaLabel: "Legend",- chartAriaRoleDescription: "chart",-}-const util = (c: number, p: number) => (p > 0 ? Math.round((c / p) * 100) : 0)-const stale = (d: string, t: UsageTimeframe) =>- Date.now() - new Date(d).getTime() > (t === "24h" ? 3 : 30) * 3600000-export function Usage() {- const { admin } = useFeatureFlags()- const [sp, setSp] = useSearchParams()- const raw = sp.get("timeframe")- const timeframe: UsageTimeframe = raw === "7d" || raw === "30d" ? raw : "24h"- const subject = sp.get("subject") ?? ""- const [input, setInput] = useState(subject)- const [metric, setMetric] = useState<Metric>("cpu")- const [overview, setOverview] = useState<UsageOverviewResponse | null>(null)- const [detail, setDetail] = useState<UsagePoolDetailResponse | null>(null)- const [pool, setPool] = useState<string | null>(null)- const [loading, setLoading] = useState(true)- const [detailLoading, setDetailLoading] = useState(false)- const [error, setError] = useState<string | null>(null)- useEffect(() => {- let active = true- setLoading(true)- setError(null)- usageApi- .overview(timeframe, subject || undefined)- .then((v) => {- if (active) {- setOverview(v)- setPool((p) =>- v.pools.some((x) => x.id === p) ? p : (v.pools[0]?.id ?? null),- )- }- })- .catch((e) => {- if (active) {- setOverview(null)- setPool(null)- setError(e instanceof Error ? e.message : "Usage data is unavailable")- }- })- .finally(() => {- if (active) setLoading(false)- })- return () => {- active = false- }- }, [timeframe, subject])- useEffect(() => {- if (!pool) {- setDetail(null)- return- }- let active = true- setDetailLoading(true)- usageApi- .pool(timeframe, pool, subject || undefined)- .then((v) => {- if (active) setDetail(v)- })- .catch((e) => {- if (active)- setError(e instanceof Error ? e.message : "Pool usage is unavailable")- })- .finally(() => {- if (active) setDetailLoading(false)- })- return () => {- active = false- }- }, [timeframe, subject, pool])- const series = useMemo(- () => [- {- title: "Consumed",- type: "bar" as const,- color: "#0972d3",- data: (overview?.pools ?? []).map((p) => ({- x: p.name,- y: p[metric].consumed,- })),- },- {- title: "Provisioned capacity",- type: "bar" as const,- color: "#9dc7ea",- data: (overview?.pools ?? []).map((p) => ({- x: p.name,- y: p[metric].provisioned,- })),- },- ],- [overview, metric],- )- const selected = overview?.pools.find((p) => p.id === pool)- const unit = metric === "cpu" ? "CPU core-hours" : "Memory GiB-hours"- const changeTime = (v: UsageTimeframe) => {- const n = new URLSearchParams(sp)- n.set("timeframe", v)- setSp(n)- }- const view = () => {- const n = new URLSearchParams(sp),- v = input.trim()- v ? n.set("subject", v) : n.delete("subject")- setSp(n)- }- return (- <PageShell- eyebrow="Resources"- title="Usage preview"- description="Preview resource consumption and provisioned capacity. No pricing or payment data is shown."- actions={- <SegmentedControl- selectedId={timeframe}- onChange={(e) => changeTime(e.detail.selectedId as UsageTimeframe)}- options={opts}- label="Usage timeframe"- />- }- >- <SpaceBetween size="l">- {admin && (- <Container header={<Header variant="h2">Administrator view</Header>}>- <SpaceBetween size="s">- <FormField- label="View usage for subject"- description="The signed-in administrator remains the real actor; this selection only scopes usage reads."- >- <SpaceBetween direction="horizontal" size="xs">- <Input- value={input}- onChange={(e) => setInput(e.detail.value)}- />- <Button onClick={view}>View usage</Button>- </SpaceBetween>- </FormField>- {subject && (- <Alert type="info">Viewing usage for {subject}</Alert>- )}- </SpaceBetween>- </Container>- )}- {loading && (- <Box textAlign="center">- <Spinner /> Loading usage data- </Box>- )}- {error && (- <Alert type="error" header="Usage data is unavailable">- {error}- </Alert>- )}- {!loading && overview && (- <SpaceBetween size="l">- <Container- header={- <Header- variant="h2"- description="Consumed values use measured usage; provisioned values use Kubernetes requests observed by OpenCost, grouped by pool for the selected timeframe."- >- Overview- </Header>- }- >- <SpaceBetween size="m">- <SegmentedControl- selectedId={metric}- onChange={(e) => setMetric(e.detail.selectedId as Metric)}- options={[- { id: "cpu", text: "CPU" },- { id: "memory", text: "Memory" },- ]}- label="Usage metric"- />- <Box variant="h3">{unit}</Box>- {overview.partial && (- <StatusIndicator type="warning">- Data is partial- </StatusIndicator>- )}- {stale(overview.data_as_of, timeframe) && (- <StatusIndicator type="warning">- Usage data may be stale- </StatusIndicator>- )}- <Box color="text-body-secondary">- Data as of {new Date(overview.data_as_of).toLocaleString()}- </Box>- {overview.pools.length === 0 ? (- <Box textAlign="center" color="text-body-secondary">- No usage data is available for this timeframe.- </Box>- ) : (- <>- <BarChart- series={series}- xScaleType="categorical"- xDomain={overview.pools.map((p) => p.name)}- yTitle={unit}- ariaLabel={`Usage overview in ${unit}`}- ariaDescription="Each pool has separately labeled consumed and provisioned capacity bars."- i18nStrings={i18n}- hideFilter- />- {overview.pools.map((p) => {- const v = p[metric]- return (- <Box key={p.id} color="text-body-secondary">- {p.name}: {v.consumed} consumed, {v.provisioned}{" "}- provisioned, {util(v.consumed, v.provisioned)}%- utilization- </Box>- )- })}- </>- )}- </SpaceBetween>- </Container>- {overview.pools.length > 0 && (- <Container- header={- <Header variant="h2">- {selected?.name ?? "Pool"} drilldown- </Header>- }- >- <SpaceBetween size="l">- <FormField label="Pool drilldown">- <Select- selectedOption={- selected- ? { label: selected.name, value: selected.id }- : null- }- onChange={(e) =>- setPool(e.detail.selectedOption.value ?? null)- }- options={overview.pools.map((p) => ({- label: p.name,- value: p.id,- }))}- />- </FormField>- {detailLoading && (- <Box>- <Spinner /> Loading pool usage- </Box>- )}- {detail && !detailLoading && (- <>- <UsageLine- title="CPU core-hours per bucket"- consumed={detail.buckets.map((b) => ({- x: new Date(b.start),- y: b.cpu_consumed,- }))}- provisioned={detail.buckets.map((b) => ({- x: new Date(b.start),- y: b.cpu_provisioned,- }))}- />- <UsageLine- title="Memory GiB-hours per bucket"- consumed={detail.buckets.map((b) => ({- x: new Date(b.start),- y: b.memory_consumed,- }))}- provisioned={detail.buckets.map((b) => ({- x: new Date(b.start),- y: b.memory_provisioned,- }))}- />- </>- )}- </SpaceBetween>- </Container>- )}- </SpaceBetween>- )}- </SpaceBetween>- </PageShell>- )-}-function UsageLine({- title,- consumed,- provisioned,-}: {- title: string- consumed: { x: Date; y: number }[]- provisioned: { x: Date; y: number }[]-}) {- return (- <SpaceBetween size="s">- <Box variant="h3">{title}</Box>- <LineChart- series={[- { title: "Consumed", type: "line", color: "#0972d3", data: consumed },- {- title: "Provisioned capacity",- type: "line",- color: "#9dc7ea",- data: provisioned,- },- ]}- xScaleType="time"- xTitle="Bucket start"- yTitle={title}- ariaLabel={title}- ariaDescription="Consumed values use measured usage; provisioned values use Kubernetes requests observed by OpenCost."- i18nStrings={i18n}- hideFilter- />- </SpaceBetween>- )-}diff --git a/libs/fleet/src/sdk/billing.ts b/libs/fleet/src/sdk/billing.tsindex 78084ef46e..9eff78d22c 100644--- a/libs/fleet/src/sdk/billing.ts+++ b/libs/fleet/src/sdk/billing.ts@@ -1,5 +1,6 @@import { getToken } from "../auth/keycloak";import {+ getLocalVisualPreviewBillingUsage,isLocalVisualPreview,localVisualPreviewPath,} from "../local-visual-preview";@@ -16,6 +17,35 @@ export interface BillingSummary {card: SavedCard | null;}+export type UsageRangeMonths = 3 | 6 | 12;++export interface UsagePoint {+ period_start: string;+ period_end: string;+ amount: number;+ estimate: boolean;+}++export interface UsageBreakdownItem {+ name: string;+ amount: number;+ quantity: number;+ period_start: string;+ period_end: string;+}++export interface BillingUsage {+ currency: string;+ range_start: string;+ range_end: string;+ current_period_start: string | null;+ current_period_end: string | null;+ current_estimate: number;+ previous_period_amount: number;+ trend: UsagePoint[];+ breakdown: UsageBreakdownItem[];+}+async function billingRequest<T>(path: string,method: "GET" | "POST",@@ -50,4 +80,13 @@ export const billingApi = {url: localVisualPreviewPath("/settings?billing=portal-preview"),}): billingRequest<{ url: string }>("/api/billing/portal-session", "POST"),+ usage: (months: UsageRangeMonths) => {+ if (isLocalVisualPreview()) {+ return getLocalVisualPreviewBillingUsage(months);+ }+ return billingRequest<BillingUsage>(+ `/api/billing/usage?months=${months}`,+ "GET",+ );+ },};diff --git a/libs/fleet/src/sdk/usage.ts b/libs/fleet/src/sdk/usage.tsindex b1c12d40fd..254d677de8 100644--- a/libs/fleet/src/sdk/usage.ts+++ b/libs/fleet/src/sdk/usage.ts@@ -1,10 +1,176 @@import { getToken } from "../auth/keycloak"-export type UsageTimeframe="24h"|"7d"|"30d"-export interface UsageMetricTotals{consumed:number;provisioned:number}-export interface UsagePoolSummary{id:string;name:string;cpu:UsageMetricTotals;memory:UsageMetricTotals}-export interface UsageOverviewResponse{data_as_of:string;partial:boolean;pools:UsagePoolSummary[]}-export interface UsageBucket{start:string;end:string;cpu_consumed:number;cpu_provisioned:number;memory_consumed:number;memory_provisioned:number}-export interface UsagePoolDetailResponse{data_as_of:string;partial:boolean;pool:{id:string;name:string};buckets:UsageBucket[]}-async function request<T>(path:string,p:URLSearchParams):Promise<T>{const token=await getToken();const r=await fetch(`${path}?${p}`,{headers:{Authorization:token?`Bearer ${token}`:""}});if(!r.ok){const b=await r.json().catch(()=>null) as {error?:string}|null;throw new Error(b?.error??`usage request failed: ${r.status}`)}return r.json() as Promise<T>}-function params(timeframe:UsageTimeframe,subject?:string){const p=new URLSearchParams({timeframe});if(subject)p.set("subject",subject);return p}-export const usageApi={overview:(t:UsageTimeframe,s?:string)=>request<UsageOverviewResponse>("/api/usage/overview",params(t,s)),pool:(t:UsageTimeframe,poolId:string,s?:string)=>{const p=params(t,s);p.set("pool",poolId);return request<UsagePoolDetailResponse>("/api/usage/pool",p)}}+import { isLocalVisualPreview } from "../local-visual-preview"++export type UsageTimeframe = "24h" | "7d" | "30d"++export interface UsageMetricTotals {+ consumed: number+ provisioned: number+}++export interface UsagePoolSummary {+ id: string+ name: string+ cpu: UsageMetricTotals+ memory: UsageMetricTotals+ cost_usd: number+}++export interface UsageOverviewResponse {+ data_as_of: string+ partial: boolean+ pools: UsagePoolSummary[]+}++export interface UsageBucket {+ start: string+ end: string+ cpu_consumed: number+ cpu_provisioned: number+ memory_consumed: number+ memory_provisioned: number+}++export interface UsagePoolDetailResponse {+ data_as_of: string+ partial: boolean+ pool: { id: string; name: string }+ buckets: UsageBucket[]+}++const previewPools: UsagePoolSummary[] = [+ {+ id: "preview:browser-agent-fleet",+ name: "browser-agent-fleet",+ cpu: { consumed: 842.6, provisioned: 1_344 },+ memory: { consumed: 3_218.4, provisioned: 5_376 },+ cost_usd: 18.42,+ },+ {+ id: "preview:desktop-agent-fleet",+ name: "desktop-agent-fleet",+ cpu: { consumed: 396.8, provisioned: 672 },+ memory: { consumed: 1_786.2, provisioned: 2_688 },+ cost_usd: 9.75,+ },+ {+ id: "preview:eval-runner-fleet",+ name: "eval-runner-fleet",+ cpu: { consumed: 271.4, provisioned: 448 },+ memory: { consumed: 986.7, provisioned: 1_792 },+ cost_usd: 6.2,+ },+ {+ id: "preview:batch-jobs-fleet",+ name: "batch-jobs-fleet",+ cpu: { consumed: 188.9, provisioned: 320 },+ memory: { consumed: 624.5, provisioned: 1_280 },+ cost_usd: 3.1,+ },+]++function previewState() {+ return new URLSearchParams(window.location.search).get("cua-preview-state")+}++async function preparePreview() {+ const state = previewState()+ if (state === "error") throw new Error("Preview usage is unavailable")+ if (state === "loading") {+ await new Promise(resolve => window.setTimeout(resolve, 2_000))+ }+ return state+}++async function previewOverview(+ timeframe: UsageTimeframe,+): Promise<UsageOverviewResponse> {+ const state = await preparePreview()+ const multiplier = timeframe === "24h" ? 1 : timeframe === "7d" ? 7 : 30+ return {+ data_as_of: "2026-08-22T02:00:00Z",+ partial: false,+ pools: state === "empty"+ ? []+ : previewPools.map(pool => ({+ ...pool,+ cost_usd: pool.cost_usd * multiplier,+ })),+ }+}++function previewBucketCount(timeframe: UsageTimeframe) {+ if (timeframe === "24h") return { count: 24, stepMs: 60 * 60 * 1_000 }+ if (timeframe === "7d") return { count: 28, stepMs: 6 * 60 * 60 * 1_000 }+ return { count: 30, stepMs: 24 * 60 * 60 * 1_000 }+}++async function previewPool(+ timeframe: UsageTimeframe,+ poolId: string,+): Promise<UsagePoolDetailResponse> {+ const state = await preparePreview()+ const pool = previewPools.find(candidate => candidate.id === poolId) ?? previewPools[0]+ const { count, stepMs } = previewBucketCount(timeframe)+ const end = new Date("2026-08-22T02:00:00Z").getTime()+ const poolScale = Math.max(+ previewPools.findIndex(candidate => candidate.id === pool.id) + 1,+ 1,+ )+ const buckets = state === "empty"+ ? []+ : Array.from({ length: count }, (_, index) => {+ const start = end - (count - index) * stepMs+ const wave = 0.72 + Math.sin(index / 2.8) * 0.12 + index / count * 0.1+ const cpuProvisioned = 38 / poolScale+ const memoryProvisioned = 152 / poolScale+ return {+ start: new Date(start).toISOString(),+ end: new Date(start + stepMs).toISOString(),+ cpu_consumed: Number((cpuProvisioned * wave).toFixed(2)),+ cpu_provisioned: Number(cpuProvisioned.toFixed(2)),+ memory_consumed: Number((memoryProvisioned * (wave - 0.06)).toFixed(2)),+ memory_provisioned: Number(memoryProvisioned.toFixed(2)),+ }+ })+ return {+ data_as_of: "2026-08-22T02:00:00Z",+ partial: false,+ pool: { id: pool.id, name: pool.name },+ buckets,+ }+}++async function request<T>(path: string, query: URLSearchParams): Promise<T> {+ const token = await getToken()+ const response = await fetch(`${path}?${query}`, {+ headers: { Authorization: token ? `Bearer ${token}` : "" },+ })+ if (!response.ok) {+ const body = await response.json().catch(() => null) as { error?: string } | null+ throw new Error(body?.error ?? `usage request failed: ${response.status}`)+ }+ return response.json() as Promise<T>+}++function params(timeframe: UsageTimeframe, subject?: string) {+ const query = new URLSearchParams({ timeframe })+ if (subject) query.set("subject", subject)+ return query+}++export const usageApi = {+ overview: (timeframe: UsageTimeframe, subject?: string) =>+ isLocalVisualPreview()+ ? previewOverview(timeframe)+ : request<UsageOverviewResponse>(+ "/api/usage/overview",+ params(timeframe, subject),+ ),+ pool: (timeframe: UsageTimeframe, poolId: string, subject?: string) => {+ if (isLocalVisualPreview()) return previewPool(timeframe, poolId)+ const query = params(timeframe, subject)+ query.set("pool", poolId)+ return request<UsagePoolDetailResponse>("/api/usage/pool", query)+ },+}