diff --git a/packages/shared/src/types/budget.ts b/packages/shared/src/types/budget.ts index 7b3fe924d57..4faee2b71bd 100644 --- a/packages/shared/src/types/budget.ts +++ b/packages/shared/src/types/budget.ts @@ -42,6 +42,7 @@ export interface BudgetPolicySummary { observedAmountExact?: string; unpricedEventCount: number; pendingRunCount: number; + unpricedUsageBlocked?: boolean; remainingAmount: number; utilizationPercent: number; warnPercent: number; diff --git a/server/src/services/anthropic-pricing.test.ts b/server/src/services/anthropic-pricing.test.ts index 16d1333a2ea..c57f4f326d7 100644 --- a/server/src/services/anthropic-pricing.test.ts +++ b/server/src/services/anthropic-pricing.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vitest"; +import { usdToUnits } from "@paperclipai/shared"; import type { AdapterUsageCheckpoint } from "@paperclipai/adapter-utils"; -import { priceAnthropicReceipt } from "./anthropic-pricing.js"; +import { + ANTHROPIC_FAMILY_MAX_RATE_CARDS, + ANTHROPIC_RATE_CARDS, + anthropicModelFamily, + priceAnthropicReceipt, +} from "./anthropic-pricing.js"; const receipt: AdapterUsageCheckpoint = { complete: true, usageBasis: "per_run", provider: "anthropic", biller: "anthropic", billingType: "metered_api", model: "claude-sonnet-5", costUsd: null, costStatus: "unpriced", @@ -26,9 +32,98 @@ describe("complete Anthropic receipt pricing", () => { expect(priced.pricingProvenance).toMatchObject({ source: "rate_card" }); expect(priced.pricingProvenance?.evidence).toMatch(/one-hour upper rate used; not an invoice; observed usage is a lower bound$/); }); + it("prices Fable 5.2, Sonnet 4.5 standard rates, legacy Opus 4.1, and other shipped Anthropic models", () => { + const fable52 = priceAnthropicReceipt({ ...receipt, model: "claude-fable-5-2" }); + expect(fable52.costStatus).toBe("estimated"); + expect(fable52.pricingProvenance).toMatchObject({ + source: "rate_card", + version: "anthropic-standard-2026-12-03", + inputCentsPerMillion: "800", + cachedInputCentsPerMillion: "20", + cacheWriteCentsPerMillion: "1600", + outputCentsPerMillion: "4000", + }); + + // Long-context [1m] variants are not silently discounted to the base card; + // they conservatively fall back to the family maximum. + const fable52Long = priceAnthropicReceipt({ ...receipt, model: "claude-fable-5-2[1m]" }); + expect(fable52Long.pricingProvenance).toMatchObject({ + source: "rate_card", + version: "anthropic-fable-family-max-2026-12-03", + inputCentsPerMillion: "1000", + cachedInputCentsPerMillion: "100", + cacheWriteCentsPerMillion: "2000", + outputCentsPerMillion: "5000", + }); + + const sonnet45 = priceAnthropicReceipt({ ...receipt, model: "claude-sonnet-4-5" }); + expect(sonnet45.costStatus).toBe("estimated"); + expect(sonnet45.pricingProvenance).toMatchObject({ + inputCentsPerMillion: "300", + cachedInputCentsPerMillion: "30", + cacheWriteCentsPerMillion: "600", + outputCentsPerMillion: "1500", + }); + + const opus41 = priceAnthropicReceipt({ ...receipt, model: "claude-opus-4-1" }); + expect(opus41.costStatus).toBe("estimated"); + expect(opus41.pricingProvenance).toMatchObject({ + inputCentsPerMillion: "1500", + cachedInputCentsPerMillion: "150", + cacheWriteCentsPerMillion: "3000", + outputCentsPerMillion: "7500", + }); + + const sonnet55 = priceAnthropicReceipt({ ...receipt, model: "claude-sonnet-5-5" }); + expect(sonnet55.costStatus).toBe("estimated"); + expect(sonnet55.pricingProvenance).toMatchObject({ + inputCentsPerMillion: "200", + cachedInputCentsPerMillion: "10", + cacheWriteCentsPerMillion: "400", + outputCentsPerMillion: "1000", + }); + + const haiku45 = priceAnthropicReceipt({ ...receipt, model: "claude-haiku-4-5" }); + expect(haiku45.costStatus).toBe("estimated"); + expect(haiku45.pricingProvenance).toMatchObject({ + inputCentsPerMillion: "100", + cachedInputCentsPerMillion: "10", + cacheWriteCentsPerMillion: "200", + outputCentsPerMillion: "500", + }); + }); + it("keeps every immutable family-max fallback >= every explicit card in its family", () => { + for (const [modelId, card] of Object.entries(ANTHROPIC_RATE_CARDS)) { + const family = anthropicModelFamily(modelId); + expect(family).not.toBeNull(); + const maxCard = ANTHROPIC_FAMILY_MAX_RATE_CARDS[family!]; + for (let i = 0; i < 4; i++) { + expect(usdToUnits(maxCard.rates[i])).toBeGreaterThanOrEqual(usdToUnits(card.rates[i])); + } + } + }); + it.each([ + { model: "claude-fable-5-9", family: "fable", input: "1000", cached: "100", cacheWrite: "2000", output: "5000" }, + { model: "claude-mythos-6", family: "mythos", input: "1000", cached: "100", cacheWrite: "2000", output: "5000" }, + { model: "claude-opus-6", family: "opus", input: "1500", cached: "150", cacheWrite: "3000", output: "7500" }, + { model: "claude-sonnet-latest", family: "sonnet", input: "300", cached: "30", cacheWrite: "600", output: "1500" }, + { model: "claude-haiku-6", family: "haiku", input: "100", cached: "10", cacheWrite: "200", output: "500" }, + ])("defaults uncataloged $model to the most expensive rate in the $family group", ({ model, family, input, cached, cacheWrite, output }) => { + const priced = priceAnthropicReceipt({ ...receipt, model }); + expect(priced.costStatus).toBe("estimated"); + expect(priced.pricingProvenance).toMatchObject({ + source: "rate_card", + version: `anthropic-${family}-family-max-2026-12-03`, + inputCentsPerMillion: input, + cachedInputCentsPerMillion: cached, + cacheWriteCentsPerMillion: cacheWrite, + outputCentsPerMillion: output, + }); + expect(priced.pricingProvenance?.evidence).toContain(`exact rate card unavailable for ${model}, conservative ${family}-family maximum rate used`); + }); it.each([ { complete: false }, { billingType: "unknown" }, { billingType: "subscription_included" }, - { provider: "unknown" }, { biller: "aws_bedrock" }, { model: "claude-sonnet-latest" }, { model: "constructor" }, { model: "toString" }, { model: "__proto__" }, + { provider: "unknown" }, { biller: "aws_bedrock" }, { model: "claude-unknown-1" }, { model: "constructor" }, { model: "toString" }, { model: "__proto__" }, { usageBasis: "session_cumulative" }, { costUsd: 0.12 }, { costUsdExact: "0.12" }, { cacheAdjustedCostUsd: 0.12 }, { pricingContext: { serviceTier: "priority" } }, { usageByModel: [{ model: "other", usage: { inputTokens: 1, outputTokens: 1 }, costUsd: 1 }] }, { usage: undefined }, { usage: { inputTokens: 1, outputTokens: 1 } }, diff --git a/server/src/services/anthropic-pricing.ts b/server/src/services/anthropic-pricing.ts index 6da90ae0767..b664611157b 100644 --- a/server/src/services/anthropic-pricing.ts +++ b/server/src/services/anthropic-pricing.ts @@ -1,31 +1,111 @@ import { centsToUsd, unitsToCents, usdToUnits } from "@paperclipai/shared"; import type { AdapterUsageCheckpoint } from "@paperclipai/adapter-utils"; -const RATE_CARDS: Record = { - "claude-sonnet-5": { rates: ["2", "0.2", "4", "10"], version: "anthropic-standard-2026-10-07" }, - "claude-opus-5-5": { rates: ["4", "0.2", "8", "20"], version: "anthropic-standard-2026-10-12" }, +type RateTuple = readonly [input: string, cachedInput: string, cacheWrite1h: string, output: string]; + +type RateCard = { + rates: RateTuple; + version: string; }; +type AnthropicModelFamily = "fable" | "mythos" | "opus" | "sonnet" | "haiku"; + +// Standard direct Anthropic API list prices (USD per 1M tokens: input, cache read, 1h cache write, output). +// Source: https://platform.claude.com/docs/en/about-claude/pricing +export const ANTHROPIC_RATE_CARDS: Readonly> = Object.freeze({ + // Fable / Mythos + "claude-fable-5-2": { rates: ["8", "0.2", "16", "40"], version: "anthropic-standard-2026-12-03" }, + "claude-fable-5-1": { rates: ["10", "0.25", "20", "50"], version: "anthropic-standard-2026-12-03" }, + "claude-fable-5": { rates: ["10", "1", "20", "50"], version: "anthropic-standard-2026-12-03" }, + "claude-mythos-5-2": { rates: ["8", "0.2", "16", "40"], version: "anthropic-standard-2026-12-03" }, + "claude-mythos-5-1": { rates: ["10", "0.25", "20", "50"], version: "anthropic-standard-2026-12-03" }, + "claude-mythos-5": { rates: ["10", "1", "20", "50"], version: "anthropic-standard-2026-12-03" }, + // Opus (including legacy Opus 4 / 4.1 at $15/$75) + "claude-opus-5-5": { rates: ["4", "0.2", "8", "20"], version: "anthropic-standard-2026-10-12" }, + "claude-opus-5": { rates: ["5", "0.5", "10", "25"], version: "anthropic-standard-2026-12-03" }, + "claude-opus-4-8": { rates: ["5", "0.5", "10", "25"], version: "anthropic-standard-2026-12-03" }, + "claude-opus-4-7": { rates: ["5", "0.5", "10", "25"], version: "anthropic-standard-2026-12-03" }, + "claude-opus-4-6": { rates: ["5", "0.5", "10", "25"], version: "anthropic-standard-2026-12-03" }, + "claude-opus-4-5": { rates: ["5", "0.5", "10", "25"], version: "anthropic-standard-2026-12-03" }, + "claude-opus-4-1": { rates: ["15", "1.5", "30", "75"], version: "anthropic-standard-2026-12-03" }, + "claude-opus-4": { rates: ["15", "1.5", "30", "75"], version: "anthropic-standard-2026-12-03" }, + // Sonnet (standard API rates, never Batch API rates) + "claude-sonnet-5-5": { rates: ["2", "0.1", "4", "10"], version: "anthropic-standard-2026-12-03" }, + "claude-sonnet-5": { rates: ["2", "0.2", "4", "10"], version: "anthropic-standard-2026-10-07" }, + "claude-sonnet-4-6": { rates: ["3", "0.3", "6", "15"], version: "anthropic-standard-2026-12-03" }, + "claude-sonnet-4-5": { rates: ["3", "0.3", "6", "15"], version: "anthropic-standard-2026-12-03" }, + // Haiku + "claude-haiku-5-5": { rates: ["0.5", "0.05", "1", "2.5"], version: "anthropic-standard-2026-12-03" }, + "claude-haiku-4-5": { rates: ["1", "0.1", "2", "5"], version: "anthropic-standard-2026-12-03" }, +}); + +// Reviewed, immutable per-family conservative maximums (must be >= every card in that family). +// Bump the version date whenever a family maximum changes so stored provenance stays reproducible. +export const ANTHROPIC_FAMILY_MAX_RATE_CARDS: Readonly> = Object.freeze({ + fable: { rates: ["10", "1", "20", "50"], version: "anthropic-fable-family-max-2026-12-03" }, + mythos: { rates: ["10", "1", "20", "50"], version: "anthropic-mythos-family-max-2026-12-03" }, + opus: { rates: ["15", "1.5", "30", "75"], version: "anthropic-opus-family-max-2026-12-03" }, + sonnet: { rates: ["3", "0.3", "6", "15"], version: "anthropic-sonnet-family-max-2026-12-03" }, + haiku: { rates: ["1", "0.1", "2", "5"], version: "anthropic-haiku-family-max-2026-12-03" }, +}); + +const ANTHROPIC_FAMILY_RE = /^claude-(fable|mythos|opus|sonnet|haiku)(?:[-@].*)?$/; + +function normalizeAnthropicModelId(model: string): string { + // Preserve variant suffixes such as `[1m]` so long-context variants do not + // silently fall down to a cheaper standard card; they fall back to the + // conservative family maximum instead. + return model.trim().toLowerCase(); +} + +export function anthropicModelFamily(normalizedModel: string): AnthropicModelFamily | null { + const match = ANTHROPIC_FAMILY_RE.exec(normalizedModel); + return (match?.[1] as AnthropicModelFamily | undefined) ?? null; +} + +function resolveAnthropicRateCard(model: string | null | undefined): { card: RateCard; fallbackFamily: AnthropicModelFamily | null } | null { + if (!model) return null; + const normalized = normalizeAnthropicModelId(model); + if (!normalized) return null; + if (Object.hasOwn(ANTHROPIC_RATE_CARDS, normalized)) { + return { card: ANTHROPIC_RATE_CARDS[normalized], fallbackFamily: null }; + } + const family = anthropicModelFamily(normalized); + if (family && Object.hasOwn(ANTHROPIC_FAMILY_MAX_RATE_CARDS, family)) { + return { card: ANTHROPIC_FAMILY_MAX_RATE_CARDS[family], fallbackFamily: family }; + } + return null; +} + /** A complete token receipt can receive an explicit estimate, never an invoice * claim. ACP aggregates cache writes without TTL; conservatively price them at - * the documented one-hour rate rather than silently assume five-minute writes. */ + * the documented one-hour rate rather than silently assume five-minute writes. + * Unknown models in a known Claude family default to the most expensive rate + * card in that family so budgets stay conservative rather than hard-stopping on + * unpriced usage. */ export function priceAnthropicReceipt(receipt: AdapterUsageCheckpoint): AdapterUsageCheckpoint { - const card = receipt.model && Object.hasOwn(RATE_CARDS, receipt.model) ? RATE_CARDS[receipt.model] : undefined; + const resolved = resolveAnthropicRateCard(receipt.model); if (!receipt.complete || !receipt.usage || receipt.usageBasis !== "per_run" || receipt.provider !== "anthropic" || receipt.biller !== "anthropic" || !["api", "metered_api"].includes(receipt.billingType ?? "") - || !card || receipt.usageByModel?.length + || !resolved || receipt.usageByModel?.length || receipt.costUsd != null || receipt.costUsdExact != null || receipt.cacheAdjustedCostUsd != null || (receipt.pricingContext?.serviceTier && !["standard", "default"].includes(receipt.pricingContext.serviceTier))) return receipt; + const { card, fallbackFamily } = resolved; const usage = receipt.usage; if (usage.cacheWriteTokens === undefined || usage.cachedInputTokens === undefined) return receipt; const counts = [usage.inputTokens - usage.cacheWriteTokens, usage.cachedInputTokens, usage.cacheWriteTokens, usage.outputTokens]; if (counts.some(count => !Number.isSafeInteger(count) || count < 0)) return receipt; const numerator = counts.reduce((total, count, index) => total + BigInt(count) * usdToUnits(card.rates[index]), 0n); + const fallbackNote = fallbackFamily + ? `; exact rate card unavailable for ${receipt.model}, conservative ${fallbackFamily}-family maximum rate used` + : ""; return { ...receipt, costUsdExact: centsToUsd(unitsToCents((numerator + 500_000n) / 1_000_000n)), costStatus: "estimated", pricingProvenance: { source: "rate_card", version: card.version, - evidence: "https://platform.claude.com/docs/en/about-claude/pricing; standard global API pricing assumed; cache-write TTL unavailable, one-hour upper rate used; not an invoice" + evidence: "https://platform.claude.com/docs/en/about-claude/pricing; standard global API pricing assumed; cache-write TTL unavailable, one-hour upper rate used" + + fallbackNote + + "; not an invoice" + (receipt.pricingProvenance?.evidence ? `; ${receipt.pricingProvenance.evidence}` : ""), inputCentsPerMillion: (usdToUnits(card.rates[0]) / 10_000_000n).toString(), cachedInputCentsPerMillion: (usdToUnits(card.rates[1]) / 10_000_000n).toString(), diff --git a/server/src/services/budget-live-usage.test.ts b/server/src/services/budget-live-usage.test.ts index 6c8b078f945..ee3d0589459 100644 --- a/server/src/services/budget-live-usage.test.ts +++ b/server/src/services/budget-live-usage.test.ts @@ -48,8 +48,12 @@ describe("live run budget pricing", () => { expect(liveRunUsageCostCents({ ...openai, ...override })).toBeNull(); }); + it("projects uncataloged Claude family models at the conservative family maximum", () => { + expect(liveRunUsageCostCents({ ...anthropic, model: "claude-sonnet-latest" })).toBe("23.3951400"); + }); + it.each([ - { biller: "aws_bedrock" }, { model: "claude-sonnet-latest" }, { pricingContext: { serviceTier: "priority" } }, + { biller: "aws_bedrock" }, { model: "claude-unknown-1" }, { pricingContext: { serviceTier: "priority" } }, { usage: { inputTokens: 1, outputTokens: 1 } }, { usage: { inputTokens: 1, cacheWriteTokens: 2, cachedInputTokens: 0, outputTokens: 1 } }, ] as Partial[])("retains Anthropic rate-card restrictions: %j", override => { diff --git a/server/src/services/budgets.ts b/server/src/services/budgets.ts index 8a36d0bb329..1025454f84e 100644 --- a/server/src/services/budgets.ts +++ b/server/src/services/budgets.ts @@ -511,6 +511,7 @@ export function budgetServiceInTransaction(db: Db, publications: ActivityPublica reservationCents: policy.reservationCents, unpricedEventCount, pendingRunCount, + unpricedUsageBlocked: unpricedUsageBlocks(policy, observed), unpricedUsagePolicy: policy.unpricedUsagePolicy as "block" | "allow", remainingAmount: amount > 0 ? Math.max(0, amount - observedAmount) : 0, utilizationPercent, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 0006e79e72b..5868503f5ec 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -433,7 +433,7 @@ "packages/shared/src/types/asset.ts": "d148d6cba0e9a8d2e3aa6cb9182df6f59f909fba", "packages/shared/src/types/attention.ts": "ec310599deb773488593db9c62c4e0af173e16a5", "packages/shared/src/types/board-bootstrap.ts": "8eb0e0ec4c91369d12b268b9411ed512c8d1e8b1", - "packages/shared/src/types/budget.ts": "7b3fe924d571008d67093c051a13d2c7e67f3ebe", + "packages/shared/src/types/budget.ts": "4faee2b71bdb110694a1237b76e1e7b0e71fd09c", "packages/shared/src/types/chat-channels.ts": "103eb76c5c517102e999b49b4bb726e0ea228902", "packages/shared/src/types/chat-github.ts": "be6e7c951620ee6d107af651fba440938f973ddc", "packages/shared/src/types/company-portability.ts": "76ce2cd19c05d788f57cde743c83b663a584648b", diff --git a/ui/src/components/BudgetIncidentCard.tsx b/ui/src/components/BudgetIncidentCard.tsx index b99b53ad1f4..c82791c97f4 100644 --- a/ui/src/components/BudgetIncidentCard.tsx +++ b/ui/src/components/BudgetIncidentCard.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; -import type { BudgetIncident } from "@paperclipai/shared"; -import { AlertOctagon, AlertTriangle, ArrowUpRight, PauseCircle } from "lucide-react"; +import type { BudgetIncident, BudgetPolicySummary } from "@paperclipai/shared"; +import { AlertOctagon, AlertTriangle, ArrowUpRight } from "lucide-react"; import { formatCents } from "../lib/utils"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; @@ -27,20 +27,33 @@ function incidentStateLabel(incident: BudgetIncident) { export function BudgetIncidentCard({ incident, + policy, onRaiseAndResume, + onAllowUnpricedUsage, onKeepPaused, isMutating, }: { incident: BudgetIncident; + policy?: BudgetPolicySummary | null; onRaiseAndResume: (amountCents: number) => void; + onAllowUnpricedUsage?: () => void; onKeepPaused: () => void; isMutating?: boolean; }) { const isWarning = incident.thresholdType === "soft"; + const effectiveObserved = policy ? policy.observedAmount : incident.amountObserved; + const effectiveLimit = policy ? policy.amount : incident.amountLimit; + const isIncompleteAccountingHardStop = + incident.thresholdType === "hard" && + (policy + ? (policy.unpricedUsageBlocked ?? + (policy.unpricedUsagePolicy !== "allow" && + (policy.unpricedEventCount > 0 || (policy.status === "hard_stop" && policy.observedAmount < policy.amount)))) + : incident.amountObserved < incident.amountLimit); const [draftAmount, setDraftAmount] = useState( centsInputValue(isWarning - ? Math.max(incident.amountObserved, incident.amountLimit) + 1000 - : Math.max(incident.amountObserved + 1000, incident.amountLimit)), + ? Math.max(effectiveObserved, effectiveLimit) + 1000 + : Math.max(effectiveObserved + 1000, effectiveLimit)), ); const parsed = parseDollarInput(draftAmount); const stateLabel = incidentStateLabel(incident); @@ -62,9 +75,11 @@ export function BudgetIncidentCard({ {incident.scopeName} - {incident.thresholdType === "hard" && incident.amountObserved < incident.amountLimit - ? `Accounting is incomplete. Known spend is ${formatCents(incident.amountObserved)}; review pending or unpriced usage in the budget policy.` - : `Spending reached ${formatCents(incident.amountObserved)} against a limit of ${formatCents(incident.amountLimit)}.`} + {isIncompleteAccountingHardStop + ? `${formatCents(effectiveObserved)} of ${formatCents(effectiveLimit)} spent · paused on unpriced or pending usage.` + : isWarning + ? `${formatCents(effectiveObserved)} of ${formatCents(effectiveLimit)} spent · work continues.` + : `${formatCents(effectiveObserved)} of ${formatCents(effectiveLimit)} spent · paused.`} {isWarning ? ( @@ -79,58 +94,57 @@ export function BudgetIncidentCard({ - {isWarning ? ( -
- -
- Spending crossed the warning threshold. This warning does not pause work. -
-
- ) : ( -
- -
- {incident.scopeType === "project" - ? "Project execution is paused. New work in this project will not start until you resolve the budget incident." - : "This scope is paused. New heartbeats will not start until you resolve the budget incident."} + {isIncompleteAccountingHardStop ? null : ( +
+ +
+ setDraftAmount(event.target.value)} + inputMode="decimal" + placeholder="0.00" + /> +
+ {parsed !== null && parsed <= effectiveObserved ? ( +

+ Must exceed current spend. +

+ ) : null}
)} -
- -
- setDraftAmount(event.target.value)} - inputMode="decimal" - placeholder="0.00" - /> - -
- {parsed !== null && parsed <= incident.amountObserved ? ( -

- The new budget must exceed current observed spend. +

+ {isIncompleteAccountingHardStop && !onAllowUnpricedUsage ? ( +

+ Allow unpriced usage in the budget policy to resume.

+ ) : ( + + )} + {isIncompleteAccountingHardStop && onAllowUnpricedUsage ? ( + + ) : isIncompleteAccountingHardStop ? ( + ) : null}
- -
- -
); diff --git a/ui/src/components/IssueAssigneePausedNotice.tsx b/ui/src/components/IssueAssigneePausedNotice.tsx new file mode 100644 index 00000000000..5aff11a2f47 --- /dev/null +++ b/ui/src/components/IssueAssigneePausedNotice.tsx @@ -0,0 +1,116 @@ +import type { Agent } from "@paperclipai/shared"; +import { PauseCircle } from "lucide-react"; +import { Link } from "@/lib/router"; +import { agentUrl } from "@/lib/utils"; +import { InlineBanner } from "./InlineBanner"; +import { Button } from "@/components/ui/button"; + +function isTerminalIssueDisposition(issueStatus: string | undefined): boolean { + return issueStatus === "done" || issueStatus === "cancelled"; +} + +export function IssueAssigneePausedNotice({ + agent, + issueStatus, + onResume, + resuming, +}: { + agent: Agent | null; + issueStatus: string | undefined; + onResume?: () => Promise | void; + resuming?: boolean; +}) { + if (!agent || agent.status !== "paused" || isTerminalIssueDisposition(issueStatus)) return null; + + // Lifecycle setup is shown by the queued turn and its inline connection card. + // Resume changes operator holds; it cannot complete verification. + if (!agent.pauseReason && ["preparing", "verifying", "resuming"].includes(agent.lifecycleState ?? "")) return null; + + // A freshly created agent is stored as paused with pauseReason "setup" until + // its setup finishes. That is not an operator pause, so say what is actually + // happening and point at the real recovery path instead of "Resume agent". + if (agent.pauseReason === "setup") { + // Only computer preparation advances on its own (matches NewAgentSetup). + // A "verifying" or parked draft waits for the user to finish the wizard. + const stillPreparing = ["preparing", "pausing"].includes(agent.lifecycleState ?? ""); + return ( +
+ + {agent.name} is still being set up. + + } + actions={ + stillPreparing ? undefined : ( + + ) + } + > + {stillPreparing + ? "Its computer is being prepared. Runs start automatically when setup finishes." + : "Its setup isn't finished yet. Finish setup to let it start runs."} + +
+ ); + } + + const isBudgetPause = agent.pauseReason === "budget"; + const canResume = Boolean(onResume) && !isBudgetPause && agent.pauseReason !== "company_archived"; + + const title = isBudgetPause ? ( + <> + {agent.name} is paused (budget). + + ) : ( + <> + {agent.name} is paused. + + ); + + const body = isBudgetPause + ? "Messages won’t get a reply until this is resolved." + : agent.pauseReason === "company_archived" + ? "Messages won’t get a reply while this company is archived." + : agent.pauseReason === "import" + ? "Imported paused — resume to get replies." + : "Messages won’t get a reply until resumed."; + + const actions = isBudgetPause ? ( + + ) : canResume ? ( + + ) : undefined; + + return ( +
+ + {body} + +
+ ); +} diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx index 1bb171340a6..d828c959c6e 100644 --- a/ui/src/components/IssueChatThread.tsx +++ b/ui/src/components/IssueChatThread.tsx @@ -12,6 +12,8 @@ import type { ComposerRunSettings } from "./task-chat/composer-run-settings"; import { ComposerRunSettingsPicker } from "./task-chat/ComposerRunSettingsPicker"; import { ComposerAddMenu, ComposerModeChip } from "./task-chat/ComposerAddMenu"; import { TaskChatPausedTakeover, type TaskComposerPause } from "./task-chat/TaskChatPausedTakeover"; +import { IssueAssigneePausedNotice } from "./IssueAssigneePausedNotice"; +export { IssueAssigneePausedNotice }; import { useEmailComment } from "./EmailMessageCard"; import { AssistantRuntimeProvider } from "@assistant-ui/react"; import type { @@ -826,106 +828,6 @@ class IssueChatErrorBoundary extends Component< } } -export function IssueAssigneePausedNotice({ - agent, - issueStatus, - onResume, - resuming, -}: { - agent: Agent | null; - issueStatus: string | undefined; - onResume?: () => Promise | void; - resuming?: boolean; -}) { - if (!agent || agent.status !== "paused" || issueStatusIsTerminalDisposition(issueStatus)) return null; - - // Lifecycle setup is shown by the queued turn and its inline connection card. - // Resume changes operator holds; it cannot complete verification. - if (!agent.pauseReason && ["preparing", "verifying", "resuming"].includes(agent.lifecycleState ?? "")) return null; - - // A freshly created agent is stored as paused with pauseReason "setup" until - // its setup finishes. That is not an operator pause, so say what is actually - // happening and point at the real recovery path instead of "Resume agent". - if (agent.pauseReason === "setup") { - // Only computer preparation advances on its own (matches NewAgentSetup). - // A "verifying" or parked draft waits for the user to finish the wizard. - const stillPreparing = ["preparing", "pausing"].includes(agent.lifecycleState ?? ""); - return ( -
- - {agent.name} is still being set up. - - } - actions={ - stillPreparing ? undefined : ( - - ) - } - > - {stillPreparing - ? "Its computer is being prepared. Runs start automatically when setup finishes." - : "Its setup isn't finished yet. Finish setup to let it start runs."} - -
- ); - } - - const pauseDetail = - agent.pauseReason === "budget" - ? "It was paused by a budget hard stop." - : agent.pauseReason === "import" - ? "It arrived paused from an organization import — imported agents stay parked until you resume them." - : agent.pauseReason === "system" - ? "It was paused by the system." - : agent.pauseReason === "company_archived" - ? "It was paused because its company is archived." - : agent.pauseReason === "manual" - ? "It was paused manually." - : ""; - // Budget pauses clear on their own when the budget resets and archive pauses - // clear when the company is restored; resuming by hand would fight either, so - // the action is only offered for the rest. - const canResume = Boolean(onResume) && agent.pauseReason !== "budget" && agent.pauseReason !== "company_archived"; - - return ( -
- - {agent.name} is paused. - - } - actions={ - canResume ? ( - - ) : undefined - } - > - New runs will not start until the agent is resumed.{pauseDetail ? ` ${pauseDetail}` : ""} - -
- ); -} - function fallbackAuthorLabel(message: ThreadMessage) { const custom = message.metadata?.custom as Record | undefined; diff --git a/ui/src/components/PausedBudgetNotices.test.tsx b/ui/src/components/PausedBudgetNotices.test.tsx new file mode 100644 index 00000000000..66707dccc2c --- /dev/null +++ b/ui/src/components/PausedBudgetNotices.test.tsx @@ -0,0 +1,231 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Agent, BudgetIncident, BudgetPolicySummary } from "@paperclipai/shared"; +import { MemoryRouter } from "@/lib/router"; +import { IssueAssigneePausedNotice } from "./IssueAssigneePausedNotice"; +import { BudgetIncidentCard } from "./BudgetIncidentCard"; + +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ + selectedCompany: { id: "company-1", issuePrefix: "FIF" }, + selectedCompanyId: "company-1", + companies: [{ id: "company-1", issuePrefix: "FIF" }], + }), +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +function makeAgent(overrides: Partial = {}): Agent { + return { + id: "agent-dorian", + companyId: "company-1", + name: "Dorian", + urlKey: "dorian", + role: "general", + status: "paused", + pauseReason: "budget", + ...overrides, + } as Agent; +} + +function makeIncident(overrides: Partial = {}): BudgetIncident { + return { + id: "incident-1", + companyId: "company-1", + policyId: "policy-1", + scopeType: "agent", + scopeId: "agent-dorian", + scopeName: "Dorian", + metric: "billed_cents", + windowKind: "calendar_month_utc", + windowStart: new Date("2026-12-01T00:00:00Z"), + windowEnd: new Date("2027-01-01T00:00:00Z"), + thresholdType: "hard", + amountLimit: 100000, + amountObserved: 167, + status: "open", + approvalId: null, + approvalStatus: null, + resolvedAt: null, + createdAt: new Date("2026-12-03T17:47:28Z"), + updatedAt: new Date("2026-12-03T17:47:28Z"), + ...overrides, + }; +} + +describe("IssueAssigneePausedNotice and BudgetIncidentCard", () => { + let container: HTMLDivElement; + let root: Root; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(() => { + act(() => { + root.unmount(); + }); + container.remove(); + }); + + it("explains budget pause in chat and links directly to the agent budgets page", () => { + act(() => { + root.render( + + + , + ); + }); + + expect(container.textContent).toContain("Dorian is paused (budget)"); + expect(container.textContent).toContain("Messages won’t get a reply"); + const budgetLink = container.querySelector('[data-testid="issue-assignee-paused-budget"]'); + expect(budgetLink).not.toBeNull(); + expect(budgetLink?.getAttribute("href")).toBe("/FIF/agents/dorian/budgets"); + expect(container.querySelector('[data-testid="issue-assignee-paused-resume"]')).toBeNull(); + }); + + it("offers direct Resume agent action for manual pauses and warns replies won't arrive", () => { + const onResume = vi.fn(); + act(() => { + root.render( + + + , + ); + }); + + expect(container.textContent).toContain("Dorian is paused"); + expect(container.textContent).toContain("Messages won’t get a reply"); + const resumeBtn = container.querySelector('[data-testid="issue-assignee-paused-resume"]'); + expect(resumeBtn).not.toBeNull(); + act(() => { + resumeBtn?.click(); + }); + expect(onResume).toHaveBeenCalledTimes(1); + }); + + it("distinguishes incomplete-accounting stops from spend-limit stops and offers Allow unpriced usage", () => { + const onAllowUnpricedUsage = vi.fn(); + act(() => { + root.render( + , + ); + }); + + expect(container.textContent).toContain("$1.67 of $1,000.00 spent · paused on unpriced or pending usage."); + expect(container.textContent).toContain("Allow unpriced usage"); + expect(container.textContent).not.toContain("Raise budget & resume"); + const allowBtn = Array.from(container.querySelectorAll("button")).find((b) => + b.textContent?.includes("Allow unpriced usage"), + ); + act(() => { + allowBtn?.click(); + }); + expect(onAllowUnpricedUsage).toHaveBeenCalledTimes(1); + }); + + it("restores Raise budget & resume when live policy state shows usage settled above the limit", () => { + const settledPolicy: BudgetPolicySummary = { + policyId: "policy-1", + companyId: "company-1", + scopeType: "agent", + scopeId: "agent-dorian", + scopeName: "Dorian", + metric: "billed_cents", + windowKind: "calendar_month_utc", + amount: 100000, + observedAmount: 120000, + unpricedEventCount: 0, + pendingRunCount: 0, + remainingAmount: 0, + utilizationPercent: 120, + warnPercent: 80, + hardStopEnabled: true, + unpricedUsagePolicy: "block", + notifyEnabled: true, + isActive: true, + status: "hard_stop", + paused: true, + pauseReason: "budget", + windowStart: new Date("2026-12-01T00:00:00Z"), + windowEnd: new Date("2027-01-01T00:00:00Z"), + }; + + act(() => { + root.render( + , + ); + }); + + expect(container.textContent).toContain("$1,200.00 of $1,000.00 spent · paused."); + expect(container.textContent).toContain("Raise budget & resume"); + expect(container.textContent).not.toContain("paused on unpriced or pending usage"); + }); + + it("keeps incomplete-accounting guidance when server reports unpricedUsageBlocked even above the cap", () => { + const unknownBrowserBlockedPolicy: BudgetPolicySummary = { + policyId: "policy-1", + companyId: "company-1", + scopeType: "agent", + scopeId: "agent-dorian", + scopeName: "Dorian", + metric: "billed_cents", + windowKind: "calendar_month_utc", + amount: 100000, + observedAmount: 120000, + unpricedEventCount: 0, + pendingRunCount: 0, + unpricedUsageBlocked: true, + remainingAmount: 0, + utilizationPercent: 120, + warnPercent: 80, + hardStopEnabled: true, + unpricedUsagePolicy: "block", + notifyEnabled: true, + isActive: true, + status: "hard_stop", + paused: true, + pauseReason: "budget", + windowStart: new Date("2026-12-01T00:00:00Z"), + windowEnd: new Date("2027-01-01T00:00:00Z"), + }; + + act(() => { + root.render( + , + ); + }); + + expect(container.textContent).toContain("paused on unpriced or pending usage."); + expect(container.textContent).not.toContain("Raise budget & resume"); + }); +}); diff --git a/ui/src/pages/AgentBudgetsPanel.tsx b/ui/src/pages/AgentBudgetsPanel.tsx index 8b405dd9d4c..b8564869a9b 100644 --- a/ui/src/pages/AgentBudgetsPanel.tsx +++ b/ui/src/pages/AgentBudgetsPanel.tsx @@ -87,7 +87,9 @@ export function AgentBudgetsPanel({ agent, companyId }: { agent: BudgetAgent; co
policy.mutate({ unpricedUsagePolicy: "allow" })} onKeepPaused={() => incident.mutate({ incidentId: entry.id, action: "keep_paused" })} onRaiseAndResume={(amount) => incident.mutate({ incidentId: entry.id, action: "raise_budget_and_resume", amount })} /> diff --git a/ui/src/pages/Costs.tsx b/ui/src/pages/Costs.tsx index f3ca4c24bcf..7f7b578359b 100644 --- a/ui/src/pages/Costs.tsx +++ b/ui/src/pages/Costs.tsx @@ -596,6 +596,10 @@ export function Costs({ agent: budgetPolicies.filter((policy) => policy.scopeType === "agent"), project: budgetPolicies.filter((policy) => policy.scopeType === "project"), }), [budgetPolicies]); + const budgetPolicyById = useMemo( + () => new Map(budgetPolicies.map((policy) => [policy.policyId, policy])), + [budgetPolicies], + ); if (!selectedCompanyId) { return ; @@ -887,12 +891,26 @@ export function Costs({
{activeBudgetIncidents.length > 0 ? ( -
- {activeBudgetIncidents.slice(0, 2).map((incident) => ( +
+ {policyMutation.error && ( +

+ Could not update the budget policy. Review your settings and try again. +

+ )} +
+ {activeBudgetIncidents.slice(0, 2).map((incident) => { + const matchedPolicy = budgetPolicyById.get(incident.policyId) ?? null; + return ( + policyMutation.mutate({ + summary: matchedPolicy, + changes: { unpricedUsagePolicy: "allow" }, + }) : undefined} onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })} onRaiseAndResume={(amount) => incidentMutation.mutate({ @@ -901,7 +919,9 @@ export function Costs({ amount, })} /> - ))} + ); + })} +
) : null} @@ -972,11 +992,19 @@ export function Costs({

- {activeBudgetIncidents.map((incident) => ( + {activeBudgetIncidents.map((incident) => { + const matchedPolicy = budgetPolicyById.get(incident.policyId) ?? null; + return ( + policyMutation.mutate({ + summary: matchedPolicy, + changes: { unpricedUsagePolicy: "allow" }, + }) : undefined} onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })} onRaiseAndResume={(amount) => incidentMutation.mutate({ @@ -985,7 +1013,8 @@ export function Costs({ amount, })} /> - ))} + ); + })}
) : null} diff --git a/ui/storybook/stories/budgets-costs/paused-agent-chat-notice.stories.tsx b/ui/storybook/stories/budgets-costs/paused-agent-chat-notice.stories.tsx new file mode 100644 index 00000000000..01b645bd355 --- /dev/null +++ b/ui/storybook/stories/budgets-costs/paused-agent-chat-notice.stories.tsx @@ -0,0 +1,156 @@ +import { useState } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import type { Agent, BudgetIncident } from "@paperclipai/shared"; +import { expect, userEvent, within } from "storybook/test"; +import { IssueAssigneePausedNotice } from "@/components/IssueAssigneePausedNotice"; +import { BudgetIncidentCard } from "@/components/BudgetIncidentCard"; +import { TaskChatBubble } from "@/components/task-chat/TaskChatBubble"; + +const baseAgent: Agent = { + id: "agent-dorian", + companyId: "company-storybook", + name: "Dorian", + urlKey: "dorian", + role: "general", + status: "paused", + pauseReason: "budget", +} as Agent; + +const unpricedIncident: BudgetIncident = { + id: "incident-unpriced", + companyId: "company-storybook", + policyId: "policy-dorian", + scopeType: "agent", + scopeId: "agent-dorian", + scopeName: "Dorian", + metric: "billed_cents", + windowKind: "calendar_month_utc", + windowStart: new Date("2026-12-01T00:00:00Z"), + windowEnd: new Date("2027-01-01T00:00:00Z"), + thresholdType: "hard", + amountLimit: 100000, + amountObserved: 167, + status: "open", + approvalId: null, + approvalStatus: null, + resolvedAt: null, + createdAt: new Date("2026-12-03T17:47:28Z"), + updatedAt: new Date("2026-12-03T17:47:28Z"), +}; + +function PausedAgentChatSurface({ + pauseReason = "budget", + showIncidentCard = false, +}: { + pauseReason?: "budget" | "manual" | "company_archived"; + showIncidentCard?: boolean; +}) { + const [resumed, setResumed] = useState(false); + const [incidentStatus, setIncidentStatus] = useState<"open" | "resolved" | "dismissed">("open"); + const agent: Agent = { + ...baseAgent, + status: resumed ? "idle" : "paused", + pauseReason: resumed ? null : pauseReason, + }; + + return ( +
+ + + + {resumed ? ( +
+ Dorian has been resumed and can reply to new messages. +
+ ) : ( + setResumed(true) : undefined} + /> + )} + + {showIncidentCard ? ( +
+ undefined} + onAllowUnpricedUsage={() => { + setIncidentStatus("resolved"); + setResumed(true); + }} + onKeepPaused={() => setIncidentStatus("dismissed")} + /> +
+ ) : null} +
+ ); +} + +const meta = { + id: "feature-paused-agent-budget-notice", + title: "Oversight and operation/Costs and budgets/Paused agent chat notice", + component: PausedAgentChatSurface, + parameters: { + layout: "padded", + paperclip: { + capabilities: ["budgets-costs/resolution"], + status: "current", + implementation: "production", + boundary: "fixtures", + notes: + "Production IssueAssigneePausedNotice and BudgetIncidentCard rendered together in a chat thread so reviewers can inspect budget-paused chat messaging, Review budget link, manual Resume agent button, and unpriced-usage hard-stop clarity.", + }, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const BudgetPausedInChat: Story = { + args: { pauseReason: "budget", showIncidentCard: false }, + play: async ({ canvasElement }) => { + const c = within(canvasElement); + await expect(c.getByText(/is paused \(budget\)/i)).toBeInTheDocument(); + await expect(c.getByText(/Messages won’t get a reply/i)).toBeInTheDocument(); + await expect(c.getByRole("link", { name: "Review budget" })).toBeInTheDocument(); + }, +}; + +export const BudgetPausedWithUnpricedIncident: Story = { + args: { pauseReason: "budget", showIncidentCard: true }, + play: async ({ canvasElement }) => { + const c = within(canvasElement); + await expect(c.getByText(/\$1\.67 of \$1,000\.00 spent · paused on unpriced or pending usage\./)).toBeInTheDocument(); + await expect(c.getByRole("button", { name: "Allow unpriced usage" })).toBeInTheDocument(); + await expect(c.queryByRole("button", { name: "Raise budget & resume" })).not.toBeInTheDocument(); + }, +}; + +export const ManuallyPausedInChat: Story = { + args: { pauseReason: "manual", showIncidentCard: false }, + play: async ({ canvasElement }) => { + const c = within(canvasElement); + const resume = c.getByRole("button", { name: "Resume agent" }); + await userEvent.click(resume); + await expect(c.getByText(/Dorian has been resumed/i)).toBeInTheDocument(); + }, +};