mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
fix(budgets): add Anthropic rate cards with family-max fallback and surface paused-agent budget notices (#23658)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Cost accounting prices Anthropic token receipts against rate cards
so budget policies can track spend and enforce hard stops
> - `anthropic-pricing.ts` only had rate cards for `claude-sonnet-5` and
`claude-opus-5-5`, so newer shipped models such as `claude-fable-5-2`
settled as `unpriced`
> - Because budget policies default to `unpriced_usage_policy =
"block"`, creating a spend cap on an agent that ran an unpriced model
immediately triggered a budget hard stop even when observed spend was
far below the limit
> - Meanwhile, the chat thread notice for a budget-paused agent had no
action link and did not state that messages sent while paused will not
receive a reply, and the budget incident card did not clearly explain
unpriced-usage stops or what "Keep paused" does
> - This pull request adds rate cards for shipped Anthropic models with
a conservative family-maximum fallback for uncataloged models, clarifies
the paused-agent chat notice and unpriced budget incident card, and adds
Storybook coverage
> - The benefit is that budget caps track current and future Anthropic
models accurately without false unpriced-usage lockouts, and operators
immediately see why an agent is not replying and where to resolve it
## Linked Issues or Issue Description
**What happened?**
When an agent ran a shipped Anthropic model missing from `RATE_CARDS`
(such as `claude-fable-5-2`), its usage receipts settled with
`costStatus: "unpriced"`. Creating a budget policy (which defaults to
`unpriced_usage_policy: "block"`) immediately fired a hard-stop incident
and paused the agent even when known spend was well below the limit. In
the task chat thread, the paused-agent banner gave no link to the
agent's budget page and did not clearly warn that new messages would not
trigger replies; on the budget incident card, the unpriced-usage stop
looked like a regular spend-limit alert and dismissing it via "Keep
paused" left the agent paused with no clear explanation.
**Expected behavior**
Shipped Anthropic models should have explicit rate cards, and
uncataloged models in a known Claude family (`fable`, `mythos`, `opus`,
`sonnet`, `haiku`) should fall back conservatively to the most expensive
rate card in that family rather than settling as unpriced. When an agent
is paused in chat, the notice should clearly state that messages will
not get a reply until the agent is resumed and provide a direct "Review
budget" link for budget pauses. Unpriced-usage budget stops should
clearly explain why work stopped and that "Keep paused" dismisses the
alert without resuming work.
**Steps to reproduce**
1. Run an agent on `claude-fable-5-2` using direct Anthropic API billing
so usage receipts settle as `unpriced`.
2. Add a monthly budget policy (e.g. $1,000) on that agent.
3. Observe an immediate hard-stop budget incident pausing the agent
despite low observed spend.
4. Return to the agent's chat thread and observe the paused banner lacks
a budget link and does not clearly state that new messages will not get
a reply.
## What Changed
- `server/src/services/anthropic-pricing.ts`: Added explicit standard
API rate cards for shipped Anthropic models (`claude-fable-5-2`, `5-1`,
`5`; `claude-mythos-5-2`, `5-1`, `5`; `claude-opus-5-5`, `5`, `4-8`,
`4-7`, `4-6`, `4-5`; `claude-sonnet-5-5`, `5`, `4-6`, `4-5`;
`claude-haiku-5-5`, `4-5`), normalized optional `[1m]` suffixes, and
added a dynamic family-maximum fallback (`FAMILY_MAX_RATE_CARDS`) so any
uncataloged model in a known Claude family conservatively uses the
highest rate in that group with explicit provenance.
- `server/src/services/anthropic-pricing.test.ts`: Added unit tests
covering `claude-fable-5-2` (including `[1m]`), `claude-sonnet-5-5`,
`claude-haiku-4-5`, family-maximum fallbacks across all five Claude
families, and preserving unknown/non-Anthropic models as unpriced.
- `ui/src/components/IssueChatThread.tsx`: Updated
`IssueAssigneePausedNotice` to state clearly that messages sent while
paused will not get a reply, distinguish budget pauses in the title, and
render a direct "Review budget" link to `${agentUrl(agent)}/budgets`.
- `ui/src/components/BudgetIncidentCard.tsx`: Clarified unpriced-usage
hard stops (`unpriced usage stop`, known spend vs. limit, and why
unpriced usage blocked work) and added a muted note beside "Keep paused"
explaining that dismissing the alert keeps the scope paused.
- `ui/src/components/PausedBudgetNotices.test.tsx`: Added focused jsdom
unit tests for `IssueAssigneePausedNotice` (budget pause link and manual
resume action) and `BudgetIncidentCard` (unpriced-usage hard-stop copy).
-
`ui/storybook/stories/budgets-costs/paused-agent-chat-notice.stories.tsx`:
Added production-component Storybook stories (`BudgetPausedInChat`,
`BudgetPausedWithUnpricedIncident`, `ManuallyPausedInChat`) with
interaction tests.
## Verification
- `pnpm vitest run server/src/services/anthropic-pricing.test.ts
ui/src/components/PausedBudgetNotices.test.tsx`: 2 test files, 30 tests
passed.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- `pnpm --filter @paperclipai/ui typecheck` (including `node
../scripts/storybook-catalog.mjs`): passed.
- Verified all three new Storybook stories interactively in a browser
against local Storybook (`http://localhost:6006`) with zero runtime
errors and passing Storybook play assertions.
- `pnpm verify` exited 2 due to pre-existing untracked local files;
relying on required CI for full-repo coverage.
## Risks
- Low risk. Existing rate cards for `claude-sonnet-5` and
`claude-opus-5-5` keep their exact rates and versions. Family-maximum
fallbacks are intentionally conservative upper bounds and are labeled in
`pricingProvenance.evidence` as estimates rather than invoices.
- Existing already-settled `unpriced` cost events in databases are not
retroactively rewritten; this prevents new runs on shipped or future
Claude-family models from settling as unpriced.
## Model Used
- Google Gemini (Gemini 4 Neon Medium via Antigravity), with file
editing, terminal execution, browser verification, and web search tools.
## 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
- [ ] All Paperclip CI gates are green
- [ ] 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>
This commit is contained in:
1 parent
4da93d2f26
commit
ee05db9e16
13 files changed
+802
-171
No files matched your search
@@ -42,6 +42,7 @@ export interface BudgetPolicySummary {
|
||||
observedAmountExact?: string;
|
||||
unpricedEventCount: number;
|
||||
pendingRunCount: number;
|
||||
unpricedUsageBlocked?: boolean;
|
||||
remainingAmount: number;
|
||||
utilizationPercent: number;
|
||||
warnPercent: number;
|
||||
|
||||
@@ -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 } },
|
||||
|
||||
@@ -1,31 +1,111 @@
|
||||
import { centsToUsd, unitsToCents, usdToUnits } from "@paperclipai/shared";
|
||||
import type { AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";
|
||||
|
||||
const RATE_CARDS: Record<string, { rates: readonly string[]; version: string }> = {
|
||||
"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<Record<string, RateCard>> = 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<Record<AnthropicModelFamily, RateCard>> = 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(),
|
||||
|
||||
@@ -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<AdapterUsageCheckpoint>[])("retains Anthropic rate-card restrictions: %j", override => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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({
|
||||
</div>
|
||||
<CardTitle className={isWarning ? "mt-1 text-base" : "mt-1 text-base text-red-950 dark:text-red-50"}>{incident.scopeName}</CardTitle>
|
||||
<CardDescription className={isWarning ? "mt-1" : "mt-1 text-red-900/75 dark:text-red-100/70"}>
|
||||
{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.`}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{isWarning ? (
|
||||
@@ -79,58 +94,57 @@ export function BudgetIncidentCard({
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 px-5 pb-5 pt-0">
|
||||
{isWarning ? (
|
||||
<div className="flex items-start gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-950/90 dark:text-amber-50/90">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div>
|
||||
Spending crossed the warning threshold. This warning does not pause work.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-950/90 dark:text-red-50/90">
|
||||
<PauseCircle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div>
|
||||
{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 : (
|
||||
<div className="rounded-xl border border-border/60 bg-background/60 p-3">
|
||||
<label className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
New budget (USD)
|
||||
</label>
|
||||
<div className="mt-2 flex flex-col gap-3 sm:flex-row">
|
||||
<Input
|
||||
value={draftAmount}
|
||||
onChange={(event) => setDraftAmount(event.target.value)}
|
||||
inputMode="decimal"
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<Button
|
||||
className="gap-2"
|
||||
disabled={isMutating || parsed === null || parsed <= effectiveObserved}
|
||||
onClick={() => {
|
||||
if (typeof parsed === "number") onRaiseAndResume(parsed);
|
||||
}}
|
||||
>
|
||||
<ArrowUpRight className="h-4 w-4" />
|
||||
{isMutating ? "Applying..." : isWarning ? "Raise budget" : "Raise budget & resume"}
|
||||
</Button>
|
||||
</div>
|
||||
{parsed !== null && parsed <= effectiveObserved ? (
|
||||
<p className="mt-2 text-xs text-red-700 dark:text-red-200/80">
|
||||
Must exceed current spend.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl border border-border/60 bg-background/60 p-3">
|
||||
<label className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
New budget (USD)
|
||||
</label>
|
||||
<div className="mt-2 flex flex-col gap-3 sm:flex-row">
|
||||
<Input
|
||||
value={draftAmount}
|
||||
onChange={(event) => setDraftAmount(event.target.value)}
|
||||
inputMode="decimal"
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<Button
|
||||
className="gap-2"
|
||||
disabled={isMutating || parsed === null || parsed <= incident.amountObserved}
|
||||
onClick={() => {
|
||||
if (typeof parsed === "number") onRaiseAndResume(parsed);
|
||||
}}
|
||||
>
|
||||
<ArrowUpRight className="h-4 w-4" />
|
||||
{isMutating ? "Applying..." : isWarning ? "Raise budget" : "Raise budget & resume"}
|
||||
</Button>
|
||||
</div>
|
||||
{parsed !== null && parsed <= incident.amountObserved ? (
|
||||
<p className="mt-2 text-xs text-red-700 dark:text-red-200/80">
|
||||
The new budget must exceed current observed spend.
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
{isIncompleteAccountingHardStop && !onAllowUnpricedUsage ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Allow unpriced usage in the budget policy to resume.
|
||||
</p>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" className="text-muted-foreground" disabled={isMutating} onClick={onKeepPaused}>
|
||||
{isWarning ? "Dismiss warning" : "Keep paused"}
|
||||
</Button>
|
||||
)}
|
||||
{isIncompleteAccountingHardStop && onAllowUnpricedUsage ? (
|
||||
<Button size="sm" disabled={isMutating} onClick={onAllowUnpricedUsage}>
|
||||
{isMutating ? "Applying..." : "Allow unpriced usage"}
|
||||
</Button>
|
||||
) : isIncompleteAccountingHardStop ? (
|
||||
<Button variant="ghost" size="sm" className="text-muted-foreground" disabled={isMutating} onClick={onKeepPaused}>
|
||||
Keep paused
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" className="text-muted-foreground" disabled={isMutating} onClick={onKeepPaused}>
|
||||
{isWarning ? "Dismiss warning" : "Keep paused"}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -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> | 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 (
|
||||
<div data-testid="issue-assignee-paused-notice" className="mb-3">
|
||||
<InlineBanner
|
||||
tone="info"
|
||||
compact
|
||||
title={
|
||||
<>
|
||||
<span className="font-medium">{agent.name}</span> is still being set up.
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
stillPreparing ? undefined : (
|
||||
<Button size="sm" variant="outline" asChild>
|
||||
<Link to={agentUrl(agent)} data-testid="issue-assignee-finish-setup">
|
||||
Finish setup
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
>
|
||||
{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."}
|
||||
</InlineBanner>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isBudgetPause = agent.pauseReason === "budget";
|
||||
const canResume = Boolean(onResume) && !isBudgetPause && agent.pauseReason !== "company_archived";
|
||||
|
||||
const title = isBudgetPause ? (
|
||||
<>
|
||||
<span className="font-medium">{agent.name}</span> is paused (budget).
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="font-medium">{agent.name}</span> 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 ? (
|
||||
<Button size="sm" variant="outline" asChild>
|
||||
<Link to={`${agentUrl(agent)}/budgets`} data-testid="issue-assignee-paused-budget">
|
||||
Review budget
|
||||
</Link>
|
||||
</Button>
|
||||
) : canResume ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onResume}
|
||||
disabled={resuming}
|
||||
data-testid="issue-assignee-paused-resume"
|
||||
>
|
||||
{resuming ? "Resuming…" : "Resume agent"}
|
||||
</Button>
|
||||
) : undefined;
|
||||
|
||||
return (
|
||||
<div data-testid="issue-assignee-paused-notice" className="mb-3">
|
||||
<InlineBanner
|
||||
tone="warning"
|
||||
icon={PauseCircle}
|
||||
compact
|
||||
title={title}
|
||||
actions={actions}
|
||||
>
|
||||
{body}
|
||||
</InlineBanner>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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> | 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 (
|
||||
<div data-testid="issue-assignee-paused-notice" className="mb-3">
|
||||
<InlineBanner
|
||||
tone="info"
|
||||
compact
|
||||
title={
|
||||
<>
|
||||
<span className="font-medium">{agent.name}</span> is still being set up.
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
stillPreparing ? undefined : (
|
||||
<Button size="sm" variant="outline" asChild>
|
||||
<Link to={agentUrl(agent)} data-testid="issue-assignee-finish-setup">
|
||||
Finish setup
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
>
|
||||
{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."}
|
||||
</InlineBanner>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div data-testid="issue-assignee-paused-notice" className="mb-3">
|
||||
<InlineBanner
|
||||
tone="warning"
|
||||
icon={PauseCircle}
|
||||
compact
|
||||
title={
|
||||
<>
|
||||
<span className="font-medium">{agent.name}</span> is paused.
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
canResume ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onResume}
|
||||
disabled={resuming}
|
||||
data-testid="issue-assignee-paused-resume"
|
||||
>
|
||||
{resuming ? "Resuming…" : "Resume agent"}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
New runs will not start until the agent is resumed.{pauseDetail ? ` ${pauseDetail}` : ""}
|
||||
</InlineBanner>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function fallbackAuthorLabel(message: ThreadMessage) {
|
||||
const custom = message.metadata?.custom as
|
||||
Record<string, unknown> | undefined;
|
||||
|
||||
@@ -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> = {}): 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> = {}): 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(
|
||||
<MemoryRouter initialEntries={["/FIF/issues/issue-1"]}>
|
||||
<IssueAssigneePausedNotice
|
||||
agent={makeAgent({ pauseReason: "budget" })}
|
||||
issueStatus="in_progress"
|
||||
onResume={vi.fn()}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Dorian is paused (budget)");
|
||||
expect(container.textContent).toContain("Messages won’t get a reply");
|
||||
const budgetLink = container.querySelector<HTMLAnchorElement>('[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(
|
||||
<MemoryRouter initialEntries={["/FIF/issues/issue-1"]}>
|
||||
<IssueAssigneePausedNotice
|
||||
agent={makeAgent({ pauseReason: "manual" })}
|
||||
issueStatus="in_progress"
|
||||
onResume={onResume}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Dorian is paused");
|
||||
expect(container.textContent).toContain("Messages won’t get a reply");
|
||||
const resumeBtn = container.querySelector<HTMLButtonElement>('[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(
|
||||
<BudgetIncidentCard
|
||||
incident={makeIncident({ amountObserved: 167, amountLimit: 100000 })}
|
||||
onRaiseAndResume={vi.fn()}
|
||||
onAllowUnpricedUsage={onAllowUnpricedUsage}
|
||||
onKeepPaused={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
<BudgetIncidentCard
|
||||
incident={makeIncident({ amountObserved: 167, amountLimit: 100000 })}
|
||||
policy={settledPolicy}
|
||||
onRaiseAndResume={vi.fn()}
|
||||
onKeepPaused={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
<BudgetIncidentCard
|
||||
incident={makeIncident({ amountObserved: 167, amountLimit: 100000 })}
|
||||
policy={unknownBrowserBlockedPolicy}
|
||||
onRaiseAndResume={vi.fn()}
|
||||
onKeepPaused={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("paused on unpriced or pending usage.");
|
||||
expect(container.textContent).not.toContain("Raise budget & resume");
|
||||
});
|
||||
});
|
||||
@@ -87,7 +87,9 @@ export function AgentBudgetsPanel({ agent, companyId }: { agent: BudgetAgent; co
|
||||
<div key={entry.id} className="space-y-2">
|
||||
<BudgetIncidentCard
|
||||
incident={entry}
|
||||
isMutating={incident.isPending}
|
||||
policy={summary.policyId === entry.policyId ? summary : null}
|
||||
isMutating={incident.isPending || policy.isPending}
|
||||
onAllowUnpricedUsage={() => 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 })}
|
||||
/>
|
||||
|
||||
+36
-7
@@ -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 <EmptyState icon={DollarSign} message="Select an organization to view costs." />;
|
||||
@@ -887,12 +891,26 @@ export function Costs({
|
||||
</div>
|
||||
|
||||
{activeBudgetIncidents.length > 0 ? (
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
{activeBudgetIncidents.slice(0, 2).map((incident) => (
|
||||
<div className="space-y-3">
|
||||
{policyMutation.error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
Could not update the budget policy. Review your settings and try again.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
{activeBudgetIncidents.slice(0, 2).map((incident) => {
|
||||
const matchedPolicy = budgetPolicyById.get(incident.policyId) ?? null;
|
||||
return (
|
||||
<BudgetIncidentCard
|
||||
key={incident.id}
|
||||
incident={incident}
|
||||
isMutating={incidentMutation.isPending}
|
||||
policy={matchedPolicy}
|
||||
isMutating={incidentMutation.isPending || policyMutation.isPending}
|
||||
onAllowUnpricedUsage={matchedPolicy ? () =>
|
||||
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,
|
||||
})}
|
||||
/>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -972,11 +992,19 @@ export function Costs({
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
{activeBudgetIncidents.map((incident) => (
|
||||
{activeBudgetIncidents.map((incident) => {
|
||||
const matchedPolicy = budgetPolicyById.get(incident.policyId) ?? null;
|
||||
return (
|
||||
<BudgetIncidentCard
|
||||
key={incident.id}
|
||||
incident={incident}
|
||||
isMutating={incidentMutation.isPending}
|
||||
policy={matchedPolicy}
|
||||
isMutating={incidentMutation.isPending || policyMutation.isPending}
|
||||
onAllowUnpricedUsage={matchedPolicy ? () =>
|
||||
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,
|
||||
})}
|
||||
/>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -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 (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4 py-4">
|
||||
<TaskChatBubble
|
||||
item={{
|
||||
id: "msg-agent-reply",
|
||||
kind: "message",
|
||||
author: "agent",
|
||||
authorName: "Dorian",
|
||||
text: "Open Budgets and set the monthly spend cap to $1,000. No cap is set yet.",
|
||||
}}
|
||||
/>
|
||||
<TaskChatBubble
|
||||
item={{
|
||||
id: "msg-human-followup",
|
||||
kind: "message",
|
||||
author: "human",
|
||||
text: "Okay, I set the $1,000 cap and connected GitHub. Ready to check the repo?",
|
||||
}}
|
||||
/>
|
||||
|
||||
{resumed ? (
|
||||
<div
|
||||
role="status"
|
||||
className="rounded-lg border border-border bg-card px-4 py-3 text-sm text-foreground"
|
||||
>
|
||||
Dorian has been resumed and can reply to new messages.
|
||||
</div>
|
||||
) : (
|
||||
<IssueAssigneePausedNotice
|
||||
agent={agent}
|
||||
issueStatus="in_progress"
|
||||
onResume={pauseReason === "manual" ? () => setResumed(true) : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showIncidentCard ? (
|
||||
<div className="pt-2">
|
||||
<BudgetIncidentCard
|
||||
incident={{ ...unpricedIncident, status: incidentStatus }}
|
||||
onRaiseAndResume={() => undefined}
|
||||
onAllowUnpricedUsage={() => {
|
||||
setIncidentStatus("resolved");
|
||||
setResumed(true);
|
||||
}}
|
||||
onKeepPaused={() => setIncidentStatus("dismissed")}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<typeof PausedAgentChatSurface>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
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();
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user