mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-15 12:28:10 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Its Costs page reports API charges and subscription token usage. > - Subscription runs do not show the recurring fee paid for the account. > - Several agents can share one paid seat, so a fee per agent would overstate cost. > - This pull request identifies connected subscription accounts and reports each monthly fee once. > - Users can compare API spend and subscription costs, see uncertainty, and enter their actual price. ## Linked Issues or Issue Description Refs #498 and #3406 for related subscription reporting needs. This change does not add subscription budget enforcement or automatic optimization. Related prior approaches: #10544 and #11104 proposed API-equivalent token costs for subscription work. This PR reports recurring account fees separately from usage charges and budgets. A search found no open PR for monthly account fee reporting. **Subsystem affected** Costs, managed AI connections, shared contracts, database schema, and board UI. **Problem or motivation** An organization can pay for subscriptions even when included runs record no additional dollar charge. The Costs page cannot show that monthly commitment or distinguish a shared paid seat from several separate seats. **Proposed solution** Discover account identity from the managed connection selected for a run. Use exact known plans for labeled monthly list-price estimates. Keep ambiguous plans and unconfirmed identities unpriced until the user supplies a price. Sum current monthly fees separately from date-filtered API charges and token usage. **Alternatives considered** A fee per agent double-counts shared accounts. Token-based API price estimates do not measure the recurring subscription fee. Provider invoices would be more exact but are not available through these account credentials. **Roadmap alignment** Extends the shipped Better Budgeting and Personal & Shared AI Accounts capabilities. The feature and UI were reviewed with the maintainer before this PR. ## What Changed - Add company-scoped subscription accounts, connection bindings, and immutable price revisions in replay-safe migration 0322. - Identify OpenAI workspace/seat and Claude organization/account pairs only after provider authentication. Keep provisional records grant-scoped; unchecked ID-token claims cannot combine accounts or grant billing editors. Keep credentials and raw provider identities out of reports. - Attach the selected subscription to new run receipts. Resolve duplicate aliases without rewriting old monetary receipts. - Add cached background discovery with four provider checks and twenty discovery requests at a time. Accepted requests wait for capacity; excess requests receive HTTP 429 and a UI retry action. Preserve saved prices and observations when a provider check fails. Dashboard polls load current prices only; audit revisions stay in the database. - Support owner-controlled monthly or annual prices, fractional-cent precision, separate currency totals, tracking status, and duplicate linking. Preserve both personal owners and shared-account managers when discovery finds the same paid seat. - Show API spend beside monthly subscription commitment, with separate token totals and clear estimate labels. Account details and fee totals follow billing-owner/shared-audience visibility; company-wide token totals remain available to cost readers. - Use consistent amount and estimate badge formatting for agent, user, project, and model rows. - Add real PostgreSQL tests, route authorization tests, UI tests, interactive Storybook fixtures, and operator documentation. ## Verification - Current head `d7b5c78dadf5033a3c447d83434676ac94687e77` passed all 53 checks, with two checks skipped. This includes the full test matrix, browser tests, build, typecheck, migration policy, canary packaging, and security checks. - Greptile Apex reviewed that exact head at 5/5 with no unresolved findings. - Local `pnpm -r typecheck`, `pnpm build`, `pnpm check:token-gates`, migration safety checks, and `git diff --check` passed. - All 238 focused tests passed across accounting, subscription persistence, authorization, UI, migration replay, and snapshot drift. - The expanded local chat suite passed 1,149 tests. Two cases failed because this workspace found an unrelated ancestor skill directory; both passed unchanged in an isolated checkout. The full local Vitest command was not repeated after the rebase because of this environment issue. CI covered the complete test matrix on the final head. - Migration `0322_reflective_kree.sql` follows master's `0321_acoustic_human_fly.sql`. Its snapshot and journal were regenerated. Master's migration and snapshot are unchanged. The subscription SQL retains its original content and hash. - Disposable PostgreSQL upgrade fixtures applied master's added lifecycle and Slack migrations without changing saved subscription prices or cost receipts. The renamed subscription migration was recognized by hash, retained one history row, and a second migration run was a no-op. - Regression tests cover provider capacity, fractional-cent edits, billing visibility after grant revocation, and fixed-price/credit/unknown usage. The new UI billing-label tests fail against the old wording and pass with the fix. - Browser checks passed for desktop and mobile layouts, shared-account totals, annual price edits, unknown prices, and stale provider data. - A live OpenAI account probe returned HTTP 200 and a verified Pro account identity. The generic Pro plan correctly remains unpriced. - Live Claude discovery identified Max 20x and a $200/month estimate. Two real Claude agent runs were attributed to that same account, with two usage receipts, two agents, one monthly fee, and zero additional usage charges. Two OpenAI connections also deduplicated to one account. - Live Codex execution is not verified: both Paperclip's managed hello test and a direct host `codex exec` fail with a workspace-routing authentication error. The current credential passes the usage API probe. This is separate from the successful account-discovery check. - A local performance fixture with 50,000 usage events and 5,001 saved price revisions produced a 1,589-byte report in 11.5 ms median / 12.2 ms maximum over ten warmed runs. PostgreSQL used the subscription/revision index to read one current price row. These are local measurements, not a production latency guarantee. - [Desktop, account details, and mobile screenshots](https://pages.paperclip.ing/pr-15634-subscription-costs-d5d285e2/) show the production Costs page with synthetic Storybook fixtures. - To inspect the UI, run `pnpm storybook` and open **Costs / Subscriptions**. Edits there change fixture data only. ## Risks - Provider plan identifiers can change. Unknown plans remain unpriced. Automatic prices are estimates before tax; discounts and negotiated prices require a user-supplied amount. - Subscription fees describe the current monthly commitment. They do not follow the selected usage date range and do not consume agent budgets or create finance events. - Monthly fees cover only accounts visible to the viewer; company-wide token totals retain their existing scope. - Legacy or unmanaged usage can remain unattributed. Unconfirmed identities require manual prices and may need explicit duplicate linking after credential changes. - Disconnecting a connection does not prove provider billing stopped. Users must end or exclude tracking explicitly. - Migration 0322 adds tables, a nullable cost-event column, and an index. It is replay-safe, but normal migration locks still apply. ## Model Used OpenAI Codex, based on GPT-6. This session did not expose a more specific backend model ID or context-window size. Capabilities used: code editing, shell execution, database tests, and browser verification. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
113 lines
4.1 KiB
TypeScript
113 lines
4.1 KiB
TypeScript
import { z } from "zod";
|
|
import { exactCentsSchema } from "./accounting.js";
|
|
import { centsToUnits, unitsToCents } from "./money.js";
|
|
|
|
export const SUBSCRIPTION_CURRENCIES = ["USD", "EUR", "GBP", "CAD", "AUD", "CHF"] as const;
|
|
export const subscriptionPriceSchema = z.object({
|
|
expectedRevision: z.number().int().nonnegative(),
|
|
plan: z.string().trim().min(1).max(100),
|
|
amountCents: exactCentsSchema.nullable(),
|
|
currency: z.enum(SUBSCRIPTION_CURRENCIES),
|
|
cadence: z.enum(["month", "year"]),
|
|
status: z.enum(["active", "ended", "excluded"]),
|
|
}).strict();
|
|
export type UpdateSubscriptionPrice = z.input<typeof subscriptionPriceSchema>;
|
|
export const mergeSubscriptionsSchema = z.object({
|
|
targetId: z.string().uuid(),
|
|
expectedRevision: z.number().int().nonnegative(),
|
|
targetRevision: z.number().int().nonnegative(),
|
|
}).strict();
|
|
|
|
export interface SubscriptionPlan {
|
|
id: string;
|
|
provider: string;
|
|
name: string;
|
|
monthlyCents: string;
|
|
currency: "USD";
|
|
sourceUrl: string;
|
|
checkedAt: string;
|
|
}
|
|
|
|
// Web list prices, before tax, assuming monthly billing. These are estimates,
|
|
// never invoices. Generic Pro/Max/team entitlements do not identify a price.
|
|
export const SUBSCRIPTION_PLANS: readonly SubscriptionPlan[] = [
|
|
["openai", "free", "ChatGPT Free", "0", "https://learn.chatgpt.com/docs/pricing"],
|
|
["openai", "go", "ChatGPT Go", "800", "https://learn.chatgpt.com/docs/pricing"],
|
|
["openai", "plus", "ChatGPT Plus", "2000", "https://learn.chatgpt.com/docs/pricing"],
|
|
["anthropic", "pro", "Claude Pro", "2000", "https://claude.com/pricing"],
|
|
["anthropic", "max_5x", "Claude Max 5x", "10000", "https://claude.com/pricing"],
|
|
["anthropic", "max_20x", "Claude Max 20x", "20000", "https://claude.com/pricing"],
|
|
["xai", "supergrok", "SuperGrok", "3000", "https://x.ai/pricing"],
|
|
["xai", "supergrok_plus", "SuperGrok Plus", "10000", "https://x.ai/pricing"],
|
|
].map(([provider, id, name, monthlyCents, sourceUrl]) => ({
|
|
provider, id, name, monthlyCents, sourceUrl, currency: "USD", checkedAt: "2026-10-08",
|
|
}));
|
|
|
|
export function subscriptionPlan(provider: string, plan: string | null): SubscriptionPlan | null {
|
|
const key = plan?.trim().toLowerCase().replaceAll(" ", "_");
|
|
return SUBSCRIPTION_PLANS.find(item => item.provider === provider && item.id === key) ?? null;
|
|
}
|
|
|
|
export function monthlySubscriptionCents(amount: string, cadence: "month" | "year"): string {
|
|
const units = centsToUnits(amount);
|
|
return unitsToCents(cadence === "year" ? (units + 6n) / 12n : units);
|
|
}
|
|
|
|
export interface SubscriptionPrice {
|
|
revision: number;
|
|
plan: string;
|
|
amountCents: string | null;
|
|
monthlyCents: string | null;
|
|
currency: string;
|
|
cadence: "month" | "year";
|
|
status: "active" | "ended" | "excluded";
|
|
source: "catalog" | "user" | "unknown";
|
|
sourceUrl: string | null;
|
|
effectiveAt: string;
|
|
}
|
|
|
|
export interface SubscriptionUsage {
|
|
inputTokens: number;
|
|
cachedInputTokens: number;
|
|
outputTokens: number;
|
|
costCents: string;
|
|
eventCount: number;
|
|
estimatedEventCount: number;
|
|
unpricedEventCount: number;
|
|
}
|
|
|
|
export interface SubscriptionAccountReport {
|
|
id: string;
|
|
provider: string;
|
|
name: string;
|
|
ownerUserId: string | null;
|
|
ownerName: string | null;
|
|
shared: boolean;
|
|
identityVerified: boolean;
|
|
detectedPlan: string | null;
|
|
observedAt: string | null;
|
|
lastCheckedAt: string | null;
|
|
refreshStatus: "ok" | "unavailable" | null;
|
|
canEdit: boolean;
|
|
price: SubscriptionPrice;
|
|
usage: SubscriptionUsage;
|
|
agents: { id: string; name: string }[];
|
|
}
|
|
|
|
export interface SubscriptionCostReport {
|
|
canRefresh: boolean;
|
|
/** Current monthly commitment for accounts visible to the caller;
|
|
* independent of the usage date filter. Aggregate run usage is company-wide. */
|
|
asOf: string;
|
|
accounts: SubscriptionAccountReport[];
|
|
monthlyTotals: { currency: string; amountCents: string; estimatedCount: number }[];
|
|
activeCount: number;
|
|
unknownPriceCount: number;
|
|
unidentifiedAccountCount: number;
|
|
api: SubscriptionUsage;
|
|
subscription: SubscriptionUsage;
|
|
/** Other billing types (credits, fixed, or unknown), outside API/subscription totals. */
|
|
unknown: SubscriptionUsage;
|
|
unattributedSubscription: SubscriptionUsage;
|
|
}
|