Skip to content

An open-source, faster Devin alternative

TypeScript

feat(billing): per-agent paid features ($20/mo Telegram) + tabbed Billing UI

motatoes01a5043c8688
diff --git a/cmd/oc/internal/commands/agent_connect.go b/cmd/oc/internal/commands/agent_connect.go
index cdc15575..9f3bac34 100644
--- a/cmd/oc/internal/commands/agent_connect.go
+++ b/cmd/oc/internal/commands/agent_connect.go
@@ -5,12 +5,28 @@ package commands
import (
"bufio"
"fmt"
+ "net/url"
"os"
"strings"
"github.com/spf13/cobra"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
)
+// dashboardAgentURL builds the dashboard URL for an agent, used in the
+// CLI's paywall-redirect message. APIURL doubles as the dashboard origin
+// (the OC server serves /api/dashboard/* and the SPA from the same host).
+func dashboardAgentURL(cmd *cobra.Command, agentID string) string {
+ cfg := config.Load(cmd)
+ base := strings.TrimRight(cfg.APIURL, "/")
+ if base == "" {
+ base = config.DefaultAPIURL
+ }
+ return base + "/agents/" + url.PathEscape(agentID)
+}
+
var agentConnectCmd = &cobra.Command{
Use: "connect <id> <channel>",
Short: "Connect a channel to an agent",
@@ -62,6 +78,20 @@ var agentConnectCmd = &cobra.Command{
var result operationSubmissionResponse
if err := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel, body, &result); err != nil {
+ // HTTP 402 → paywalled feature. The dashboard owns
+ // subscription flow (Stripe Checkout needs a browser);
+ // surface a clean message and the upgrade URL instead of
+ // a raw API error.
+ if apiErr, ok := err.(*client.APIError); ok && apiErr.StatusCode == 402 {
+ upgradeURL := dashboardAgentURL(cmd, agentID)
+ fmt.Fprintf(os.Stderr,
+ "\nThis agent is not subscribed to %s ($20/mo per agent).\n"+
+ "Subscribe in the dashboard, then re-run this command:\n"+
+ " %s\n\n",
+ channel, upgradeURL,
+ )
+ return fmt.Errorf("subscription required for %s on %s", channel, agentID)
+ }
return err
}
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 7e013a25..3cd5eb26 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -370,6 +370,7 @@ func main() {
var stripeClient *billing.StripeClient
if cfg.StripeSecretKey != "" {
stripeClient = billing.NewStripeClient(cfg.StripeSecretKey, cfg.StripeWebhookSecret, cfg.StripeSuccessURL, cfg.StripeCancelURL)
+ stripeClient.TelegramAgentPriceID = cfg.StripeTelegramAgentPriceID
if err := stripeClient.EnsureProducts(); err != nil {
log.Printf("opensandbox: Stripe product setup failed: %v (billing may not work)", err)
} else {
diff --git a/internal/api/dashboard_agent_subscriptions.go b/internal/api/dashboard_agent_subscriptions.go
new file mode 100644
index 00000000..8a02865b
--- /dev/null
+++ b/internal/api/dashboard_agent_subscriptions.go
@@ -0,0 +1,519 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net/http"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// Per-agent paywalled-feature subscription endpoints. v1 ships with one
+// feature ("telegram") but the data model is feature-keyed so adding
+// Discord / Slack / etc. later is a matter of a new env var + a new
+// frontend tile, no schema change.
+//
+// Auth: cookie-protected (mounted under /api/dashboard) for end-user
+// flows; sessions-api hits the API-key-protected entitlement endpoint
+// (see dashboardAgentEntitlements wired in router.go).
+
+const (
+ telegramFeature = "telegram"
+)
+
+// reconcileAgentFeatureFromStripe checks Stripe for an existing
+// subscription matching (agent_id, feature) and persists a local row
+// if Stripe has it but we don't. Used to recover from a missing
+// webhook (e.g. STRIPE_WEBHOOK_SECRET unset, transient network glitch).
+//
+// Returns the resulting active subscription, or nil if Stripe also
+// has nothing.
+func (s *Server) reconcileAgentFeatureFromStripe(ctx context.Context, orgID uuid.UUID, agentID, feature string) (*db.AgentSubscription, error) {
+ if s.stripeClient == nil || s.store == nil {
+ return nil, nil
+ }
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err != nil || org.StripeCustomerID == nil {
+ return nil, err
+ }
+ stripeSub, err := s.stripeClient.FindAgentFeatureSubscription(*org.StripeCustomerID, agentID, feature)
+ if err != nil || stripeSub == nil {
+ return nil, err
+ }
+
+ // Idempotent: if we already have it, just nudge status.
+ row, err := s.store.GetAgentSubscriptionByStripeID(ctx, stripeSub.ID)
+ if err != nil {
+ return nil, err
+ }
+
+ var currentPeriodEnd *time.Time
+ if stripeSub.Items != nil && len(stripeSub.Items.Data) > 0 && stripeSub.Items.Data[0].CurrentPeriodEnd > 0 {
+ t := time.Unix(stripeSub.Items.Data[0].CurrentPeriodEnd, 0).UTC()
+ currentPeriodEnd = &t
+ }
+ priceID := ""
+ if stripeSub.Items != nil && len(stripeSub.Items.Data) > 0 && stripeSub.Items.Data[0].Price != nil {
+ priceID = stripeSub.Items.Data[0].Price.ID
+ }
+
+ if row != nil {
+ // Update status from Stripe (in case we missed the webhook update).
+ if err := s.store.UpdateAgentSubscriptionFromStripe(ctx, stripeSub.ID, string(stripeSub.Status), currentPeriodEnd, stripeSub.CancelAtPeriodEnd, nil); err != nil {
+ return nil, err
+ }
+ row.Status = string(stripeSub.Status)
+ row.CurrentPeriodEnd = currentPeriodEnd
+ row.CancelAtPeriodEnd = stripeSub.CancelAtPeriodEnd
+ return row, nil
+ }
+
+ saved, err := s.store.CreateAgentSubscription(ctx, db.AgentSubscription{
+ OrgID: orgID,
+ AgentID: agentID,
+ Feature: feature,
+ StripeCustomerID: *org.StripeCustomerID,
+ StripeSubscriptionID: stripeSub.ID,
+ StripePriceID: priceID,
+ Status: string(stripeSub.Status),
+ CurrentPeriodEnd: currentPeriodEnd,
+ CancelAtPeriodEnd: stripeSub.CancelAtPeriodEnd,
+ })
+ if err != nil {
+ return nil, err
+ }
+ log.Printf("billing: reconciled agent_subscription from Stripe (agent=%s feature=%s sub=%s status=%s)",
+ agentID, feature, stripeSub.ID, stripeSub.Status)
+ return saved, nil
+}
+
+// dashboardSubscribeAgentFeature creates a Stripe subscription for the
+// given (agent_id, feature) pair. Two flows:
+//
+// 1. Customer has a saved default payment method → call
+// subscriptions.create directly. Returns {status:"active", agent_id}.
+// 2. No card on file → create a Stripe Checkout session
+// (mode=subscription) and return its URL. Frontend redirects.
+//
+// Idempotent: if an active subscription already exists for this
+// (agent_id, feature), returns the existing one with status:"already_subscribed".
+func (s *Server) dashboardSubscribeAgentFeature(c echo.Context) error {
+ if s.stripeClient == nil || s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "billing not configured"})
+ }
+
+ feature := c.Param("feature")
+ agentID := c.Param("agentId")
+ if agentID == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "agent_id required"})
+ }
+
+ priceID, ok := s.priceIDForFeature(feature)
+ if !ok {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": fmt.Sprintf("unknown feature %q or price not configured", feature),
+ })
+ }
+ if priceID == "" {
+ // Feature exists but is ungated on this deployment (dev mode)
+ // — surface that explicitly so the caller knows there's nothing
+ // to pay for. UI treats this like already-entitled.
+ return c.JSON(http.StatusOK, map[string]any{
+ "status": "ungated",
+ "feature": feature,
+ "agent_id": agentID,
+ })
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ ctx := c.Request().Context()
+
+ // Already subscribed? Return existing.
+ existing, err := s.store.GetActiveAgentSubscription(ctx, agentID, feature)
+ if err != nil {
+ log.Printf("billing: get active sub failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})
+ }
+ if existing == nil {
+ // Reconcile path: maybe Stripe has the sub but our DB lost the
+ // webhook (or signature wasn't configured). Re-import before
+ // telling the user to pay again.
+ if reconciled, rerr := s.reconcileAgentFeatureFromStripe(ctx, orgID, agentID, feature); rerr == nil && reconciled != nil {
+ existing = reconciled
+ }
+ }
+ if existing != nil && existing.OrgID == orgID && db.AgentSubscriptionIsActive(existing.Status) {
+ return c.JSON(http.StatusOK, map[string]any{
+ "status": "already_subscribed",
+ "feature": feature,
+ "agent_id": agentID,
+ "subscription_id": existing.StripeSubscriptionID,
+ })
+ }
+
+ // Need a Stripe customer ID for the org. Existing billing flow
+ // creates one when the org first enters checkout for the pro plan.
+ // For per-agent subs we may need to create one here lazily so the
+ // user can pay for telegram even on a free plan.
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err != nil {
+ log.Printf("billing: get org failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})
+ }
+ customerID := ""
+ if org.StripeCustomerID != nil {
+ customerID = *org.StripeCustomerID
+ }
+ if customerID == "" {
+ newCustomer, err := s.stripeClient.CreateCustomer(org.Name, "")
+ if err != nil {
+ log.Printf("billing: create customer failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "stripe customer create failed"})
+ }
+ customerID = newCustomer
+ if err := s.store.SetStripeCustomerID(ctx, orgID, customerID); err != nil {
+ log.Printf("billing: persist customer id failed: %v", err)
+ // Don't fail the request — we have the ID locally and will
+ // use it; persistence retry happens on next request.
+ }
+ }
+
+ metadata := map[string]string{
+ "type": "agent_feature_subscription",
+ "org_id": orgID.String(),
+ "agent_id": agentID,
+ "feature": feature,
+ }
+
+ pmID, err := s.stripeClient.GetCustomerDefaultPaymentMethod(customerID)
+ if err != nil {
+ log.Printf("billing: fetch default pm failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "stripe lookup failed"})
+ }
+
+ if pmID == "" {
+ // No card on file — bounce through Checkout. The webhook
+ // handler will record the subscription on completion.
+ successURL := s.stripeClient.SuccessURL()
+ cancelURL := s.stripeClient.CancelURL()
+ url, err := s.stripeClient.CreateAgentFeatureCheckoutSession(customerID, priceID, successURL, cancelURL, metadata)
+ if err != nil {
+ log.Printf("billing: create checkout failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "checkout create failed"})
+ }
+ return c.JSON(http.StatusOK, map[string]any{
+ "status": "checkout_required",
+ "checkout_url": url,
+ "feature": feature,
+ "agent_id": agentID,
+ })
+ }
+
+ // Saved card path — direct subscription, no redirect.
+ sub, err := s.stripeClient.CreateAgentFeatureSubscription(customerID, priceID, metadata)
+ if err != nil {
+ log.Printf("billing: direct subscribe failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "subscribe failed",
+ "detail": err.Error(),
+ })
+ }
+
+ // stripe-go v82 moved CurrentPeriodEnd off the Subscription onto each
+ // SubscriptionItem; for our single-item subs we just read the first.
+ var currentPeriodEnd time.Time
+ if sub.Items != nil && len(sub.Items.Data) > 0 && sub.Items.Data[0].CurrentPeriodEnd > 0 {
+ currentPeriodEnd = time.Unix(sub.Items.Data[0].CurrentPeriodEnd, 0).UTC()
+ }
+ row := db.AgentSubscription{
+ OrgID: orgID,
+ AgentID: agentID,
+ Feature: feature,
+ StripeCustomerID: customerID,
+ StripeSubscriptionID: sub.ID,
+ StripePriceID: priceID,
+ Status: string(sub.Status),
+ CancelAtPeriodEnd: sub.CancelAtPeriodEnd,
+ }
+ if !currentPeriodEnd.IsZero() {
+ row.CurrentPeriodEnd = &currentPeriodEnd
+ }
+ saved, err := s.store.CreateAgentSubscription(ctx, row)
+ if err != nil {
+ // Stripe sub exists but DB write failed — log loudly. The
+ // webhook handler will reconcile on next event.
+ log.Printf("billing: persist agent_subscription failed (stripe sub=%s, agent=%s): %v", sub.ID, agentID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "subscription created in Stripe but local persist failed; will reconcile on next webhook",
+ })
+ }
+
+ return c.JSON(http.StatusOK, map[string]any{
+ "status": "active",
+ "feature": feature,
+ "agent_id": agentID,
+ "subscription_id": saved.StripeSubscriptionID,
+ "price_id": saved.StripePriceID,
+ })
+}
+
+// dashboardCancelAgentFeature schedules the per-agent subscription to
+// stop renewing at period end. Customer keeps the feature until the
+// current billing period ends (no proration, no immediate cutoff).
+// The webhook handler flips the local row to canceled when Stripe
+// confirms the deletion.
+func (s *Server) dashboardCancelAgentFeature(c echo.Context) error {
+ if s.stripeClient == nil || s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "billing not configured"})
+ }
+
+ feature := c.Param("feature")
+ agentID := c.Param("agentId")
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ ctx := c.Request().Context()
+ existing, err := s.store.GetActiveAgentSubscription(ctx, agentID, feature)
+ if err != nil {
+ log.Printf("billing: get active sub failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})
+ }
+ if existing == nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active subscription"})
+ }
+ if existing.OrgID != orgID {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active subscription"})
+ }
+
+ if _, err := s.stripeClient.CancelAgentFeatureSubscription(existing.StripeSubscriptionID, false); err != nil {
+ log.Printf("billing: cancel subscription failed: %v", err)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": "stripe cancel failed",
+ "detail": err.Error(),
+ })
+ }
+ // Optimistic local update — webhook will reconcile.
+ if err := s.store.UpdateAgentSubscriptionFromStripe(ctx, existing.StripeSubscriptionID, existing.Status, existing.CurrentPeriodEnd, true, nil); err != nil {
+ log.Printf("billing: persist cancel-at-period-end failed: %v", err)
+ }
+ return c.JSON(http.StatusOK, map[string]any{
+ "status": "scheduled_cancel",
+ "feature": feature,
+ "agent_id": agentID,
+ "cancel_at_period_end": true,
+ "current_period_end": existing.CurrentPeriodEnd,
+ })
+}
+
+// dashboardListAgentEntitlements returns which paywalled features the
+// caller's org has paid for on a given agent. Used by the agent detail
+// page to decide whether to show the paywall or the connect flow.
+func (s *Server) dashboardListAgentEntitlements(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ agentID := c.Param("agentId")
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ type entRow struct {
+ Feature string `json:"feature"`
+ Entitled bool `json:"entitled"`
+ Reason string `json:"reason,omitempty"`
+ PriceMonthlyCents int64 `json:"price_monthly_cents,omitempty"`
+ Status string `json:"status,omitempty"`
+ CurrentPeriodEnd *time.Time `json:"current_period_end,omitempty"`
+ CancelAtPeriodEnd bool `json:"cancel_at_period_end,omitempty"`
+ StripeSubscriptionID string `json:"stripe_subscription_id,omitempty"`
+ }
+
+ out := []entRow{}
+ for _, feature := range []string{telegramFeature} {
+ priceID, _ := s.priceIDForFeature(feature)
+ row := entRow{Feature: feature}
+ if priceID == "" {
+ // Ungated on this deployment.
+ row.Entitled = true
+ row.Reason = "ungated"
+ out = append(out, row)
+ continue
+ }
+ sub, err := s.store.GetActiveAgentSubscription(c.Request().Context(), agentID, feature)
+ if err != nil {
+ log.Printf("billing: list entitlements lookup failed: %v", err)
+ }
+ if sub == nil {
+ // Reconcile path — see subscribe handler.
+ if reconciled, rerr := s.reconcileAgentFeatureFromStripe(c.Request().Context(), orgID, agentID, feature); rerr == nil && reconciled != nil {
+ sub = reconciled
+ }
+ }
+ if sub != nil && sub.OrgID == orgID && db.AgentSubscriptionIsActive(sub.Status) {
+ row.Entitled = true
+ row.Status = sub.Status
+ row.CurrentPeriodEnd = sub.CurrentPeriodEnd
+ row.CancelAtPeriodEnd = sub.CancelAtPeriodEnd
+ row.StripeSubscriptionID = sub.StripeSubscriptionID
+ } else {
+ row.Entitled = false
+ row.Reason = "subscription_required"
+ }
+ row.PriceMonthlyCents = priceMonthlyCentsForFeature(feature)
+ out = append(out, row)
+ }
+ return c.JSON(http.StatusOK, map[string]any{"agent_id": agentID, "entitlements": out})
+}
+
+// dashboardListOrgAgentSubscriptions returns every per-agent subscription
+// the org owns (active and historical). Powers the Billing → Agents tab.
+//
+// We deliberately do not filter by status here — past subscriptions
+// (canceled, etc.) are useful billing context. The UI groups by agent
+// and feature and shows the most-recent per pair.
+func (s *Server) dashboardListOrgAgentSubscriptions(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+ subs, err := s.store.ListAgentSubscriptionsByOrg(c.Request().Context(), orgID)
+ if err != nil {
+ log.Printf("billing: list org agent subscriptions failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})
+ }
+
+ type row struct {
+ AgentID string `json:"agent_id"`
+ Feature string `json:"feature"`
+ Status string `json:"status"`
+ Active bool `json:"active"`
+ PriceMonthlyCents int64 `json:"price_monthly_cents"`
+ CurrentPeriodEnd *time.Time `json:"current_period_end,omitempty"`
+ CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
+ CanceledAt *time.Time `json:"canceled_at,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ StripeSubscriptionID string `json:"stripe_subscription_id"`
+ }
+ out := make([]row, 0, len(subs))
+ for _, sub := range subs {
+ out = append(out, row{
+ AgentID: sub.AgentID,
+ Feature: sub.Feature,
+ Status: sub.Status,
+ Active: db.AgentSubscriptionIsActive(sub.Status),
+ PriceMonthlyCents: priceMonthlyCentsForFeature(sub.Feature),
+ CurrentPeriodEnd: sub.CurrentPeriodEnd,
+ CancelAtPeriodEnd: sub.CancelAtPeriodEnd,
+ CanceledAt: sub.CanceledAt,
+ CreatedAt: sub.CreatedAt,
+ StripeSubscriptionID: sub.StripeSubscriptionID,
+ })
+ }
+ return c.JSON(http.StatusOK, map[string]any{"subscriptions": out})
+}
+
+// apiAgentEntitlement is the sessions-api-callable variant — accepts
+// JWT identity auth (aud=opencomputer-api) and returns a tight
+// {entitled: bool, reason} payload. Used by sessions-api right before
+// allowing a connect-channel operation.
+func (s *Server) apiAgentEntitlement(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ agentID := c.Param("agentId")
+ feature := c.Param("feature")
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ priceID, knownFeature := s.priceIDForFeature(feature)
+ if !knownFeature {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "unknown feature"})
+ }
+ if priceID == "" {
+ // Feature ungated on this deployment.
+ return c.JSON(http.StatusOK, map[string]any{
+ "entitled": true,
+ "reason": "ungated",
+ "feature": feature,
+ "agent_id": agentID,
+ })
+ }
+
+ sub, err := s.store.GetActiveAgentSubscription(c.Request().Context(), agentID, feature)
+ if err != nil {
+ log.Printf("billing: entitlement lookup failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal"})
+ }
+ if sub == nil {
+ // Same reconcile path as the dashboard handler — Stripe is the
+ // source of truth, so look there before telling the CLI/sessions-api
+ // the user hasn't paid.
+ if reconciled, rerr := s.reconcileAgentFeatureFromStripe(c.Request().Context(), orgID, agentID, feature); rerr == nil && reconciled != nil {
+ sub = reconciled
+ }
+ }
+ if sub == nil || sub.OrgID != orgID || !db.AgentSubscriptionIsActive(sub.Status) {
+ return c.JSON(http.StatusPaymentRequired, map[string]any{
+ "entitled": false,
+ "reason": "subscription_required",
+ "feature": feature,
+ "agent_id": agentID,
+ "price_monthly_cents": priceMonthlyCentsForFeature(feature),
+ })
+ }
+ return c.JSON(http.StatusOK, map[string]any{
+ "entitled": true,
+ "feature": feature,
+ "agent_id": agentID,
+ "status": sub.Status,
+ "current_period_end": sub.CurrentPeriodEnd,
+ "cancel_at_period_end": sub.CancelAtPeriodEnd,
+ })
+}
+
+// priceIDForFeature maps a feature string to its configured Stripe
+// price ID. Returns ("", true) if the feature is known but ungated on
+// this deployment (used as the dev-mode escape). Returns ("", false)
+// for unknown features.
+func (s *Server) priceIDForFeature(feature string) (string, bool) {
+ if s.stripeClient == nil {
+ return "", feature == telegramFeature // unknown stripe → behave as ungated for the known features
+ }
+ switch feature {
+ case telegramFeature:
+ return s.stripeClient.TelegramAgentPriceID, true
+ default:
+ return "", false
+ }
+}
+
+// priceMonthlyCentsForFeature is the human-readable price the UI
+// surfaces. Hardcoded for now — Stripe is the source of truth for
+// what the customer is actually charged; this is just for display.
+// If the two diverge, that's a config bug.
+func priceMonthlyCentsForFeature(feature string) int64 {
+ switch feature {
+ case telegramFeature:
+ return 2000 // $20.00/mo
+ }
+ return 0
+}
+
diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.go
index 42bd7f09..a2a03fe2 100644
--- a/internal/api/dashboard_billing.go
+++ b/internal/api/dashboard_billing.go
@@ -1,15 +1,18 @@
package api
import (
+ "context"
"encoding/json"
"io"
"log"
"net/http"
"strconv"
+ "time"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
)
// billingSetup initiates the upgrade flow: creates Stripe customer + Checkout session.
@@ -246,7 +249,8 @@ func (s *Server) stripeWebhook(c echo.Context) error {
if err := json.Unmarshal(event.Data.Raw, &sess); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "bad event data"})
}
- if sess.Metadata["type"] == "setup" {
+ switch sess.Metadata["type"] {
+ case "setup":
orgIDStr := sess.Metadata["org_id"]
orgID, err := uuid.Parse(orgIDStr)
if err != nil {
@@ -277,8 +281,19 @@ func (s *Server) stripeWebhook(c echo.Context) error {
}
log.Printf("billing: org %s upgraded to pro (subscription=%s, $30 credit applied)", orgID, subID)
+
+ case "agent_feature_subscription":
+ // Customer paid for a per-agent feature via Checkout. The
+ // Stripe-side subscription is already created (Checkout
+ // mode=subscription); we just persist the local row so
+ // the entitlement check finds it. Subscription metadata
+ // carries (org_id, agent_id, feature).
+ s.recordAgentFeatureCheckoutCompletion(ctx, sess.Metadata, event.Data.Raw)
}
+ case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted":
+ s.handleAgentFeatureSubscriptionEvent(ctx, string(event.Type), event.Data.Raw)
+
case "invoice.paid":
log.Printf("billing: invoice paid: %s", string(event.Data.Raw)[:100])
@@ -288,3 +303,137 @@ func (s *Server) stripeWebhook(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
}
+
+// recordAgentFeatureCheckoutCompletion persists a freshly-created
+// per-agent feature subscription that was set up via Checkout. The
+// Subscription object is already on Stripe; we just need to insert
+// the local row. Metadata is propagated from the Checkout Session
+// into the Subscription, so the subsequent customer.subscription.*
+// events will also trigger handleAgentFeatureSubscriptionEvent which
+// fills in current_period_end / status / etc.
+func (s *Server) recordAgentFeatureCheckoutCompletion(ctx context.Context, metadata map[string]string, raw []byte) {
+ orgID, err := uuid.Parse(metadata["org_id"])
+ if err != nil {
+ log.Printf("billing: agent_feature_subscription checkout missing org_id: %v", err)
+ return
+ }
+ agentID := metadata["agent_id"]
+ feature := metadata["feature"]
+ if agentID == "" || feature == "" {
+ log.Printf("billing: agent_feature_subscription checkout missing agent_id/feature in metadata")
+ return
+ }
+
+ // Pull the subscription_id out of the checkout session payload —
+ // Stripe attaches it after Checkout creates the subscription.
+ var sess struct {
+ Subscription string `json:"subscription"`
+ Customer string `json:"customer"`
+ }
+ if err := json.Unmarshal(raw, &sess); err != nil {
+ log.Printf("billing: agent_feature_subscription checkout: unmarshal: %v", err)
+ return
+ }
+ if sess.Subscription == "" {
+ log.Printf("billing: agent_feature_subscription checkout has no subscription id")
+ return
+ }
+
+ // Idempotent: skip if we already recorded it.
+ existing, err := s.store.GetAgentSubscriptionByStripeID(ctx, sess.Subscription)
+ if err == nil && existing != nil {
+ return
+ }
+
+ priceID := ""
+ if s.stripeClient != nil {
+ switch feature {
+ case "telegram":
+ priceID = s.stripeClient.TelegramAgentPriceID
+ }
+ }
+
+ if _, err := s.store.CreateAgentSubscription(ctx, db.AgentSubscription{
+ OrgID: orgID,
+ AgentID: agentID,
+ Feature: feature,
+ StripeCustomerID: sess.Customer,
+ StripeSubscriptionID: sess.Subscription,
+ StripePriceID: priceID,
+ Status: "incomplete", // will be updated by subscription.updated event
+ }); err != nil {
+ log.Printf("billing: persist agent_subscription from checkout failed: %v", err)
+ } else {
+ log.Printf("billing: agent_feature_subscription recorded: agent=%s feature=%s sub=%s", agentID, feature, sess.Subscription)
+ }
+}
+
+// handleAgentFeatureSubscriptionEvent reconciles status on every
+// customer.subscription.* event. We filter to subscriptions that we
+// have a local row for — anything else is the org-level pro-plan
+// subscription which is handled elsewhere.
+//
+// `customer.subscription.deleted` fires when Stripe finally removes
+// the subscription (after period end if cancel_at_period_end was
+// scheduled, or immediately for a hard cancel). At that point we
+// flip the local row to canceled and disconnect any active Telegram
+// webhook so the user actually loses access.
+func (s *Server) handleAgentFeatureSubscriptionEvent(ctx context.Context, eventType string, raw []byte) {
+ var sub struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
+ CanceledAt *int64 `json:"canceled_at"`
+ Metadata map[string]string `json:"metadata"`
+ Items struct {
+ Data []struct {
+ CurrentPeriodEnd int64 `json:"current_period_end"`
+ } `json:"data"`
+ } `json:"items"`
+ }
+ if err := json.Unmarshal(raw, &sub); err != nil {
+ log.Printf("billing: subscription event unmarshal: %v", err)
+ return
+ }
+
+ row, err := s.store.GetAgentSubscriptionByStripeID(ctx, sub.ID)
+ if err != nil {
+ log.Printf("billing: lookup agent_subscription %s failed: %v", sub.ID, err)
+ return
+ }
+ if row == nil {
+ // Not a per-agent subscription — ignore.
+ return
+ }
+
+ var currentPeriodEnd *time.Time
+ if len(sub.Items.Data) > 0 && sub.Items.Data[0].CurrentPeriodEnd > 0 {
+ t := time.Unix(sub.Items.Data[0].CurrentPeriodEnd, 0).UTC()
+ currentPeriodEnd = &t
+ }
+ var canceledAt *time.Time
+ if sub.CanceledAt != nil && *sub.CanceledAt > 0 {
+ t := time.Unix(*sub.CanceledAt, 0).UTC()
+ canceledAt = &t
+ }
+
+ if err := s.store.UpdateAgentSubscriptionFromStripe(
+ ctx, sub.ID, sub.Status, currentPeriodEnd, sub.CancelAtPeriodEnd, canceledAt,
+ ); err != nil {
+ log.Printf("billing: update agent_subscription %s failed: %v", sub.ID, err)
+ return
+ }
+
+ // On terminal statuses, the entitlement check will start denying
+ // new connect attempts immediately. We deliberately don't auto-
+ // disconnect a currently-connected Telegram channel from here —
+ // that side-effect needs an authenticated call into sessions-api,
+ // and the cleanest way to do it is from the user-facing flow
+ // (e.g. show "subscription expired" in the UI and let them click
+ // Disconnect, or have sessions-api re-check entitlement on each
+ // inbound webhook). Phase-1 leaves this as a "soft" gate.
+ if eventType == "customer.subscription.deleted" {
+ log.Printf("billing: agent_subscription terminated: agent=%s feature=%s sub=%s status=%s",
+ row.AgentID, row.Feature, sub.ID, sub.Status)
+ }
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 515dbf49..1a7edf3f 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -194,6 +194,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Identity
api.POST("/auth/token", s.createAuthToken)
+ // Per-agent paywalled-feature entitlement check, callable from
+ // sessions-api with a JWT (aud=opencomputer-api) right before
+ // allowing a connect-channel operation.
+ api.GET("/agents/:agentId/entitlements/:feature", s.apiAgentEntitlement)
+
// Sandbox lifecycle
api.POST("/sandboxes", s.createSandbox)
api.GET("/sandboxes", s.listSandboxes)
@@ -407,6 +412,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
dash.GET("/billing/invoices", s.billingInvoices)
dash.POST("/billing/redeem", s.billingRedeem)
dash.POST("/billing/portal", s.billingPortal)
+ dash.GET("/billing/agent-subscriptions", s.dashboardListOrgAgentSubscriptions)
// Admin endpoints
@@ -415,6 +421,13 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// no API key is needed end-to-end. CLI users bypass this and hit
// sessions-api directly with X-API-Key.
dash.Any("/agents", s.dashboardAgentsProxy)
+ // Per-agent paywalled-feature subscriptions (telegram et al).
+ // Mounted BEFORE the catch-all /agents/* proxy so they don't
+ // get forwarded to sessions-api.
+ dash.GET("/agents/:agentId/entitlements", s.dashboardListAgentEntitlements)
+ dash.POST("/agents/:agentId/subscriptions/:feature", s.dashboardSubscribeAgentFeature)
+ dash.DELETE("/agents/:agentId/subscriptions/:feature", s.dashboardCancelAgentFeature)
+
dash.Any("/agents/*", s.dashboardAgentsProxy)
// Session detail + stats
diff --git a/internal/billing/stripe.go b/internal/billing/stripe.go
index 58b1c019..a66b391d 100644
--- a/internal/billing/stripe.go
+++ b/internal/billing/stripe.go
@@ -43,6 +43,11 @@ type StripeClient struct {
OverageMeterEventName string // "sandbox_compute_sandbox_overage"
ReservedPriceID string // flat reserved Price for `reserved_usage` events
ReservedMeterEventName string // "sandbox_compute_sandbox_reserved"
+
+ // Per-agent paywalled-feature prices. Configured from env and
+ // referenced by name from the dashboard subscribe handlers. Empty
+ // string means the feature is not gated on this deployment (dev mode).
+ TelegramAgentPriceID string // recurring $20/mo price for the per-agent Telegram feature
}
// NewStripeClient creates a new Stripe client.
@@ -476,6 +481,13 @@ func (s *StripeClient) ReportDiskOverageUsage(customerID string, gbSeconds int64
return nil
}
+// SuccessURL returns the configured Stripe Checkout success URL. Public
+// because per-feature subscribe handlers reuse the same redirect targets.
+func (s *StripeClient) SuccessURL() string { return s.successURL }
+
+// CancelURL returns the configured Stripe Checkout cancel URL.
+func (s *StripeClient) CancelURL() string { return s.cancelURL }
+
// GetCustomerBalance returns the customer's balance in cents (negative = credit).
func (s *StripeClient) GetCustomerBalance(customerID string) (int64, error) {
c, err := customer.Get(customerID, nil)
@@ -485,6 +497,138 @@ func (s *StripeClient) GetCustomerBalance(customerID string) (int64, error) {
return c.Balance, nil
}
+// GetCustomerDefaultPaymentMethod returns the saved default payment
+// method ID for a customer, or "" if none is on file. Used by the
+// per-agent subscribe flow: with a card on file we can call subscriptions.New
+// directly; without one we have to bounce through Stripe Checkout.
+func (s *StripeClient) GetCustomerDefaultPaymentMethod(customerID string) (string, error) {
+ c, err := customer.Get(customerID, nil)
+ if err != nil {
+ return "", err
+ }
+ if c.InvoiceSettings != nil && c.InvoiceSettings.DefaultPaymentMethod != nil {
+ return c.InvoiceSettings.DefaultPaymentMethod.ID, nil
+ }
+ return "", nil
+}
+
+// CreateAgentFeatureSubscription creates a per-agent paywalled-feature
+// subscription using a saved payment method. Caller must have verified
+// a default payment method exists (via GetCustomerDefaultPaymentMethod).
+//
+// metadata is stamped onto the Stripe Subscription so the webhook
+// handler can route updates back to the right (org, agent, feature)
+// triple without a DB lookup. Caller passes (org_id, agent_id, feature, type).
+//
+// Returns the Stripe subscription. Status will typically be "active"
+// (paid immediately), or "incomplete" if the saved card was declined —
+// callers should check.
+func (s *StripeClient) CreateAgentFeatureSubscription(
+ customerID, priceID string,
+ metadata map[string]string,
+) (*stripe.Subscription, error) {
+ params := &stripe.SubscriptionParams{
+ Customer: stripe.String(customerID),
+ Items: []*stripe.SubscriptionItemsParams{{
+ Price: stripe.String(priceID),
+ }},
+ // Charge the saved card immediately. Subscription becomes
+ // active on first invoice payment success.
+ PaymentBehavior: stripe.String("error_if_incomplete"),
+ }
+ for k, v := range metadata {
+ params.AddMetadata(k, v)
+ }
+ sub, err := subscription.New(params)
+ if err != nil {
+ return nil, fmt.Errorf("create agent-feature subscription: %w", err)
+ }
+ return sub, nil
+}
+
+// CreateAgentFeatureCheckoutSession redirects the customer to Stripe
+// Checkout to add a payment method AND start the subscription
+// atomically. Used when the customer has no card on file.
+//
+// metadata is propagated to both the Checkout Session and (via
+// SubscriptionData) the resulting Subscription so the webhook can wire
+// it back to the right agent on completion.
+func (s *StripeClient) CreateAgentFeatureCheckoutSession(
+ customerID, priceID string,
+ successURL, cancelURL string,
+ metadata map[string]string,
+) (string, error) {
+ params := &stripe.CheckoutSessionParams{
+ Customer: stripe.String(customerID),
+ Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
+ SuccessURL: stripe.String(successURL),
+ CancelURL: stripe.String(cancelURL),
+ LineItems: []*stripe.CheckoutSessionLineItemParams{{
+ Price: stripe.String(priceID),
+ Quantity: stripe.Int64(1),
+ }},
+ SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{},
+ }
+ for k, v := range metadata {
+ params.AddMetadata(k, v)
+ params.SubscriptionData.AddMetadata(k, v)
+ }
+ sess, err := checkoutsession.New(params)
+ if err != nil {
+ return "", fmt.Errorf("create agent-feature checkout: %w", err)
+ }
+ return sess.URL, nil
+}
+
+// FindAgentFeatureSubscription looks up an active subscription on a
+// customer for a given (agent_id, feature) combo, identified by the
+// metadata stamps we set at create time. Used by the reconciliation
+// path: if our local DB lost a row (webhook never arrived because
+// STRIPE_WEBHOOK_SECRET wasn't set, network blip, etc.), Stripe is
+// the source of truth and we re-import from there.
+func (s *StripeClient) FindAgentFeatureSubscription(customerID, agentID, feature string) (*stripe.Subscription, error) {
+ iter := subscription.List(&stripe.SubscriptionListParams{
+ Customer: stripe.String(customerID),
+ Status: stripe.String("all"), // include past_due/incomplete; caller decides
+ })
+ for iter.Next() {
+ sub := iter.Subscription()
+ if sub.Metadata == nil {
+ continue
+ }
+ if sub.Metadata["agent_id"] == agentID && sub.Metadata["feature"] == feature {
+ // Return the first (most recent — Stripe lists newest-first).
+ // Caller handles status filtering.
+ return sub, nil
+ }
+ }
+ if err := iter.Err(); err != nil {
+ return nil, fmt.Errorf("list subscriptions: %w", err)
+ }
+ return nil, nil
+}
+
+// CancelAgentFeatureSubscription cancels a Stripe subscription. By
+// default cancels at period end so the customer keeps the feature
+// until the end of what they've paid for. Pass immediate=true to cut
+// service off now (used by the disconnect-on-payment-failure flow).
+func (s *StripeClient) CancelAgentFeatureSubscription(subscriptionID string, immediate bool) (*stripe.Subscription, error) {
+ if immediate {
+ sub, err := subscription.Cancel(subscriptionID, nil)
+ if err != nil {
+ return nil, fmt.Errorf("cancel subscription: %w", err)
+ }
+ return sub, nil
+ }
+ sub, err := subscription.Update(subscriptionID, &stripe.SubscriptionParams{
+ CancelAtPeriodEnd: stripe.Bool(true),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("schedule subscription cancel: %w", err)
+ }
+ return sub, nil
+}
+
// ListInvoices returns past invoices for a customer.
func (s *StripeClient) ListInvoices(customerID string, limit int) ([]*stripe.Invoice, error) {
params := &stripe.InvoiceListParams{
diff --git a/internal/config/config.go b/internal/config/config.go
index 564302ed..4f98a97f 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -106,6 +106,10 @@ type Config struct {
StripeSuccessURL string
StripeCancelURL string
+ // Per-agent paywalled-feature prices (set in Stripe dashboard, referenced
+ // by ID here). Empty = feature ungated on this deployment (dev mode).
+ StripeTelegramAgentPriceID string
+
// Segment analytics — if set, GB-minute usage events are shipped per org.
SegmentWriteKey string
@@ -205,8 +209,9 @@ func Load() (*Config, error) {
MaxWorkersPerRegion: envOrDefaultInt("OPENSANDBOX_MAX_WORKERS", 10),
IdleReserveWorkers: envOrDefaultInt("OPENSANDBOX_IDLE_RESERVE", 1),
- StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),
- StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),
+ StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),
+ StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),
+ StripeTelegramAgentPriceID: os.Getenv("STRIPE_TELEGRAM_AGENT_PRICE_ID"),
StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),
StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),
diff --git a/internal/db/migrations/032_agent_subscriptions.up.sql b/internal/db/migrations/032_agent_subscriptions.up.sql
new file mode 100644
index 00000000..1ef4c1ce
--- /dev/null
+++ b/internal/db/migrations/032_agent_subscriptions.up.sql
@@ -0,0 +1,39 @@
+-- Per-agent paid feature subscriptions.
+--
+-- Each row represents one Stripe subscription gating one feature on one
+-- agent (e.g. Telegram channel). Modeled as a separate table — not
+-- columns on `orgs` — because:
+-- - agent IDs are owned by sessions-api (text, not a UUID FK).
+-- - more features (Discord, Slack, etc.) will land here without
+-- adding columns.
+-- - terminal subscriptions (canceled, past_due) need to be retained
+-- for billing history without polluting active-state queries.
+--
+-- The (org_id, agent_id, feature) tuple is unique among non-terminal
+-- rows — partial unique index below — so a single agent can be
+-- "subscribed to telegram" only once at a time, but historic rows
+-- coexist for audit.
+CREATE TABLE agent_subscriptions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
+ agent_id TEXT NOT NULL,
+ feature TEXT NOT NULL, -- 'telegram', future: 'discord', 'slack', ...
+ stripe_customer_id TEXT NOT NULL,
+ stripe_subscription_id TEXT NOT NULL,
+ stripe_price_id TEXT NOT NULL,
+ status TEXT NOT NULL, -- 'active' | 'trialing' | 'past_due' | 'canceled' | 'incomplete' | 'incomplete_expired' | 'unpaid'
+ current_period_end TIMESTAMPTZ,
+ cancel_at_period_end BOOLEAN NOT NULL DEFAULT FALSE,
+ canceled_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- One active row per (agent, feature). Terminal rows can stack so
+-- billing history is preserved across resubscriptions.
+CREATE UNIQUE INDEX agent_subscriptions_active_per_feature
+ ON agent_subscriptions (agent_id, feature)
+ WHERE status NOT IN ('canceled', 'incomplete_expired', 'unpaid');
+
+CREATE INDEX agent_subscriptions_org ON agent_subscriptions (org_id);
+CREATE INDEX agent_subscriptions_stripe_sub ON agent_subscriptions (stripe_subscription_id);
diff --git a/internal/db/store.go b/internal/db/store.go
index 238f640f..bf9cc35f 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -125,6 +125,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{32, "migrations/029_orgs_max_memory_gb.up.sql"},
{33, "migrations/030_billable_events.up.sql"},
{34, "migrations/031_orgs_billing_mode.up.sql"},
+ {35, "migrations/032_agent_subscriptions.up.sql"},
}
for _, m := range migrations {
@@ -2117,3 +2118,169 @@ func (s *Store) DecryptSecretEntries(ctx context.Context, storeID uuid.UUID) ([]
}
return secrets, nil
}
+
+// --- Agent feature subscriptions (per-agent paywalled features) ---
+
+type AgentSubscription struct {
+ ID uuid.UUID `json:"id"`
+ OrgID uuid.UUID `json:"orgId"`
+ AgentID string `json:"agentId"`
+ Feature string `json:"feature"`
+ StripeCustomerID string `json:"stripeCustomerId"`
+ StripeSubscriptionID string `json:"stripeSubscriptionId"`
+ StripePriceID string `json:"stripePriceId"`
+ Status string `json:"status"`
+ CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"`
+ CancelAtPeriodEnd bool `json:"cancelAtPeriodEnd"`
+ CanceledAt *time.Time `json:"canceledAt,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// AgentSubscriptionIsActive returns true for statuses where the feature
+// should be enabled. Mirrors the partial-unique-index condition in
+// migration 032; keep them in sync.
+func AgentSubscriptionIsActive(status string) bool {
+ switch status {
+ case "active", "trialing", "past_due", "incomplete":
+ // past_due/incomplete are grace-period states — Stripe still
+ // considers them billable. We let the bot run during grace and
+ // rely on the webhook to flip to canceled when Stripe gives up.
+ return true
+ default:
+ return false
+ }
+}
+
+// GetActiveAgentSubscription returns the single active subscription for
+// (agent_id, feature) if one exists. Used for entitlement checks.
+func (s *Store) GetActiveAgentSubscription(ctx context.Context, agentID, feature string) (*AgentSubscription, error) {
+ var sub AgentSubscription
+ var currentPeriodEnd, canceledAt *time.Time
+ err := s.pool.QueryRow(ctx, `
+ SELECT id, org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,
+ stripe_price_id, status, current_period_end, cancel_at_period_end,
+ canceled_at, created_at, updated_at
+ FROM agent_subscriptions
+ WHERE agent_id = $1 AND feature = $2
+ AND status NOT IN ('canceled','incomplete_expired','unpaid')
+ LIMIT 1`, agentID, feature).Scan(
+ &sub.ID, &sub.OrgID, &sub.AgentID, &sub.Feature, &sub.StripeCustomerID,
+ &sub.StripeSubscriptionID, &sub.StripePriceID, &sub.Status,
+ &currentPeriodEnd, &sub.CancelAtPeriodEnd, &canceledAt,
+ &sub.CreatedAt, &sub.UpdatedAt,
+ )
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ sub.CurrentPeriodEnd = currentPeriodEnd
+ sub.CanceledAt = canceledAt
+ return &sub, nil
+}
+
+// ListAgentSubscriptionsByOrg returns all subscriptions for an org, used
+// by the billing page's per-agent-features section.
+func (s *Store) ListAgentSubscriptionsByOrg(ctx context.Context, orgID uuid.UUID) ([]AgentSubscription, error) {
+ rows, err := s.pool.Query(ctx, `
+ SELECT id, org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,
+ stripe_price_id, status, current_period_end, cancel_at_period_end,
+ canceled_at, created_at, updated_at
+ FROM agent_subscriptions
+ WHERE org_id = $1
+ ORDER BY created_at DESC`, orgID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var subs []AgentSubscription
+ for rows.Next() {
+ var sub AgentSubscription
+ var currentPeriodEnd, canceledAt *time.Time
+ if err := rows.Scan(
+ &sub.ID, &sub.OrgID, &sub.AgentID, &sub.Feature, &sub.StripeCustomerID,
+ &sub.StripeSubscriptionID, &sub.StripePriceID, &sub.Status,
+ &currentPeriodEnd, &sub.CancelAtPeriodEnd, &canceledAt,
+ &sub.CreatedAt, &sub.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ sub.CurrentPeriodEnd = currentPeriodEnd
+ sub.CanceledAt = canceledAt
+ subs = append(subs, sub)
+ }
+ return subs, rows.Err()
+}
+
+// GetAgentSubscriptionByStripeID is the lookup path used by the Stripe
+// webhook handler — it gets a subscription_id from Stripe and needs to
+// find the matching internal row.
+func (s *Store) GetAgentSubscriptionByStripeID(ctx context.Context, stripeSubscriptionID string) (*AgentSubscription, error) {
+ var sub AgentSubscription
+ var currentPeriodEnd, canceledAt *time.Time
+ err := s.pool.QueryRow(ctx, `
+ SELECT id, org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,
+ stripe_price_id, status, current_period_end, cancel_at_period_end,
+ canceled_at, created_at, updated_at
+ FROM agent_subscriptions
+ WHERE stripe_subscription_id = $1
+ LIMIT 1`, stripeSubscriptionID).Scan(
+ &sub.ID, &sub.OrgID, &sub.AgentID, &sub.Feature, &sub.StripeCustomerID,
+ &sub.StripeSubscriptionID, &sub.StripePriceID, &sub.Status,
+ &currentPeriodEnd, &sub.CancelAtPeriodEnd, &canceledAt,
+ &sub.CreatedAt, &sub.UpdatedAt,
+ )
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ sub.CurrentPeriodEnd = currentPeriodEnd
+ sub.CanceledAt = canceledAt
+ return &sub, nil
+}
+
+// CreateAgentSubscription records a fresh Stripe subscription. Caller
+// is responsible for ensuring the Stripe-side object exists first.
+func (s *Store) CreateAgentSubscription(ctx context.Context, sub AgentSubscription) (*AgentSubscription, error) {
+ row := s.pool.QueryRow(ctx, `
+ INSERT INTO agent_subscriptions
+ (org_id, agent_id, feature, stripe_customer_id, stripe_subscription_id,
+ stripe_price_id, status, current_period_end, cancel_at_period_end)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
+ RETURNING id, created_at, updated_at`,
+ sub.OrgID, sub.AgentID, sub.Feature, sub.StripeCustomerID,
+ sub.StripeSubscriptionID, sub.StripePriceID, sub.Status,
+ sub.CurrentPeriodEnd, sub.CancelAtPeriodEnd,
+ )
+ if err := row.Scan(&sub.ID, &sub.CreatedAt, &sub.UpdatedAt); err != nil {
+ return nil, err
+ }
+ return &sub, nil
+}
+
+// UpdateAgentSubscriptionFromStripe applies status/period/cancel fields
+// from a Stripe webhook event onto the local row. Identifies by stripe
+// subscription_id.
+func (s *Store) UpdateAgentSubscriptionFromStripe(
+ ctx context.Context,
+ stripeSubscriptionID, status string,
+ currentPeriodEnd *time.Time,
+ cancelAtPeriodEnd bool,
+ canceledAt *time.Time,
+) error {
+ _, err := s.pool.Exec(ctx, `
+ UPDATE agent_subscriptions
+ SET status = $2,
+ current_period_end = $3,
+ cancel_at_period_end = $4,
+ canceled_at = $5,
+ updated_at = now()
+ WHERE stripe_subscription_id = $1`,
+ stripeSubscriptionID, status, currentPeriodEnd, cancelAtPeriodEnd, canceledAt,
+ )
+ return err
+}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 2e1f20e0..d31456b2 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -449,6 +449,68 @@ export const getAgentLogs = (agentId: string, tail = 300) =>
`/agents/${encodeURIComponent(agentId)}/logs?tail=${tail}`,
)
+// ── Per-agent paywalled feature subscriptions (Telegram et al) ──
+
+export type EntitlementReason = 'ungated' | 'subscription_required' | string
+
+export interface AgentEntitlement {
+ feature: string
+ entitled: boolean
+ reason?: EntitlementReason
+ price_monthly_cents?: number
+ status?: string
+ current_period_end?: string
+ cancel_at_period_end?: boolean
+ stripe_subscription_id?: string
+}
+
+export const listAgentEntitlements = (agentId: string) =>
+ apiFetch<{ agent_id: string; entitlements: AgentEntitlement[] }>(
+ `/agents/${encodeURIComponent(agentId)}/entitlements`,
+ )
+
+export type SubscribeResult =
+ | { status: 'active'; feature: string; agent_id: string; subscription_id: string; price_id: string }
+ | { status: 'already_subscribed'; feature: string; agent_id: string; subscription_id: string }
+ | { status: 'ungated'; feature: string; agent_id: string }
+ | { status: 'checkout_required'; feature: string; agent_id: string; checkout_url: string }
+
+export const subscribeAgentFeature = (agentId: string, feature: string) =>
+ apiFetch<SubscribeResult>(
+ `/agents/${encodeURIComponent(agentId)}/subscriptions/${encodeURIComponent(feature)}`,
+ { method: 'POST' },
+ )
+
+export interface OrgAgentSubscription {
+ agent_id: string
+ feature: string
+ status: string
+ active: boolean
+ price_monthly_cents: number
+ current_period_end?: string
+ cancel_at_period_end: boolean
+ canceled_at?: string
+ created_at: string
+ stripe_subscription_id: string
+}
+
+export const listOrgAgentSubscriptions = () =>
+ apiFetch<{ subscriptions: OrgAgentSubscription[] }>(
+ '/billing/agent-subscriptions',
+ )
+
+export const cancelAgentFeature = (agentId: string, feature: string) =>
+ apiFetch<{
+ status: string
+ feature: string
+ agent_id: string
+ cancel_at_period_end: boolean
+ current_period_end?: string
+ }>(
+ `/agents/${encodeURIComponent(agentId)}/subscriptions/${encodeURIComponent(feature)}`,
+ { method: 'DELETE' },
+ )
+
/**
* Streams a chat turn to an agent's instance and yields parsed SSE events
* as they arrive. The upstream (sessions-api POST /v1/agents/:id/instances/:id/messages)
@@ -461,19 +523,35 @@ export type ChatEvent =
| { type: 'done' }
| { type: 'raw'; data: string }
+export interface ChatTurn { role: 'user' | 'assistant' | 'system'; content: string }
+
export async function* streamAgentChat(
agentId: string,
instanceId: string,
content: string,
conversationId?: string,
+ history?: ChatTurn[],
): AsyncGenerator<ChatEvent, void, unknown> {
+ // OpenAI-style chat-completions is stateless: the gateway needs the
+ // full conversation each turn to have any memory of prior messages.
+ // Caller passes `history` (already including the new user turn).
+ // For backwards compat with older callers, we still accept `content`
+ // as a single-turn shortcut.
+ const body: Record<string, unknown> = {}
+ if (history && history.length > 0) {
+ body.messages = history
+ } else {
+ body.content = content
+ }
+ if (conversationId) body.conversation_id = conversationId
+
const res = await fetch(
`/api/dashboard/agents/${encodeURIComponent(agentId)}/instances/${encodeURIComponent(instanceId)}/messages`,
{
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(conversationId ? { content, conversation_id: conversationId } : { content }),
+ body: JSON.stringify(body),
},
)
if (!res.ok || !res.body) {
diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsx
index e2aca29e..4ac3167b 100644
--- a/web/src/pages/AgentDetail.tsx
+++ b/web/src/pages/AgentDetail.tsx
@@ -13,6 +13,10 @@ import {
getAgentOperations,
getAgentLogs,
streamAgentChat,
+ listAgentEntitlements,
+ subscribeAgentFeature,
+ cancelAgentFeature,
+ type AgentEntitlement,
type AgentDetail,
type AgentOperation,
type AgentEvent as AgentEventRow,
@@ -33,6 +37,7 @@ export default function AgentDetailPage() {
const { agentId = '' } = useParams<{ agentId: string }>()
const navigate = useNavigate()
const [detail, setDetail] = useState<AgentDetail | null>(null)
+ const [entitlementsByFeature, setEntitlementsByFeature] = useState<Record<string, AgentEntitlement>>({})
const [loading, setLoading] = useState(true)
const [tab, setTab] = useState<Tab>('overview')
const [banner, setBanner] = useState<Banner>(null)
@@ -42,6 +47,16 @@ export default function AgentDetailPage() {
try {
const d = await getAgent(agentId)
setDetail(d)
+ // Refresh entitlements alongside detail so the header upgrade
+ // pill stays in sync with the latest subscription state.
+ try {
+ const e = await listAgentEntitlements(agentId)
+ const map: Record<string, AgentEntitlement> = {}
+ for (const ent of e.entitlements) map[ent.feature] = ent
+ setEntitlementsByFeature(map)
+ } catch {
+ // best-effort — don't block the page on entitlement fetch
+ }
} catch (err) {
setBanner({ kind: 'error', text: `Failed to load agent: ${(err as Error).message}` })
} finally {
@@ -180,6 +195,34 @@ export default function AgentDetailPage() {
)}
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
+ {(() => {
+ const tg = entitlementsByFeature.telegram
+ const needsUpgrade = tg && tg.entitled === false && tg.reason !== 'ungated'
+ if (!needsUpgrade) return null
+ const priceCents = tg.price_monthly_cents ?? 2000
+ return (
+ <button
+ onClick={() => setTab('channels')}
+ style={{
+ background: 'rgba(99,102,241,0.08)',
+ color: 'var(--accent-indigo, #818cf8)',
+ border: '1px solid rgba(99,102,241,0.35)',
+ padding: '6px 12px',
+ borderRadius: 999,
+ cursor: 'pointer',
+ fontSize: 12,
+ fontFamily: 'var(--font-body)',
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: 6,
+ }}
+ title={`Subscribe to Telegram channel for $${(priceCents / 100).toFixed(0)}/mo`}
+ >
+ <span style={{ fontSize: 11 }}>★</span>
+ Upgrade — ${(priceCents / 100).toFixed(0)}/mo
+ </button>
+ )
+ })()}
<button
onClick={() =>
act('restart core', () => restartAgent(agentId), 'Core restarted.')
@@ -639,12 +682,22 @@ function ChatTab({
if (!input.trim() || !instanceId || streaming) return
const userMsg = input.trim()
setInput('')
+ // Build the full history we'll send to the gateway BEFORE we mutate
+ // local state. Includes every prior user/assistant turn (skipping
+ // 'system' rows we generate locally for error display) plus the
+ // new user turn. Empty-text turns are dropped — the placeholder
+ // assistant bubble we add for UX must not be sent.
+ const apiHistory = history
+ .filter((m) => (m.role === 'user' || m.role === 'assistant') && m.text.length > 0)
+ .map((m) => ({ role: m.role as 'user' | 'assistant', content: m.text }))
+ apiHistory.push({ role: 'user', content: userMsg })
+
setHistory((h) => [...h, { role: 'user', text: userMsg }, { role: 'assistant', text: '' }])
setStreaming(true)
let receivedText = false
let saw_done = false
try {
- for await (const ev of streamAgentChat(agentId, instanceId, userMsg, conversationId)) {
+ for await (const ev of streamAgentChat(agentId, instanceId, userMsg, conversationId, apiHistory)) {
if (ev.type === 'text' && ev.content) {
receivedText = true
setHistory((h) => {
@@ -775,9 +828,28 @@ function ChannelsTab({
onAction: <T>(label: string, fn: () => Promise<T>, ok: string) => Promise<void>
}) {
const [telegramModal, setTelegramModal] = useState(false)
+ const [paywallModal, setPaywallModal] = useState(false)
+ const [subscribing, setSubscribing] = useState(false)
+ const [entitlements, setEntitlements] = useState<Record<string, AgentEntitlement>>({})
const telegramConnected = detail.channels.some((c) => c.name === 'telegram')
const canMutate = detail.core !== null
+ async function refreshEntitlements() {
+ try {
+ const res = await listAgentEntitlements(detail.id)
+ const map: Record<string, AgentEntitlement> = {}
+ for (const e of res.entitlements) map[e.feature] = e
+ setEntitlements(map)
+ } catch {
+ // best-effort: leave previous state
+ }
+ }
+
+ useEffect(() => {
+ void refreshEntitlements()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [detail.id])
+
if (!canMutate) {
return (
<p style={{ fontSize: 13, color: 'var(--text-tertiary)' }}>
@@ -786,6 +858,50 @@ function ChannelsTab({
)
}
+ const telegramEntitlement = entitlements.telegram
+ const telegramEntitled = telegramEntitlement?.entitled !== false // undefined treated as entitled (loading) to avoid flash
+ const telegramUngated = telegramEntitlement?.reason === 'ungated'
+ const telegramPriceCents = telegramEntitlement?.price_monthly_cents ?? 2000
+
+ async function handleTelegramAction() {
+ if (telegramConnected) {
+ // Already connected — manage flow
+ setTelegramModal(true)
+ return
+ }
+ if (!telegramEntitled) {
+ // Show paywall first
+ setPaywallModal(true)
+ return
+ }
+ // Entitled but not connected — connect flow
+ setTelegramModal(true)
+ }
+
+ async function handleSubscribe() {
+ setSubscribing(true)
+ try {
+ const result = await subscribeAgentFeature(detail.id, 'telegram')
+ if (result.status === 'checkout_required') {
+ // Bounce to Stripe Checkout for first-time card capture.
+ // Intentional: we lose the "open the connect modal next" flow,
+ // because Stripe redirects out and back. The user comes back
+ // to /agents/:id/?success=true and has to click Connect again
+ // — entitlement check will pass at that point.
+ window.location.href = result.checkout_url
+ return
+ }
+ // active / already_subscribed / ungated → entitled now
+ await refreshEntitlements()
+ setPaywallModal(false)
+ setTelegramModal(true)
+ } catch (err) {
+ alert(`Subscription failed: ${(err as Error).message}`)
+ } finally {
+ setSubscribing(false)
+ }
+ }
+
return (
<>
<div style={integrationGrid}>
@@ -794,13 +910,25 @@ function ChannelsTab({
accent="sky"
icon="✈️"
name="Telegram"
- description="Talk to the agent through a Telegram bot."
+ description={
+ telegramUngated
+ ? 'Talk to the agent through a Telegram bot. (Paywall not configured on this deployment.)'
+ : telegramEntitled
+ ? 'Talk to the agent through a Telegram bot.'
+ : `Talk to the agent through a Telegram bot. $${(telegramPriceCents / 100).toFixed(0)}/mo per agent.`
+ }
status={telegramConnected ? 'connected' : 'available'}
- actionLabel={telegramConnected ? 'Configure' : 'Connect'}
+ actionLabel={
+ telegramConnected
+ ? 'Configure'
+ : telegramEntitled
+ ? 'Connect'
+ : `Subscribe & connect — $${(telegramPriceCents / 100).toFixed(0)}/mo`
+ }
actionTone={telegramConnected ? 'secondary' : 'primary'}
busy={acting === 'connect telegram' || acting === 'disconnect telegram'}
disabled={!!acting}
- onAction={() => setTelegramModal(true)}
+ onAction={handleTelegramAction}
/>
{COMING_SOON_CHANNELS.map((it) => (
@@ -816,9 +944,22 @@ function ChannelsTab({
))}
</div>
+ {paywallModal && (
+ <TelegramPaywallModal
+ priceCents={telegramPriceCents}
+ subscribing={subscribing}
+ onClose={() => setPaywallModal(false)}
+ onSubscribe={handleSubscribe}
+ />
+ )}
+
{telegramModal && (
<TelegramConnectModal
alreadyConnected={telegramConnected}
+ ungated={telegramUngated}
+ subscriptionActive={!!entitlements.telegram?.entitled && !telegramUngated}
+ subscriptionWillCancel={!!entitlements.telegram?.cancel_at_period_end}
+ subscriptionRenewsAt={entitlements.telegram?.current_period_end}
onClose={() => setTelegramModal(false)}
onSubmit={async (token) => {
setTelegramModal(false)
@@ -838,12 +979,78 @@ function ChannelsTab({
'Telegram disconnected.',
)
}}
+ onCancelSubscription={async () => {
+ try {
+ await cancelAgentFeature(detail.id, 'telegram')
+ await refreshEntitlements()
+ setTelegramModal(false)
+ alert('Subscription scheduled to cancel at period end. Telegram remains active until then.')
+ } catch (err) {
+ alert(`Cancel failed: ${(err as Error).message}`)
+ }
+ }}
/>
)}
</>
)
}
+function TelegramPaywallModal({
+ priceCents,
+ subscribing,
+ onClose,
+ onSubscribe,
+}: {
+ priceCents: number
+ subscribing: boolean
+ onClose: () => void
+ onSubscribe: () => Promise<void>
+}) {
+ return (
+ <div
+ onClick={onClose}
+ style={{
+ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100,
+ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
+ }}
+ >
+ <div
+ onClick={(e) => e.stopPropagation()}
+ style={{
+ background: 'var(--bg-deep)',
+ border: '1px solid var(--border-subtle)',
+ borderRadius: 12, width: '100%', maxWidth: 460, padding: 22,
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
+ <h2 style={{ fontSize: 16, margin: 0, fontFamily: 'var(--font-display)' }}>Subscribe to Telegram for this agent</h2>
+ <button onClick={onClose} style={iconButton}>×</button>
+ </div>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.6, marginBottom: 16 }}>
+ Connecting Telegram to a managed agent costs <b>${(priceCents / 100).toFixed(0)}/month</b>. Each agent
+ you connect to Telegram is billed separately. Cancel any time — service runs to the end of the
+ current billing period.
+ </div>
+ <div style={{
+ background: 'rgba(99,102,241,0.08)',
+ border: '1px solid rgba(99,102,241,0.2)',
+ borderRadius: 6, padding: '10px 12px',
+ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 16,
+ }}>
+ Your card on file will be charged immediately and prorated to the end of the current billing
+ period. If no card is on file, Stripe Checkout will collect one.
+ </div>
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
+ <button type="button" onClick={onClose} style={secondaryButton}>Cancel</button>
+ <button onClick={() => void onSubscribe()} disabled={subscribing} style={primaryButton}>
+ {subscribing ? <BusyLabel text="Subscribing…" /> : `Subscribe — $${(priceCents / 100).toFixed(0)}/mo`}
+ </button>
+ </div>
+ </div>
+ </div>
+ )
+}
+
function PluginsTab({
detail,
acting,
@@ -1045,14 +1252,24 @@ function IntegrationCard({
function TelegramConnectModal({
alreadyConnected,
+ ungated,
+ subscriptionActive,
+ subscriptionWillCancel,
+ subscriptionRenewsAt,
onClose,
onSubmit,
onDisconnect,
+ onCancelSubscription,
}: {
alreadyConnected: boolean
+ ungated: boolean
+ subscriptionActive: boolean
+ subscriptionWillCancel: boolean
+ subscriptionRenewsAt?: string
onClose: () => void
onSubmit: (token: string) => void | Promise<void>
onDisconnect: () => void | Promise<void>
+ onCancelSubscription: () => void | Promise<void>
}) {
const [token, setToken] = useState('')
const title = alreadyConnected ? 'Configure Telegram' : 'Connect Telegram'
@@ -1084,6 +1301,53 @@ function TelegramConnectModal({
</p>
)}
+ {ungated && (
+ <div style={{
+ background: 'rgba(251,191,36,0.08)',
+ border: '1px solid rgba(251,191,36,0.25)',
+ borderRadius: 6, padding: '8px 12px', marginBottom: 14,
+ fontSize: 12, color: 'var(--text-secondary)',
+ }}>
+ <b style={{ color: '#fbbf24' }}>Not gated yet</b> on this deployment — connect proceeds without
+ a subscription. Set <code style={codeInline}>STRIPE_TELEGRAM_AGENT_PRICE_ID</code> on the server
+ to enable the paywall.
+ </div>
+ )}
+
+ {!ungated && subscriptionActive && (
+ <div style={{
+ background: 'rgba(52,211,153,0.08)',
+ border: '1px solid rgba(52,211,153,0.2)',
+ borderRadius: 6, padding: '8px 12px', marginBottom: 14,
+ fontSize: 12, color: 'var(--text-secondary)',
+ }}>
+ {subscriptionWillCancel ? (
+ <>
+ Subscription <b>scheduled to cancel</b>
+ {subscriptionRenewsAt && ` on ${new Date(subscriptionRenewsAt).toLocaleDateString()}`}
+ . Telegram remains active until then.
+ </>
+ ) : (
+ <>
+ Subscription <b style={{ color: '#34d399' }}>active</b>
+ {subscriptionRenewsAt && ` · renews ${new Date(subscriptionRenewsAt).toLocaleDateString()}`}
+ .{' '}
+ <button
+ type="button"
+ onClick={() => {
+ if (window.confirm('Cancel Telegram subscription? Service continues until period end.')) {
+ void onCancelSubscription()
+ }
+ }}
+ style={{ background: 'none', border: 'none', color: 'var(--accent-rose, #f87171)', cursor: 'pointer', padding: 0, fontSize: 12, textDecoration: 'underline' }}
+ >
+ Cancel subscription
+ </button>
+ </>
+ )}
+ </div>
+ )}
+
<form
onSubmit={(e) => { e.preventDefault(); if (token.trim()) void onSubmit(token.trim()) }}
style={{ display: 'grid', gap: 14 }}
@@ -1105,7 +1369,7 @@ function TelegramConnectModal({
<button
type="button"
onClick={() => {
- if (window.confirm('Disconnect Telegram from this agent?')) {
+ if (window.confirm('Disconnect Telegram from this agent? Subscription remains active until cancelled separately.')) {
void onDisconnect()
}
}}
diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsx
index d913440e..40c78eaa 100644
--- a/web/src/pages/Billing.tsx
+++ b/web/src/pages/Billing.tsx
@@ -1,14 +1,62 @@
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
+import { Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
getBilling, billingSetup, billingPortal, getBillingInvoices, redeemPromoCode,
- type StripeInvoice,
+ listOrgAgentSubscriptions, listAgents, cancelAgentFeature,
+ type StripeInvoice, type OrgAgentSubscription, type Agent,
} from '../api/client'
+type Tab = 'sandboxes' | 'agents' | 'invoices'
+
export default function Billing() {
+ const [tab, setTab] = useState<Tab>('sandboxes')
+
+ return (
+ <div>
+ <div style={{ marginBottom: 24 }}>
+ <h1 className="page-title">Billing</h1>
+ <p className="page-subtitle">Manage your plan, per-agent subscriptions, and invoices</p>
+ </div>
+
+ {/* Tabs */}
+ <div style={{ display: 'flex', borderBottom: '1px solid var(--border-subtle)', marginBottom: 18, gap: 4 }}>
+ {(['sandboxes', 'agents', 'invoices'] as Tab[]).map((t) => (
+ <button
+ key={t}
+ onClick={() => setTab(t)}
+ style={{
+ background: 'none',
+ border: 'none',
+ borderBottom: tab === t ? '2px solid var(--accent-indigo)' : '2px solid transparent',
+ padding: '10px 14px',
+ color: tab === t ? 'var(--text-primary)' : 'var(--text-secondary)',
+ fontSize: 13,
+ fontFamily: 'var(--font-body)',
+ fontWeight: tab === t ? 600 : 400,
+ cursor: 'pointer',
+ textTransform: 'capitalize',
+ }}
+ >
+ {t}
+ </button>
+ ))}
+ </div>
+
+ {tab === 'sandboxes' && <PlanTab />}
+ {tab === 'agents' && <AgentsTab />}
+ {tab === 'invoices' && <InvoicesTab />}
+ </div>
+ )
+}
+
+// ───────────── Plan & Usage tab ─────────────
+
+function PlanTab() {
const queryClient = useQueryClient()
- const { data: billing, isLoading } = useQuery({ queryKey: ['billing'], queryFn: getBilling, refetchInterval: 30_000 })
- const { data: invoiceData } = useQuery({ queryKey: ['invoices'], queryFn: () => getBillingInvoices() })
+ const { data: billing, isLoading } = useQuery({
+ queryKey: ['billing'], queryFn: getBilling, refetchInterval: 30_000,
+ })
const [promoCode, setPromoCode] = useState('')
const [redeemSuccess, setRedeemSuccess] = useState('')
@@ -17,12 +65,10 @@ export default function Billing() {
mutationFn: billingSetup,
onSuccess: (data) => { window.location.href = data.url },
})
-
const portalMutation = useMutation({
mutationFn: billingPortal,
onSuccess: (data) => { window.location.href = data.url },
})
-
const redeemMutation = useMutation({
mutationFn: () => redeemPromoCode(promoCode),
onSuccess: (data) => {
@@ -35,226 +81,489 @@ export default function Billing() {
const isPro = billing?.plan === 'pro'
- return (
- <div>
- <div style={{ marginBottom: 32 }}>
- <h1 className="page-title">Billing</h1>
- <p className="page-subtitle">Manage your plan and payment settings</p>
+ if (isLoading) {
+ return (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
+ <div className="loading-spinner" />
</div>
+ )
+ }
- {isLoading ? (
- <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
- <div className="loading-spinner" />
+ return (
+ <>
+ {/* Plan Card */}
+ <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
+ Current Plan
+ </span>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
+ <span className="metric-value" style={{
+ fontSize: 36, fontWeight: 700,
+ color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',
+ }}>
+ {isPro ? 'Pro' : 'Free'}
+ </span>
+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ {isPro
+ ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`
+ : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, up to 4GB / 1 vCPU`}
+ </span>
</div>
- ) : (
- <>
- {/* Plan Card */}
- <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>
- <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
- Current Plan
- </span>
- <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
- <span className="metric-value" style={{
- fontSize: 36, fontWeight: 700,
- color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',
- }}>
- {isPro ? 'Pro' : 'Free'}
- </span>
- <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
- {isPro
- ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`
- : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, up to 4GB / 1 vCPU`}
- </span>
- </div>
- {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (
- <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>
- ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining
- </div>
- )}
+ {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (
+ <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>
+ ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining
+ </div>
+ )}
- {!isPro && billing != null && (
- <div style={{ marginTop: 12 }}>
- {billing.freeCreditsRemainingCents > 0 ? (
- <div style={{
- fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-mono)',
- color: 'var(--accent-emerald)', marginBottom: 12,
- }}>
- ${(billing.freeCreditsRemainingCents / 100).toFixed(2)} free trial credit remaining
- </div>
- ) : (
- <div style={{
- fontSize: 13, color: 'var(--accent-rose)', marginBottom: 12,
- display: 'flex', alignItems: 'center', gap: 6,
- }}>
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
- </svg>
- Free trial credits exhausted — upgrade to continue using sandboxes
- </div>
- )}
-
- <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>
- Upgrade to Pro for an additional $30 free credit and larger machine sizes
- </div>
- <button
- onClick={() => setupMutation.mutate()}
- disabled={setupMutation.isPending}
- style={{
- padding: '10px 24px', fontSize: 14, fontWeight: 600,
- fontFamily: 'var(--font-body)', cursor: 'pointer',
- border: 'none', borderRadius: 'var(--radius-sm)',
- background: 'var(--accent-indigo)', color: '#fff',
- opacity: setupMutation.isPending ? 0.6 : 1,
- }}
- >
- {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}
- </button>
- {setupMutation.isError && (
- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
- {(setupMutation.error as Error).message}
- </p>
- )}
+ {!isPro && billing != null && (
+ <div style={{ marginTop: 12 }}>
+ {billing.freeCreditsRemainingCents > 0 ? (
+ <div style={{
+ fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-mono)',
+ color: 'var(--accent-emerald)', marginBottom: 12,
+ }}>
+ ${(billing.freeCreditsRemainingCents / 100).toFixed(2)} free trial credit remaining
</div>
- )}
-
- {isPro && (
+ ) : (
<div style={{
- fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,
+ fontSize: 13, color: 'var(--accent-rose)', marginBottom: 12,
display: 'flex', alignItems: 'center', gap: 6,
}}>
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>
- Payment method on file — billed monthly via Stripe
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
+ </svg>
+ Free trial credits exhausted — upgrade to continue using sandboxes
</div>
)}
- <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>
- Need more concurrency?{' '}
- <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"
- style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>
- Talk to us
- </a>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>
+ Upgrade to Pro for an additional $30 free credit and larger machine sizes
</div>
+ <button
+ onClick={() => setupMutation.mutate()}
+ disabled={setupMutation.isPending}
+ style={{
+ padding: '10px 24px', fontSize: 14, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: 'none', borderRadius: 'var(--radius-sm)',
+ background: 'var(--accent-indigo)', color: '#fff',
+ opacity: setupMutation.isPending ? 0.6 : 1,
+ }}
+ >
+ {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}
+ </button>
+ {setupMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
+ {(setupMutation.error as Error).message}
+ </p>
+ )}
</div>
+ )}
- {/* Stripe Billing Portal CTA (pro only) */}
- {isPro && (
- <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>
- <span className="section-title" style={{ marginBottom: 10, display: 'block' }}>
- Usage & Invoices
- </span>
- <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 14, lineHeight: 1.5 }}>
- View your current-cycle usage, invoices, and manage your payment method on Stripe.
- </p>
- <button
- onClick={() => portalMutation.mutate()}
- disabled={portalMutation.isPending}
- style={{
- padding: '10px 20px', fontSize: 13, fontWeight: 600,
- fontFamily: 'var(--font-body)', cursor: 'pointer',
- border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)',
- background: 'rgba(255,255,255,0.02)', color: 'var(--text-primary)',
- opacity: portalMutation.isPending ? 0.6 : 1,
- }}
- >
- {portalMutation.isPending ? 'Opening Stripe…' : 'Open Stripe billing portal ↗'}
- </button>
- {portalMutation.isError && (
- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
- {(portalMutation.error as Error).message}
- </p>
- )}
- </div>
- )}
+ {isPro && (
+ <div style={{
+ fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,
+ display: 'flex', alignItems: 'center', gap: 6,
+ }}>
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>
+ Payment method on file — billed monthly via Stripe
+ </div>
+ )}
- {/* Redeem Promotion Code (pro only) */}
- {isPro && (
- <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>
- <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>Promotion Code</span>
- <div style={{ display: 'flex', alignItems: 'end', gap: 14 }}>
- <div>
- <label style={{ fontSize: 11, color: 'var(--text-tertiary)', display: 'block', marginBottom: 6 }}>
- Enter a promotion code to apply credit
- </label>
- <input
- className="input"
- type="text"
- placeholder="e.g. WELCOME100"
- value={promoCode}
- onChange={e => setPromoCode(e.target.value.toUpperCase())}
- style={{ width: 240, fontFamily: 'var(--font-mono)', fontSize: 13 }}
- />
- </div>
- <button
- onClick={() => redeemMutation.mutate()}
- disabled={redeemMutation.isPending || !promoCode.trim()}
- style={{
- padding: '8px 20px', fontSize: 13, fontWeight: 600,
- fontFamily: 'var(--font-body)', cursor: 'pointer',
- border: 'none', borderRadius: 'var(--radius-sm)',
- background: 'var(--accent-indigo)', color: '#fff',
- opacity: redeemMutation.isPending || !promoCode.trim() ? 0.5 : 1,
- }}
- >
- {redeemMutation.isPending ? 'Applying...' : 'Redeem'}
- </button>
- </div>
- {redeemSuccess && (
- <p style={{ fontSize: 13, color: 'var(--accent-emerald)', marginTop: 10 }}>{redeemSuccess}</p>
- )}
- {redeemMutation.isError && (
- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
- {(redeemMutation.error as Error).message}
- </p>
- )}
- </div>
+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>
+ Need more concurrency?{' '}
+ <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"
+ style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>
+ Talk to us
+ </a>
+ </div>
+ </div>
+
+ {/* Stripe Billing Portal CTA (pro only) */}
+ {isPro && (
+ <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 10, display: 'block' }}>
+ Usage & Payment Method
+ </span>
+ <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 14, lineHeight: 1.5 }}>
+ View your current-cycle usage, manage your payment method, and download invoices on Stripe.
+ </p>
+ <button
+ onClick={() => portalMutation.mutate()}
+ disabled={portalMutation.isPending}
+ style={{
+ padding: '10px 20px', fontSize: 13, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)',
+ background: 'rgba(255,255,255,0.02)', color: 'var(--text-primary)',
+ opacity: portalMutation.isPending ? 0.6 : 1,
+ }}
+ >
+ {portalMutation.isPending ? 'Opening Stripe…' : 'Open Stripe billing portal ↗'}
+ </button>
+ {portalMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
+ {(portalMutation.error as Error).message}
+ </p>
)}
+ </div>
+ )}
- {/* Invoice History (pro only) */}
- {isPro && (
- <div className="glass-card animate-in stagger-4" style={{ padding: '22px 24px' }}>
- <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>Invoices</span>
- {!invoiceData?.invoices?.length ? (
- <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
- No invoices yet — your first invoice will appear at the end of the billing period
- </div>
- ) : (
- <table className="data-table">
- <thead>
- <tr><th>Date</th><th>Number</th><th>Status</th><th>Amount</th><th></th></tr>
- </thead>
- <tbody>
- {invoiceData.invoices.map((inv: StripeInvoice) => (
- <tr key={inv.id}>
- <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
- {new Date(inv.created * 1000).toLocaleDateString()}
- </td>
- <td style={{ fontSize: 12 }}>{inv.number}</td>
- <td><InvoiceStatus status={inv.status} /></td>
- <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600 }}>
- ${(inv.amountDue / 100).toFixed(2)}
- </td>
- <td>
- {inv.hostedUrl && (
- <a href={inv.hostedUrl} target="_blank" rel="noreferrer"
- style={{ fontSize: 12, color: 'var(--accent-indigo)', textDecoration: 'none' }}>
- View
- </a>
- )}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- )}
+ {/* Redeem Promotion Code (pro only) */}
+ {isPro && (
+ <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>Promotion Code</span>
+ <div style={{ display: 'flex', alignItems: 'end', gap: 14 }}>
+ <div>
+ <label style={{ fontSize: 11, color: 'var(--text-tertiary)', display: 'block', marginBottom: 6 }}>
+ Enter a promotion code to apply credit
+ </label>
+ <input
+ className="input"
+ type="text"
+ placeholder="e.g. WELCOME100"
+ value={promoCode}
+ onChange={e => setPromoCode(e.target.value.toUpperCase())}
+ style={{ width: 240, fontFamily: 'var(--font-mono)', fontSize: 13 }}
+ />
</div>
+ <button
+ onClick={() => redeemMutation.mutate()}
+ disabled={redeemMutation.isPending || !promoCode.trim()}
+ style={{
+ padding: '8px 20px', fontSize: 13, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: 'none', borderRadius: 'var(--radius-sm)',
+ background: 'var(--accent-indigo)', color: '#fff',
+ opacity: redeemMutation.isPending || !promoCode.trim() ? 0.5 : 1,
+ }}
+ >
+ {redeemMutation.isPending ? 'Applying...' : 'Redeem'}
+ </button>
+ </div>
+ {redeemSuccess && (
+ <p style={{ fontSize: 13, color: 'var(--accent-emerald)', marginTop: 10 }}>{redeemSuccess}</p>
+ )}
+ {redeemMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
+ {(redeemMutation.error as Error).message}
+ </p>
)}
- </>
+ </div>
+ )}
+ </>
+ )
+}
+
+// ───────────── Agents tab ─────────────
+
+function AgentsTab() {
+ const queryClient = useQueryClient()
+ const { data: subsData, isLoading: subsLoading } = useQuery({
+ queryKey: ['org-agent-subscriptions'],
+ queryFn: listOrgAgentSubscriptions,
+ refetchInterval: 30_000,
+ })
+ const { data: agentsData } = useQuery({
+ queryKey: ['agents'], queryFn: listAgents,
+ })
+
+ const cancelMutation = useMutation({
+ mutationFn: ({ agentId, feature }: { agentId: string; feature: string }) =>
+ cancelAgentFeature(agentId, feature),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['org-agent-subscriptions'] })
+ },
+ })
+
+ // Index agents by ID so we can show display names instead of raw IDs.
+ const agentsById = useMemo(() => {
+ const map: Record<string, Agent> = {}
+ for (const a of agentsData?.agents ?? []) map[a.id] = a
+ return map
+ }, [agentsData])
+
+ // De-duplicate to one row per (agent_id, feature). We sort by created_at
+ // desc so the freshest row wins — covers cases where a user canceled then
+ // re-subscribed.
+ const rows = useMemo(() => {
+ const seen = new Set<string>()
+ const sorted = [...(subsData?.subscriptions ?? [])].sort((a, b) =>
+ b.created_at.localeCompare(a.created_at),
+ )
+ const out: OrgAgentSubscription[] = []
+ for (const sub of sorted) {
+ const key = `${sub.agent_id}::${sub.feature}`
+ if (seen.has(key)) continue
+ seen.add(key)
+ out.push(sub)
+ }
+ return out
+ }, [subsData])
+
+ const activeRows = rows.filter(r => r.active)
+ const inactiveRows = rows.filter(r => !r.active)
+
+ const totalMonthlyCents = activeRows.reduce((sum, r) => sum + r.price_monthly_cents, 0)
+
+ if (subsLoading) {
+ return (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
+ <div className="loading-spinner" />
+ </div>
+ )
+ }
+
+ return (
+ <>
+ {/* Summary card */}
+ <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>
+ Per-agent features
+ </span>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 6 }}>
+ <span className="metric-value" style={{ fontSize: 32, fontWeight: 700 }}>
+ ${(totalMonthlyCents / 100).toFixed(2)}
+ </span>
+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ /mo across {activeRows.length} active subscription{activeRows.length === 1 ? '' : 's'}
+ </span>
+ </div>
+ <p style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5, marginTop: 6 }}>
+ Each connected channel (e.g. Telegram) is billed per-agent. Subscribe or cancel from each
+ agent's page.
+ </p>
+ </div>
+
+ {/* Active subscriptions */}
+ <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>
+ Active
+ </span>
+ {activeRows.length === 0 ? (
+ <div style={{ textAlign: 'center', padding: '32px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
+ No active per-agent subscriptions yet.
+ </div>
+ ) : (
+ <table className="data-table">
+ <thead>
+ <tr>
+ <th>Agent</th>
+ <th>Feature</th>
+ <th>Status</th>
+ <th>Renews</th>
+ <th style={{ textAlign: 'right' }}>Price</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {activeRows.map((sub) => {
+ const agent = agentsById[sub.agent_id]
+ const label = agent?.display_name || sub.agent_id
+ const renewLabel = sub.cancel_at_period_end
+ ? `Ends ${formatDate(sub.current_period_end)}`
+ : sub.current_period_end
+ ? formatDate(sub.current_period_end)
+ : '—'
+ return (
+ <tr key={sub.stripe_subscription_id}>
+ <td>
+ <Link to={`/agents/${encodeURIComponent(sub.agent_id)}`}
+ style={{ color: 'var(--accent-indigo)', textDecoration: 'none', fontWeight: 600 }}>
+ {label}
+ </Link>
+ {agent && (
+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>
+ {sub.agent_id}
+ </div>
+ )}
+ </td>
+ <td style={{ textTransform: 'capitalize', fontSize: 13 }}>{sub.feature}</td>
+ <td><SubscriptionStatus status={sub.status} cancelAtPeriodEnd={sub.cancel_at_period_end} /></td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-secondary)' }}>
+ {renewLabel}
+ </td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, textAlign: 'right' }}>
+ ${(sub.price_monthly_cents / 100).toFixed(2)}/mo
+ </td>
+ <td style={{ textAlign: 'right' }}>
+ {!sub.cancel_at_period_end && (
+ <button
+ onClick={() => {
+ if (confirm(`Cancel ${sub.feature} for ${label} at end of billing period?`)) {
+ cancelMutation.mutate({ agentId: sub.agent_id, feature: sub.feature })
+ }
+ }}
+ disabled={cancelMutation.isPending}
+ style={{
+ background: 'none',
+ border: '1px solid var(--border-subtle)',
+ color: 'var(--text-secondary)',
+ fontSize: 12,
+ padding: '4px 10px',
+ borderRadius: 'var(--radius-sm)',
+ cursor: 'pointer',
+ fontFamily: 'var(--font-body)',
+ }}
+ >
+ Cancel
+ </button>
+ )}
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ {/* Past subscriptions (collapsed-feeling) */}
+ {inactiveRows.length > 0 && (
+ <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px' }}>
+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>
+ Past
+ </span>
+ <table className="data-table">
+ <thead>
+ <tr>
+ <th>Agent</th>
+ <th>Feature</th>
+ <th>Status</th>
+ <th>Ended</th>
+ </tr>
+ </thead>
+ <tbody>
+ {inactiveRows.map((sub) => {
+ const agent = agentsById[sub.agent_id]
+ const label = agent?.display_name || sub.agent_id
+ return (
+ <tr key={sub.stripe_subscription_id}>
+ <td>
+ <Link to={`/agents/${encodeURIComponent(sub.agent_id)}`}
+ style={{ color: 'var(--text-secondary)', textDecoration: 'none' }}>
+ {label}
+ </Link>
+ </td>
+ <td style={{ textTransform: 'capitalize', fontSize: 13 }}>{sub.feature}</td>
+ <td><SubscriptionStatus status={sub.status} cancelAtPeriodEnd={false} /></td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-tertiary)' }}>
+ {formatDate(sub.canceled_at || sub.current_period_end)}
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </>
+ )
+}
+
+// ───────────── Invoices tab ─────────────
+
+function InvoicesTab() {
+ const { data: billing } = useQuery({ queryKey: ['billing'], queryFn: getBilling })
+ const { data: invoiceData, isLoading } = useQuery({
+ queryKey: ['invoices'], queryFn: () => getBillingInvoices(),
+ })
+
+ const isPro = billing?.plan === 'pro'
+
+ if (isLoading) {
+ return (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
+ <div className="loading-spinner" />
+ </div>
+ )
+ }
+
+ if (!isPro) {
+ return (
+ <div className="glass-card" style={{ padding: 28, textAlign: 'center' }}>
+ <p style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
+ Invoices appear here once you're on the Pro plan or have a per-agent subscription.
+ </p>
+ </div>
+ )
+ }
+
+ return (
+ <div className="glass-card animate-in stagger-1" style={{ padding: '22px 24px' }}>
+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>Invoices</span>
+ {!invoiceData?.invoices?.length ? (
+ <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
+ No invoices yet — your first invoice will appear at the end of the billing period
+ </div>
+ ) : (
+ <table className="data-table">
+ <thead>
+ <tr><th>Date</th><th>Number</th><th>Status</th><th>Amount</th><th></th></tr>
+ </thead>
+ <tbody>
+ {invoiceData.invoices.map((inv: StripeInvoice) => (
+ <tr key={inv.id}>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
+ {new Date(inv.created * 1000).toLocaleDateString()}
+ </td>
+ <td style={{ fontSize: 12 }}>{inv.number}</td>
+ <td><InvoiceStatus status={inv.status} /></td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600 }}>
+ ${(inv.amountDue / 100).toFixed(2)}
+ </td>
+ <td>
+ {inv.hostedUrl && (
+ <a href={inv.hostedUrl} target="_blank" rel="noreferrer"
+ style={{ fontSize: 12, color: 'var(--accent-indigo)', textDecoration: 'none' }}>
+ View
+ </a>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
)}
</div>
)
}
+// ───────────── Helpers ─────────────
+
+function formatDate(s?: string | null) {
+ if (!s) return '—'
+ const d = new Date(s)
+ if (isNaN(d.getTime())) return '—'
+ return d.toLocaleDateString()
+}
+
+function SubscriptionStatus({ status, cancelAtPeriodEnd }: { status: string; cancelAtPeriodEnd: boolean }) {
+ let color = 'var(--text-tertiary)'
+ let bg = 'rgba(255,255,255,0.04)'
+ let label = status
+
+ if (cancelAtPeriodEnd) {
+ color = 'var(--accent-amber, #f59e0b)'
+ bg = 'rgba(245,158,11,0.1)'
+ label = 'cancels'
+ } else if (status === 'active' || status === 'trialing') {
+ color = 'var(--accent-emerald)'; bg = 'rgba(52,211,153,0.1)'
+ } else if (status === 'past_due' || status === 'incomplete') {
+ color = 'var(--accent-amber, #f59e0b)'; bg = 'rgba(245,158,11,0.1)'
+ } else if (status === 'canceled' || status === 'unpaid' || status === 'incomplete_expired') {
+ color = 'var(--accent-rose)'; bg = 'rgba(244,63,94,0.1)'
+ }
+ return (
+ <span style={{
+ display: 'inline-block', padding: '2px 8px', borderRadius: 4,
+ fontSize: 11, fontWeight: 600, color, background: bg,
+ textTransform: 'uppercase', letterSpacing: '0.5px',
+ }}>{label}</span>
+ )
+}
+
function InvoiceStatus({ status }: { status: string }) {
let color = 'var(--text-tertiary)'
let bg = 'rgba(255,255,255,0.04)'