Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(models): rewrite the price editor's form wiring (LFE-14948) (#15982)

Nikita Kabardinb7a353421619
diff --git a/web/src/components/table/use-cases/models.tsx b/web/src/components/table/use-cases/models.tsx
index 2daf262a74..d5d936f95f 100644
--- a/web/src/components/table/use-cases/models.tsx
+++ b/web/src/components/table/use-cases/models.tsx
@@ -26,7 +26,7 @@ import { LangfuseIcon } from "@/src/components/design-system/LangfuseIcon/Langfu
import { useRouter } from "next/router";
import { PriceUnitSelector } from "@/src/features/models/components/PriceUnitSelector";
import { usePriceUnitMultiplier } from "@/src/features/models/hooks/usePriceUnitMultiplier";
-import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog";
import { TestModelMatchButton } from "@/src/features/models/components/test-match/TestModelMatchButton";
import { ActionButton } from "@/src/components/ActionButton";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
diff --git a/web/src/features/models/components/CloneModelButton.tsx b/web/src/features/models/components/CloneModelButton.tsx
index 9e57d764de..91717aad95 100644
--- a/web/src/features/models/components/CloneModelButton.tsx
+++ b/web/src/features/models/components/CloneModelButton.tsx
@@ -1,6 +1,6 @@
import { Button } from "@/src/components/ui/button";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog";
import { type GetModelResult } from "@/src/features/models/validation";
export const CloneModelButton = ({
diff --git a/web/src/features/models/components/EditModelButton.tsx b/web/src/features/models/components/EditModelButton.tsx
index c301f79edb..d55bec8e05 100644
--- a/web/src/features/models/components/EditModelButton.tsx
+++ b/web/src/features/models/components/EditModelButton.tsx
@@ -1,6 +1,6 @@
import { Button } from "@/src/components/ui/button";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog";
import { type GetModelResult } from "@/src/features/models/validation";
export const EditModelButton = ({
diff --git a/web/src/features/models/components/PriceBreakdownTooltip.tsx b/web/src/features/models/components/PriceBreakdownTooltip.tsx
index 04303b9fcc..f13e0b31e8 100644
--- a/web/src/features/models/components/PriceBreakdownTooltip.tsx
+++ b/web/src/features/models/components/PriceBreakdownTooltip.tsx
@@ -10,7 +10,7 @@ import {
TooltipTrigger,
} from "@/src/components/ui/tooltip";
import { usePriceUnitMultiplier } from "@/src/features/models/hooks/usePriceUnitMultiplier";
-import { getMaxDecimals } from "@/src/features/models/utils";
+import { getMaxDecimals } from "@/src/features/models/fns/getMaxDecimals";
import { type PriceUnit } from "@/src/features/models/validation";
export const PriceBreakdownTooltip = ({
diff --git a/web/src/features/models/components/PricePreview.tsx b/web/src/features/models/components/PricePreview.tsx
index 0189f3ef23..24f7db13d5 100644
--- a/web/src/features/models/components/PricePreview.tsx
+++ b/web/src/features/models/components/PricePreview.tsx
@@ -1,26 +1,28 @@
import Decimal from "decimal.js";
-import { PriceMapSchema } from "@/src/features/models/validation";
-import { getMaxDecimals } from "@/src/features/models/utils";
+import { getMaxDecimals } from "@/src/features/models/fns/getMaxDecimals";
+/**
+ * Preview of the rows that currently hold a valid price. Rows that are
+ * mid-edit are simply absent — field-level messages own their errors.
+ */
export function PricePreview({
prices,
}: {
- prices: Record<string, number | undefined>;
+ // `key` is the usage type's row identity: names can collide while editing.
+ prices: { key: string; usageType: string; price: number }[];
}) {
- const parsedPrices = PriceMapSchema.safeParse(prices);
-
- const getMaxDecimalsForPriceGroup = (
- price: number | undefined,
- multiplier: number,
- ) => {
- return price != null
- ? Math.max(
- ...Object.values(prices).map((price) => {
- return getMaxDecimals(price, multiplier);
- }),
- )
- : 0;
+ // One scale per column, shared by every row so the decimal points line up.
+ const decimalsFor = (multiplier: number) =>
+ prices.length === 0
+ ? 0
+ : Math.max(
+ ...prices.map(({ price }) => getMaxDecimals(price, multiplier)),
+ );
+ const decimals = {
+ unit: decimalsFor(1),
+ per1K: decimalsFor(1000),
+ per1M: decimalsFor(1000000),
};
return (
@@ -32,49 +34,32 @@ export function PricePreview({
</h4>
</div>
- {parsedPrices.success ? (
- <div className="space-y-2">
- <div className="border-border text-muted-foreground grid grid-cols-[2fr_1fr_1fr_1fr] gap-2 border-b pb-2 text-xs font-bold">
- <span>Usage Type</span>
- <span className="text-right">per unit</span>
- <span className="text-right">per 1K</span>
- <span className="text-right">per 1M</span>
- </div>
-
- {Object.entries(parsedPrices.data)
- .filter((entry): entry is [string, number] => Boolean(entry[1]))
- .map(([usageType, price]) => (
- <div
- key={usageType}
- className="text-muted-foreground grid grid-cols-[2fr_1fr_1fr_1fr] gap-2 rounded px-1 py-0.5 text-xs"
- >
- <span className="font-bold break-all">{usageType}</span>
- <span className="text-right font-mono">
- $
- {new Decimal(price).toFixed(
- getMaxDecimalsForPriceGroup(price, 1),
- )}
- </span>
- <span className="text-right font-mono">
- $
- {new Decimal(price)
- .mul(1000)
- .toFixed(getMaxDecimalsForPriceGroup(price, 1000))}
- </span>
- <span className="text-right font-mono">
- $
- {new Decimal(price)
- .mul(1000000)
- .toFixed(getMaxDecimalsForPriceGroup(price, 1000000))}
- </span>
- </div>
- ))}
- </div>
- ) : (
- <div className="bg-destructive/10 text-destructive rounded-md p-3 text-sm">
- Invalid price entries. Please check your input format.
+ <div className="space-y-2">
+ <div className="border-border text-muted-foreground grid grid-cols-[2fr_1fr_1fr_1fr] gap-2 border-b pb-2 text-xs font-bold">
+ <span>Usage Type</span>
+ <span className="text-right">per unit</span>
+ <span className="text-right">per 1K</span>
+ <span className="text-right">per 1M</span>
</div>
- )}
+
+ {prices.map(({ key, usageType, price }) => (
+ <div
+ key={key}
+ className="text-muted-foreground grid grid-cols-[2fr_1fr_1fr_1fr] gap-2 rounded px-1 py-0.5 text-xs"
+ >
+ <span className="font-bold break-all">{usageType}</span>
+ <span className="text-right font-mono">
+ ${new Decimal(price).toFixed(decimals.unit)}
+ </span>
+ <span className="text-right font-mono">
+ ${new Decimal(price).mul(1000).toFixed(decimals.per1K)}
+ </span>
+ <span className="text-right font-mono">
+ ${new Decimal(price).mul(1000000).toFixed(decimals.per1M)}
+ </span>
+ </div>
+ ))}
+ </div>
</div>
</div>
);
diff --git a/web/src/features/models/components/PricingSection/PricingSection.tsx b/web/src/features/models/components/PricingSection/PricingSection.tsx
new file mode 100644
index 0000000000..dbdf9c4acb
--- /dev/null
+++ b/web/src/features/models/components/PricingSection/PricingSection.tsx
@@ -0,0 +1,175 @@
+import { PlusCircle } from "lucide-react";
+import { useState } from "react";
+import { useFieldArray } from "react-hook-form";
+import { Button } from "@/src/components/ui/button";
+import { FormDescription, FormLabel } from "@/src/components/ui/form";
+import { Accordion } from "@/src/components/ui/accordion";
+import { derivePriorities } from "@/src/features/models/fns/derivePriorities";
+import { makeUsageTypeKeys } from "@/src/features/models/fns/makeUsageTypeKeys";
+import { TierAccordionItem } from "./components/TierAccordionItem";
+import { TierPriceEditor } from "./components/TierPriceEditor";
+import { TierPrefillButtons } from "./components/TierPrefillButtons";
+import type { UseFormReturn } from "react-hook-form";
+import type { FormUpsertModel } from "@/src/features/models/validation";
+
+type PricingSectionProps = {
+ form: UseFormReturn<FormUpsertModel>;
+};
+
+export type { PricingSectionProps };
+
+const NEW_TIER_CONDITION = {
+ usageDetailPattern: "^input",
+ operator: "gt" as const,
+ value: 0,
+ caseSensitive: false,
+};
+
+export function PricingSection({ form }: PricingSectionProps) {
+ const tiers = useFieldArray({ control: form.control, name: "pricingTiers" });
+ // Radix seeds `defaultValue` once, at mount, so a tier added later would
+ // render collapsed. Track what the user closed instead: new tiers are open.
+ const [collapsedTiers, setCollapsedTiers] = useState<string[]>([]);
+ const usageTypes = useFieldArray({
+ control: form.control,
+ name: "usageTypes",
+ });
+
+ // Usage types are shared by every tier, so adding one adds a price row to
+ // each tier. Renaming or removing touches no other tier's prices at all.
+ const addUsageTypes = (names: string[]) => {
+ const existing = form.getValues("usageTypes");
+ const keys = makeUsageTypeKeys(existing, names.length);
+ const rows = names.map((name, index) => ({ key: keys[index], name }));
+
+ usageTypes.append(rows);
+ form.getValues("pricingTiers").forEach((_, tierIndex) => {
+ rows.forEach((row) =>
+ form.setValue(`pricingTiers.${tierIndex}.prices.${row.key}`, "0"),
+ );
+ });
+ };
+
+ // Drop the removed row's prices too, so a later row cannot inherit them.
+ const removeUsageType = (index: number) => {
+ const removedKey = form.getValues(`usageTypes.${index}.key`);
+ usageTypes.remove(index);
+ form.getValues("pricingTiers").forEach((tier, tierIndex) => {
+ const { [removedKey]: _removed, ...rest } = tier.prices;
+ form.setValue(`pricingTiers.${tierIndex}.prices`, rest);
+ });
+ };
+
+ const prefillUsageTypes = (names: string[]) => {
+ const existing = new Set(
+ form.getValues("usageTypes").map((row) => row.name.trim()),
+ );
+ const missing = names.filter((name) => !existing.has(name));
+ if (missing.length > 0) addUsageTypes(missing);
+ };
+
+ const addTier = () => {
+ const existing = form.getValues("pricingTiers");
+ const takenNames = new Set(existing.map((tier) => tier.name.trim()));
+ let suffix = 1;
+ while (takenNames.has(`Custom Tier ${suffix}`)) suffix++;
+
+ tiers.append({
+ name: `Custom Tier ${suffix}`,
+ isDefault: false,
+ conditions: [{ ...NEW_TIER_CONDITION }],
+ // Prices are keyed by usage type row key, so this copies by identity.
+ prices: { ...(existing.find((tier) => tier.isDefault)?.prices ?? {}) },
+ });
+ };
+
+ const priceEditorProps = {
+ form,
+ usageTypeRows: usageTypes.fields,
+ onAddUsageType: () => addUsageTypes([""]),
+ onRemoveUsageType: removeUsageType,
+ };
+
+ if (tiers.fields.length <= 1) {
+ // SIMPLE VIEW: Just show prices for the single default tier
+ const defaultTierIndex = Math.max(
+ 0,
+ tiers.fields.findIndex((tier) => tier.isDefault),
+ );
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <FormLabel>Prices</FormLabel>
+ <FormDescription>
+ Set prices per usage type for this model. Usage types must exactly
+ match the keys of the ingested usage details.
+ </FormDescription>
+ </div>
+
+ <TierPrefillButtons onPrefill={prefillUsageTypes} />
+ <TierPriceEditor
+ {...priceEditorProps}
+ tierIndex={defaultTierIndex}
+ isDefault={true}
+ />
+
+ <Button type="button" variant="ghost" onClick={addTier}>
+ <PlusCircle className="mr-2 h-4 w-4" />
+ Add Custom Pricing Tier
+ </Button>
+ </div>
+ );
+ }
+
+ const priorities = derivePriorities(tiers.fields);
+ const tierIds = tiers.fields.map((field) => field.id);
+
+ // ACCORDION VIEW: Multiple tiers
+ return (
+ <div className="space-y-4">
+ <div>
+ <FormLabel>Pricing Tiers</FormLabel>
+ <FormDescription>
+ Define pricing rules evaluated in priority order. Tiers are checked
+ from top to bottom until conditions match.
+ </FormDescription>
+ </div>
+
+ <Accordion
+ type="multiple"
+ value={tierIds.filter((id) => !collapsedTiers.includes(id))}
+ onValueChange={(open) =>
+ setCollapsedTiers(tierIds.filter((id) => !open.includes(id)))
+ }
+ className="space-y-2"
+ >
+ {tiers.fields.map((field, index) => (
+ <TierAccordionItem
+ key={field.id}
+ tier={field}
+ index={index}
+ priority={priorities[index]}
+ form={form}
+ remove={tiers.remove}
+ isDefault={field.isDefault}
+ >
+ {field.isDefault && (
+ <TierPrefillButtons onPrefill={prefillUsageTypes} />
+ )}
+ <TierPriceEditor
+ {...priceEditorProps}
+ tierIndex={index}
+ isDefault={field.isDefault}
+ />
+ </TierAccordionItem>
+ ))}
+ </Accordion>
+
+ <Button type="button" variant="outline" onClick={addTier}>
+ <PlusCircle className="mr-2 h-4 w-4" />
+ Add Custom Tier
+ </Button>
+ </div>
+ );
+}
diff --git a/web/src/features/models/components/pricing-tiers/TierAccordionItem.tsx b/web/src/features/models/components/PricingSection/components/TierAccordionItem.tsx
similarity index 80%
rename from web/src/features/models/components/pricing-tiers/TierAccordionItem.tsx
rename to web/src/features/models/components/PricingSection/components/TierAccordionItem.tsx
index aa4aac25f6..df6fd260dc 100644
--- a/web/src/features/models/components/pricing-tiers/TierAccordionItem.tsx
+++ b/web/src/features/models/components/PricingSection/components/TierAccordionItem.tsx
@@ -14,18 +14,19 @@ import {
FormLabel,
FormMessage,
} from "@/src/components/ui/form";
+import { useWatch } from "react-hook-form";
import { TierConditionsEditor } from "./TierConditionsEditor";
-import { TierPriceEditor } from "./TierPriceEditor";
-import { TierPrefillButtons } from "./TierPrefillButtons";
import type { UseFormReturn, FieldArrayWithId } from "react-hook-form";
-import type { FormUpsertModel } from "../../validation";
+import type { FormUpsertModel } from "@/src/features/models/validation";
type TierAccordionItemProps = {
tier: FieldArrayWithId<FormUpsertModel, "pricingTiers", "id">;
index: number;
+ priority: number;
form: UseFormReturn<FormUpsertModel>;
remove: (index: number) => void;
isDefault: boolean;
+ children: React.ReactNode;
};
export type { TierAccordionItemProps };
@@ -33,22 +34,26 @@ export type { TierAccordionItemProps };
export function TierAccordionItem({
tier,
index,
+ priority,
form,
remove,
isDefault,
+ children,
}: TierAccordionItemProps) {
+ const name = useWatch({
+ control: form.control,
+ name: `pricingTiers.${index}.name`,
+ });
+
return (
- <AccordionItem
- value={`tier-${index}`}
- className="bg-muted/30 rounded-lg border"
- >
+ <AccordionItem value={tier.id} className="bg-muted/30 rounded-lg border">
<AccordionTrigger className="px-4 hover:no-underline">
<div className="flex w-full items-center justify-between">
<div className="flex items-center gap-2">
- <span className="font-bold">{tier.name}</span>
+ <span className="font-bold">{name ?? tier.name}</span>
{isDefault && <Badge variant="secondary">Default</Badge>}
<span className="text-muted-foreground text-xs">
- Priority: {tier.priority}
+ Priority: {priority}
</span>
</div>
{!isDefault && (
@@ -86,9 +91,7 @@ export function TierAccordionItem({
{/* Conditions (only for non-default) */}
{!isDefault && <TierConditionsEditor tierIndex={index} form={form} />}
- {/* Prices */}
- {isDefault && <TierPrefillButtons tierIndex={index} form={form} />}
- <TierPriceEditor tierIndex={index} form={form} isDefault={isDefault} />
+ {children}
</AccordionContent>
</AccordionItem>
);
diff --git a/web/src/features/models/components/pricing-tiers/TierConditionsEditor.tsx b/web/src/features/models/components/PricingSection/components/TierConditionsEditor.tsx
similarity index 98%
rename from web/src/features/models/components/pricing-tiers/TierConditionsEditor.tsx
rename to web/src/features/models/components/PricingSection/components/TierConditionsEditor.tsx
index c3265d6f28..a4abf1933b 100644
--- a/web/src/features/models/components/pricing-tiers/TierConditionsEditor.tsx
+++ b/web/src/features/models/components/PricingSection/components/TierConditionsEditor.tsx
@@ -19,7 +19,7 @@ import {
SelectValue,
} from "@/src/components/ui/select";
import type { UseFormReturn } from "react-hook-form";
-import type { FormUpsertModel } from "../../validation";
+import type { FormUpsertModel } from "@/src/features/models/validation";
type TierConditionsEditorProps = {
tierIndex: number;
diff --git a/web/src/features/models/components/PricingSection/components/TierPrefillButtons.tsx b/web/src/features/models/components/PricingSection/components/TierPrefillButtons.tsx
new file mode 100644
index 0000000000..832f2becd0
--- /dev/null
+++ b/web/src/features/models/components/PricingSection/components/TierPrefillButtons.tsx
@@ -0,0 +1,54 @@
+import { Button } from "@/src/components/ui/button";
+import { FormDescription } from "@/src/components/ui/form";
+
+type TierPrefillButtonsProps = {
+ onPrefill: (usageTypes: string[]) => void;
+};
+
+export type { TierPrefillButtonsProps };
+
+const TEMPLATES: { label: string; usageTypes: string[] }[] = [
+ {
+ label: "OpenAI",
+ usageTypes: [
+ "input",
+ "output",
+ "input_cached_tokens",
+ "output_reasoning_tokens",
+ ],
+ },
+ {
+ label: "Anthropic",
+ usageTypes: [
+ "input",
+ "input_tokens",
+ "output",
+ "output_tokens",
+ "cache_creation_input_tokens",
+ "cache_read_input_tokens",
+ "input_cache_creation_5m",
+ "input_cache_creation_1h",
+ ],
+ },
+];
+
+export function TierPrefillButtons({ onPrefill }: TierPrefillButtonsProps) {
+ return (
+ <div className="space-y-2">
+ <FormDescription>Prefill usage types from template:</FormDescription>
+ <div className="flex gap-2">
+ {TEMPLATES.map((template) => (
+ <Button
+ key={template.label}
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onPrefill(template.usageTypes)}
+ >
+ {template.label}
+ </Button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/features/models/components/PricingSection/components/TierPriceEditor.tsx b/web/src/features/models/components/PricingSection/components/TierPriceEditor.tsx
new file mode 100644
index 0000000000..a8359ec63f
--- /dev/null
+++ b/web/src/features/models/components/PricingSection/components/TierPriceEditor.tsx
@@ -0,0 +1,147 @@
+import { MinusCircle, PlusCircle } from "lucide-react";
+import { useWatch } from "react-hook-form";
+import { Button } from "@/src/components/ui/button";
+import { Input } from "@/src/components/ui/input";
+import {
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { parsePriceInput } from "@/src/features/models/fns/parsePriceInput";
+import { PricePreview } from "@/src/features/models/components/PricePreview";
+import type { FieldArrayWithId, UseFormReturn } from "react-hook-form";
+import type { FormUpsertModel } from "@/src/features/models/validation";
+
+type TierPriceEditorProps = {
+ tierIndex: number;
+ form: UseFormReturn<FormUpsertModel>;
+ isDefault: boolean;
+ usageTypeRows: FieldArrayWithId<FormUpsertModel, "usageTypes", "id">[];
+ onAddUsageType: () => void;
+ onRemoveUsageType: (index: number) => void;
+};
+
+export type { TierPriceEditorProps };
+
+export function TierPriceEditor({
+ tierIndex,
+ form,
+ isDefault,
+ usageTypeRows,
+ onAddUsageType,
+ onRemoveUsageType,
+}: TierPriceEditorProps) {
+ // Names live on the model, prices on the tier; both are watched so a rename
+ // in the default tier shows up in every tier's rows immediately.
+ const usageTypeValues = useWatch({
+ control: form.control,
+ name: "usageTypes",
+ });
+ const tierPrices = useWatch({
+ control: form.control,
+ name: `pricingTiers.${tierIndex}.prices`,
+ });
+ const tierName = useWatch({
+ control: form.control,
+ name: `pricingTiers.${tierIndex}.name`,
+ });
+
+ const nameOf = (index: number) =>
+ usageTypeValues?.[index]?.name ?? usageTypeRows[index]?.name ?? "";
+
+ const previewPrices = usageTypeRows.flatMap((row, index) => {
+ const price = parsePriceInput(tierPrices?.[row.key]);
+ const usageType = nameOf(index).trim();
+ return price === null || !usageType
+ ? []
+ : [{ key: row.key, usageType, price }];
+ });
+
+ return (
+ <div className="space-y-3">
+ <FormLabel>Prices</FormLabel>
+ <div className="text-muted-foreground grid grid-cols-2 gap-1 text-sm">
+ <span>Usage type</span>
+ <span>Price per unit</span>
+ </div>
+ {usageTypeRows.map((row, index) => (
+ // The row key is opaque form state, so no edit can reorder or remount
+ // these inputs.
+ <div key={row.key} className="grid grid-cols-2 items-start gap-1">
+ {isDefault ? (
+ <FormField
+ control={form.control}
+ name={`usageTypes.${index}.name`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Key (e.g. input, output)"
+ aria-label={`Usage type ${index + 1}`}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : (
+ // Usage types belong to the default tier; here they are just labels.
+ <span
+ className="flex h-9 items-center truncate text-sm"
+ title={nameOf(index)}
+ >
+ {nameOf(index)}
+ </span>
+ )}
+ <div className="flex gap-1">
+ <FormField
+ control={form.control}
+ name={`pricingTiers.${tierIndex}.prices.${row.key}`}
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormControl>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ inputMode="decimal"
+ placeholder="Price per unit"
+ aria-label={`${tierName} price for ${nameOf(index) || `usage type ${index + 1}`}`}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {isDefault && (
+ <Button
+ type="button"
+ variant="outline"
+ title="Remove price"
+ size="icon"
+ disabled={usageTypeRows.length <= 1}
+ onClick={() => onRemoveUsageType(index)}
+ >
+ <MinusCircle className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ ))}
+ {isDefault && (
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={onAddUsageType}
+ className="flex items-center gap-1"
+ >
+ <PlusCircle className="h-4 w-4" />
+ <span>Add Price</span>
+ </Button>
+ )}
+ <PricePreview prices={previewPrices} />
+ </div>
+ );
+}
diff --git a/web/src/features/models/components/ProvidedModelNameCell.tsx b/web/src/features/models/components/ProvidedModelNameCell.tsx
index b03e113a3a..7607af7d8d 100644
--- a/web/src/features/models/components/ProvidedModelNameCell.tsx
+++ b/web/src/features/models/components/ProvidedModelNameCell.tsx
@@ -1,6 +1,6 @@
import { PlusCircle } from "lucide-react";
import TableIdOrName from "@/src/components/table/table-id";
-import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog";
/**
* Renders the "Provided Model Name" cell shared by the generations and events
diff --git a/web/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog.clienttest.tsx b/web/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog.clienttest.tsx
new file mode 100644
index 0000000000..3b61e8d4cd
--- /dev/null
+++ b/web/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog.clienttest.tsx
@@ -0,0 +1,276 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+
+import { type GetModelResult } from "@/src/features/models/validation";
+
+const upsertMutateAsync = vi.fn().mockResolvedValue({
+ id: "model-1",
+ modelName: "gpt-realtime-2.1",
+});
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ useUtils: () => ({ models: { invalidate: vi.fn() } }),
+ models: {
+ upsert: {
+ useMutation: () => ({
+ mutateAsync: upsertMutateAsync,
+ isPending: false,
+ }),
+ },
+ },
+ },
+}));
+
+vi.mock("next/router", () => ({
+ useRouter: () => ({ push: vi.fn(), query: { projectId: "p1" } }),
+}));
+
+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
+ usePostHogClientCapture: () => vi.fn(),
+}));
+
+vi.mock("@/src/features/notifications/showSuccessToast", () => ({
+ showSuccessToast: vi.fn(),
+}));
+
+vi.mock("@/src/components/editor", () => ({
+ CodeMirrorEditor: () => null,
+}));
+
+import { UpsertModelFormDialog } from "./UpsertModelFormDialog";
+
+const defaultTier = {
+ id: "tier-default",
+ name: "Standard",
+ isDefault: true,
+ priority: 0,
+ conditions: [],
+ prices: { text_input: 0.000004, text_output: 0.000016, audio: 0.00003 },
+};
+
+const longContextTier = {
+ id: "tier-long",
+ name: "Long context",
+ isDefault: false,
+ priority: 1,
+ conditions: [
+ {
+ usageDetailPattern: "^text_input",
+ operator: "gt" as const,
+ value: 128000,
+ caseSensitive: false,
+ },
+ ],
+ prices: { text_input: 0.000008, text_output: 0.000032, audio: 0.00006 },
+};
+
+const modelData = (
+ pricingTiers: GetModelResult["pricingTiers"],
+): GetModelResult => ({
+ id: "model-1",
+ projectId: "p1",
+ modelName: "gpt-realtime-2.1",
+ matchPattern: "(?i)^(gpt-realtime-2.1)$",
+ tokenizerConfig: null,
+ tokenizerId: null,
+ pricingTiers,
+});
+
+/** Types character by character, as a user does — one change event per key. */
+const typeInto = (input: HTMLInputElement, text: string) => {
+ for (const character of text) {
+ fireEvent.change(input, { target: { value: input.value + character } });
+ }
+};
+
+const retype = (input: HTMLInputElement, text: string) => {
+ fireEvent.change(input, { target: { value: "" } });
+ typeInto(input, text);
+};
+
+// Queried by placeholder, so these tests do not depend on the editor's markup.
+const usageTypeInputs = () =>
+ screen.getAllByPlaceholderText(
+ "Key (e.g. input, output)",
+ ) as HTMLInputElement[];
+const priceInputs = () =>
+ screen.getAllByPlaceholderText("Price per unit") as HTMLInputElement[];
+
+const openEditDialog = (pricingTiers: GetModelResult["pricingTiers"]) => {
+ render(
+ <UpsertModelFormDialog
+ action="edit"
+ projectId="p1"
+ modelData={modelData(pricingTiers)}
+ >
+ <button>Open editor</button>
+ </UpsertModelFormDialog>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
+};
+
+const openCloneDialog = (matchPattern: string) => {
+ render(
+ <UpsertModelFormDialog
+ action="clone"
+ projectId="p1"
+ modelData={{ ...modelData([defaultTier]), matchPattern }}
+ >
+ <button>Open editor</button>
+ </UpsertModelFormDialog>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
+};
+
+const submit = () =>
+ fireEvent.click(screen.getByRole("button", { name: /^(Save|Submit)$/ }));
+
+describe("UpsertModelFormDialog price editor", () => {
+ beforeAll(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ Element.prototype.scrollIntoView = vi.fn();
+ Element.prototype.hasPointerCapture = vi.fn();
+ });
+
+ beforeEach(() => {
+ upsertMutateAsync.mockClear();
+ });
+
+ it("keeps every keystroke of a usage type that extends an existing one", () => {
+ openEditDialog([defaultTier]);
+
+ // Typing `text_input_cached` passes through the existing key `text_input`.
+ retype(usageTypeInputs()[2], "text_input_cached");
+ retype(priceInputs()[2], "0.0000025");
+
+ expect(usageTypeInputs().map((input) => input.value)).toEqual([
+ "text_input",
+ "text_output",
+ "text_input_cached",
+ ]);
+ expect(priceInputs()[2].value).toBe("0.0000025");
+ });
+
+ it("renaming a usage type keeps the other rows and the custom tier's price", async () => {
+ openEditDialog([defaultTier, longContextTier]);
+
+ retype(usageTypeInputs()[0], "text_input_cached");
+ submit();
+
+ await waitFor(() => expect(upsertMutateAsync).toHaveBeenCalledTimes(1));
+ expect(upsertMutateAsync.mock.calls[0][0].pricingTiers).toEqual([
+ {
+ name: "Standard",
+ isDefault: true,
+ priority: 0,
+ conditions: [],
+ prices: {
+ text_input_cached: 0.000004,
+ text_output: 0.000016,
+ audio: 0.00003,
+ },
+ },
+ {
+ name: "Long context",
+ isDefault: false,
+ priority: 1,
+ conditions: longContextTier.conditions,
+ // The rename must not zero this tier's price for the renamed key.
+ prices: {
+ text_input_cached: 0.000008,
+ text_output: 0.000032,
+ audio: 0.00006,
+ },
+ },
+ ]);
+ });
+
+ it("renaming a clone keeps a custom match pattern but follows a generated one", () => {
+ const custom = String.raw`(?i)^(gpt-realtime-2\.\d+)$`;
+ openCloneDialog(custom);
+ typeInto(
+ document.querySelector('input[name="modelName"]') as HTMLInputElement,
+ "-mine",
+ );
+ expect(
+ (document.querySelector('input[name="matchPattern"]') as HTMLInputElement)
+ .value,
+ ).toBe(custom);
+
+ cleanup();
+ openCloneDialog("(?i)^(gpt-realtime-2.1)$");
+ typeInto(
+ document.querySelector('input[name="modelName"]') as HTMLInputElement,
+ "-mine",
+ );
+ expect(
+ (document.querySelector('input[name="matchPattern"]') as HTMLInputElement)
+ .value,
+ ).toBe("(?i)^(gpt-realtime-2.1-mine)$");
+ });
+
+ it("saving is a checkpoint: saved values are clean, an in-flight edit is not", async () => {
+ const confirm = vi.spyOn(window, "confirm").mockReturnValue(false);
+
+ // Saved values become the new baseline: closing needs no confirmation.
+ openEditDialog([defaultTier]);
+ retype(priceInputs()[0], "0.000009");
+ await act(async () => submit());
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(confirm).not.toHaveBeenCalled();
+ expect(document.querySelector('div[role="dialog"]')).toBeNull();
+
+ cleanup();
+
+ // An edit typed while the save is in flight was never submitted, so it
+ // stays unsaved work and the discard guard still fires for it.
+ let settleSave: (model: {
+ id: string;
+ modelName: string;
+ }) => void = () => {};
+ upsertMutateAsync.mockImplementationOnce(
+ () => new Promise((resolve) => (settleSave = resolve)),
+ );
+ openEditDialog([defaultTier]);
+ retype(priceInputs()[0], "0.000009");
+ await act(async () => submit());
+ retype(priceInputs()[0], "0.000011");
+ await act(async () => {
+ settleSave({ id: "model-1", modelName: "gpt-realtime-2.1" });
+ });
+
+ expect(priceInputs()[0].value).toBe("0.000011");
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(confirm).toHaveBeenCalledTimes(1);
+ expect(document.querySelector('div[role="dialog"]')).not.toBeNull();
+ confirm.mockRestore();
+ });
+
+ it("shows inline errors instead of silently refusing to submit", async () => {
+ openEditDialog([defaultTier]);
+
+ fireEvent.change(usageTypeInputs()[0], { target: { value: "audio" } });
+ fireEvent.change(priceInputs()[1], { target: { value: "" } });
+ submit();
+
+ expect(
+ await screen.findByText('Duplicate usage type "audio"'),
+ ).toBeTruthy();
+ expect(screen.getByText("Enter a price of 0 or more")).toBeTruthy();
+ expect(upsertMutateAsync).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/features/models/components/UpsertModelFormDialog.tsx b/web/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog.tsx
similarity index 63%
rename from web/src/features/models/components/UpsertModelFormDialog.tsx
rename to web/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog.tsx
index 8b11fc9f7c..96bd20c5d5 100644
--- a/web/src/features/models/components/UpsertModelFormDialog.tsx
+++ b/web/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog.tsx
@@ -1,8 +1,10 @@
/* eslint-disable @repo/no-abstracted-overlay-trigger */
/* eslint @repo/no-style-props: "off" */
+import cloneDeep from "lodash/cloneDeep";
+import isEqual from "lodash/isEqual";
import Link from "next/link";
-import { useEffect, useState, useMemo } from "react";
-import { useForm, useFieldArray } from "react-hook-form";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
import { CodeMirrorEditor } from "@/src/components/editor";
import { Button } from "@/src/components/ui/button";
@@ -33,6 +35,9 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
+import { buildFormValues } from "@/src/features/models/fns/buildFormValues";
+import { matchPatternFor } from "@/src/features/models/fns/matchPatternFor";
+import { toPricingTierInputs } from "@/src/features/models/fns/toPricingTierInputs";
import {
type FormUpsertModel,
FormUpsertModelSchema,
@@ -44,7 +49,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/router";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
-import { PricingSection } from "./pricing-tiers/PricingSection";
+import { PricingSection } from "@/src/features/models/components/PricingSection/PricingSection";
type UpsertModelDialogProps =
| {
@@ -65,6 +70,9 @@ type UpsertModelDialogProps =
className?: string;
};
+const DISCARD_CHANGES_MESSAGE =
+ "Discard your unsaved changes to this model definition?";
+
export const UpsertModelFormDialog = (({
children,
...props
@@ -75,159 +83,25 @@ export const UpsertModelFormDialog = (({
const utils = api.useUtils();
const [open, setOpen] = useState(false);
- // Initialize form default values
- const defaultValues: FormUpsertModel = useMemo(() => {
- if (props.action !== "create") {
- // EDIT or CLONE: Load all tiers
- const loadedTiers = props.modelData.pricingTiers.map((tier) => ({
- id: tier.id,
- name: tier.name,
- isDefault: tier.isDefault,
- priority: tier.priority,
- conditions: tier.conditions,
- prices: tier.prices,
- }));
-
- return {
- modelName: props.modelData.modelName,
- matchPattern: props.modelData.matchPattern,
- tokenizerId: props.modelData.tokenizerId,
- tokenizerConfig: JSON.stringify(props.modelData.tokenizerConfig ?? {}),
- pricingTiers: loadedTiers,
- };
- }
- // CREATE: Start with 1 default tier
- return {
- modelName: props.prefilledModelData?.modelName ?? "",
- matchPattern: props.prefilledModelData?.modelName
- ? `(?i)^(${props.prefilledModelData?.modelName})$`
- : "",
- tokenizerId: null,
- tokenizerConfig: null,
- pricingTiers: [
- {
- name: "Standard",
- isDefault: true,
- priority: 0,
- conditions: [],
- prices: props.prefilledModelData?.prices ?? {
- input: 0.000001,
- output: 0.000002,
- },
- },
- ],
- };
- }, [props]);
-
const form = useForm({
resolver: zodResolver(FormUpsertModelSchema),
- defaultValues,
+ defaultValues: buildFormValues(props),
});
- const modelName = form.watch("modelName");
- const matchPattern = form.watch("matchPattern");
const tokenizerId = form.watch("tokenizerId");
- const { fields, append, remove } = useFieldArray({
- control: form.control,
- name: "pricingTiers",
- });
-
- // Watch default tier prices for syncing
- const defaultTierIndex = fields.findIndex((f) => f.isDefault);
- const defaultTierPrices =
- defaultTierIndex !== -1
- ? form.watch(`pricingTiers.${defaultTierIndex}.prices`)
- : undefined;
-
- // Compute keys signature - memoized to prevent unnecessary updates
- const defaultKeysSignature = useMemo(() => {
- if (!defaultTierPrices) return "";
- return Object.keys(defaultTierPrices).sort().join(",");
- }, [defaultTierPrices]);
-
- // Auto-assign priorities based on order
- useEffect(() => {
- fields.forEach((field, index) => {
- const tier = form.getValues(`pricingTiers.${index}`);
- const expectedPriority = tier.isDefault ? 0 : index;
- if (tier.priority !== expectedPriority) {
- form.setValue(`pricingTiers.${index}.priority`, expectedPriority);
- }
- });
- }, [fields, form]);
-
- // Sync usage keys from default tier to all non-default tiers
- useEffect(() => {
- if (!defaultTierPrices || defaultTierIndex === -1 || !defaultKeysSignature)
- return;
-
- const defaultKeys = defaultKeysSignature.split(",");
-
- fields.forEach((field, index) => {
- if (field.isDefault) return;
-
- const currentPrices = form.getValues(`pricingTiers.${index}.prices`);
- const currentKeys = Object.keys(currentPrices).sort();
-
- // Only update if keys don't match
- const keysMatch =
- defaultKeys.length === currentKeys.length &&
- defaultKeys.every((key, i) => key === currentKeys[i]);
-
- if (!keysMatch) {
- const newPrices: Record<string, number> = {};
- defaultKeys.forEach((key) => {
- newPrices[key] = currentPrices[key] ?? 0;
- });
- form.setValue(`pricingTiers.${index}.prices`, newPrices);
- }
- });
- }, [defaultKeysSignature, defaultTierPrices, defaultTierIndex, fields, form]);
-
- // prefill match pattern if model name changes
- useEffect(() => {
- const getRegexString = (modelName: string) => `(?i)^(${modelName})$`;
-
- if (
- modelName &&
- (!matchPattern ||
- matchPattern === `(?i)^(${modelName.slice(0, -1)})$` ||
- matchPattern === `(?i)^(${modelName})$`)
- ) {
- form.setValue("matchPattern", getRegexString(modelName));
- }
- }, [modelName, matchPattern, form]);
-
- const upsertModelMutation = api.models.upsert.useMutation({
- onSuccess: (upsertedModel) => {
- utils.models.invalidate();
- form.reset();
- setOpen(false);
- showSuccessToast({
- title: `Model ${props.action === "edit" ? "updated" : "created"}`,
- description: `The model '${upsertedModel.modelName}' has been successfully ${props.action === "edit" ? "updated" : "created"}. New generations will use these model prices.`,
- });
- router.push(
- `/project/${props.projectId}/settings/models/${upsertedModel.id}`,
- );
- },
- onError: (error) => setFormError(error.message),
- });
+ const upsertModelMutation = api.models.upsert.useMutation();
const onSubmit = async (values: FormUpsertModel) => {
capture("models:new_form_submit");
+ setFormError(null);
+ // Snapshot before the await: nothing typed while the save is in flight may
+ // become part of the saved baseline, or the dirty guard would let it go.
+ // getValues() copies only the top level, so the clone is load-bearing.
+ const submitted = cloneDeep(form.getValues());
- // Transform FormPricingTier[] -> PricingTierInput[] (remove id field and filter prices)
- const pricingTiers = values.pricingTiers.map(({ id: _id, ...tier }) => ({
- ...tier,
- prices: Object.fromEntries(
- Object.entries(tier.prices).filter(([_, value]) => value != null),
- ) as Record<string, number>,
- }));
-
- await upsertModelMutation
- .mutateAsync({
+ try {
+ const upsertedModel = await upsertModelMutation.mutateAsync({
modelId: props.action === "edit" ? props.modelData.id : null,
projectId: props.projectId,
modelName:
@@ -235,37 +109,46 @@ export const UpsertModelFormDialog = (({
? props.modelData.modelName
: values.modelName,
matchPattern: values.matchPattern,
- pricingTiers,
+ pricingTiers: toPricingTierInputs(values),
tokenizerId: values.tokenizerId,
tokenizerConfig:
values.tokenizerConfig &&
typeof JSON.parse(values.tokenizerConfig) === "object"
? (JSON.parse(values.tokenizerConfig) as Record<string, number>)
: undefined,
- })
- .catch((error) => {
- setFormError(error.message);
});
- };
- const addTier = () => {
- const defaultTier = fields.find((f) => f.isDefault);
- if (!defaultTier) return;
+ utils.models.invalidate();
+ showSuccessToast({
+ title: `Model ${props.action === "edit" ? "updated" : "created"}`,
+ description: `The model '${upsertedModel.modelName}' has been successfully ${props.action === "edit" ? "updated" : "created"}. New generations will use these model prices.`,
+ });
+
+ // Editing is a checkpoint, not an exit: keep the dialog and its context.
+ if (props.action === "edit") {
+ const live = form.getValues();
+ form.reset(submitted); // what we saved is the new clean baseline
+ if (!isEqual(live, submitted)) {
+ // Typed while the save was in flight: still the user's unsaved work.
+ form.reset(live, { keepDefaultValues: true });
+ }
+ return;
+ }
+
+ setOpen(false);
+ router.push(
+ `/project/${props.projectId}/settings/models/${upsertedModel.id}`,
+ );
+ } catch (error) {
+ setFormError(error instanceof Error ? error.message : String(error));
+ }
+ };
- append({
- name: `Custom Tier ${fields.length}`,
- isDefault: false,
- priority: fields.length,
- conditions: [
- {
- usageDetailPattern: "^input",
- operator: "gt",
- value: 0,
- caseSensitive: false,
- },
- ],
- prices: { ...defaultTier.prices }, // Copy default tier prices
- });
+ const requestClose = () => {
+ if (form.formState.isDirty && !window.confirm(DISCARD_CHANGES_MESSAGE)) {
+ return;
+ }
+ setOpen(false);
};
return (
@@ -273,10 +156,13 @@ export const UpsertModelFormDialog = (({
open={open}
onOpenChange={(newOpen) => {
if (!newOpen) {
- form.reset();
- setFormError(null);
+ requestClose();
+ return;
}
- setOpen(newOpen);
+ // Reopening starts from the model's current data, not the last edit.
+ form.reset(buildFormValues(props));
+ setFormError(null);
+ setOpen(true);
}}
>
<DialogTrigger
@@ -328,7 +214,28 @@ export const UpsertModelFormDialog = (({
using the same name and match pattern.
</FormDescription>
<FormControl>
- <Input {...field} />
+ <Input
+ {...field}
+ onChange={(e) => {
+ const previousName = form.getValues("modelName");
+ const nextName = e.target.value;
+ field.onChange(e);
+
+ // Follow the name only while the pattern is still the
+ // one we generated — a hand-written or cloned pattern
+ // is the user's, and typing a name must not touch it.
+ const pattern = form.getValues("matchPattern");
+ if (
+ !pattern ||
+ pattern === matchPatternFor(previousName)
+ ) {
+ form.setValue(
+ "matchPattern",
+ nextName ? matchPatternFor(nextName) : "",
+ );
+ }
+ }}
+ />
</FormControl>
<FormMessage />
</FormItem>
@@ -354,13 +261,7 @@ export const UpsertModelFormDialog = (({
)}
/>
- {/* PRICING SECTION */}
- <PricingSection
- fields={fields}
- form={form}
- remove={remove}
- addTier={addTier}
- />
+ <PricingSection form={form} />
<FormField
control={form.control}
@@ -440,16 +341,12 @@ export const UpsertModelFormDialog = (({
</DialogBody>
<DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => setOpen(false)}
- >
+ <Button type="button" variant="outline" onClick={requestClose}>
Cancel
</Button>
<Button type="submit" loading={upsertModelMutation.isPending}>
- Submit
+ {props.action === "edit" ? "Save" : "Submit"}
</Button>
</DialogFooter>
</form>
diff --git a/web/src/features/models/components/pricing-tiers/PricingSection.tsx b/web/src/features/models/components/pricing-tiers/PricingSection.tsx
deleted file mode 100644
index d38f01dae6..0000000000
--- a/web/src/features/models/components/pricing-tiers/PricingSection.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { PlusCircle } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { FormDescription, FormLabel } from "@/src/components/ui/form";
-import { Accordion } from "@/src/components/ui/accordion";
-import { TierAccordionItem } from "./TierAccordionItem";
-import { TierPriceEditor } from "./TierPriceEditor";
-import { TierPrefillButtons } from "./TierPrefillButtons";
-import type { UseFormReturn, UseFieldArrayReturn } from "react-hook-form";
-import type { FormUpsertModel } from "../../validation";
-
-type PricingSectionProps = {
- fields: UseFieldArrayReturn<FormUpsertModel, "pricingTiers">["fields"];
- form: UseFormReturn<FormUpsertModel>;
- remove: UseFieldArrayReturn<FormUpsertModel, "pricingTiers">["remove"];
- addTier: () => void;
-};
-
-export type { PricingSectionProps };
-
-export function PricingSection({
- fields,
- form,
- remove,
- addTier,
-}: PricingSectionProps) {
- const hasMultipleTiers = fields.length > 1;
- const defaultTierIndex = fields.findIndex((f) => f.isDefault);
-
- if (!hasMultipleTiers) {
- // SIMPLE VIEW: Just show prices for the single default tier
- return (
- <div className="space-y-4">
- <div>
- <FormLabel>Prices</FormLabel>
- <FormDescription>
- Set prices per usage type for this model. Usage types must exactly
- match the keys of the ingested usage details.
- </FormDescription>
- </div>
-
- <TierPrefillButtons tierIndex={defaultTierIndex} form={form} />
- <TierPriceEditor
- tierIndex={defaultTierIndex}
- form={form}
- isDefault={true}
- />
-
- <Button type="button" variant="ghost" onClick={addTier}>
- <PlusCircle className="mr-2 h-4 w-4" />
- Add Custom Pricing Tier
- </Button>
- </div>
- );
- }
-
- // ACCORDION VIEW: Multiple tiers
- return (
- <div className="space-y-4">
- <div>
- <FormLabel>Pricing Tiers</FormLabel>
- <FormDescription>
- Define pricing rules evaluated in priority order. Tiers are checked
- from top to bottom until conditions match.
- </FormDescription>
- </div>
-
- <Accordion
- type="multiple"
- defaultValue={fields.map((_, i) => `tier-${i}`)} // All expanded
- className="space-y-2"
- >
- {fields.map((field, index) => (
- <TierAccordionItem
- key={field.id}
- tier={field}
- index={index}
- form={form}
- remove={remove}
- isDefault={field.isDefault}
- />
- ))}
- </Accordion>
-
- <Button type="button" variant="outline" onClick={addTier}>
- <PlusCircle className="mr-2 h-4 w-4" />
- Add Custom Tier
- </Button>
- </div>
- );
-}
diff --git a/web/src/features/models/components/pricing-tiers/TierPrefillButtons.tsx b/web/src/features/models/components/pricing-tiers/TierPrefillButtons.tsx
deleted file mode 100644
index 7f2fc08d15..0000000000
--- a/web/src/features/models/components/pricing-tiers/TierPrefillButtons.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { Button } from "@/src/components/ui/button";
-import { FormDescription } from "@/src/components/ui/form";
-import type { UseFormReturn } from "react-hook-form";
-import type { FormUpsertModel } from "../../validation";
-
-type TierPrefillButtonsProps = {
- tierIndex: number;
- form: UseFormReturn<FormUpsertModel>;
-};
-
-export type { TierPrefillButtonsProps };
-
-export function TierPrefillButtons({
- tierIndex,
- form,
-}: TierPrefillButtonsProps) {
- const prices = form.watch(`pricingTiers.${tierIndex}.prices`) || {};
-
- return (
- <div className="space-y-2">
- <FormDescription>Prefill usage types from template:</FormDescription>
- <div className="flex gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => {
- form.setValue(`pricingTiers.${tierIndex}.prices`, {
- input: 0,
- output: 0,
- input_cached_tokens: 0,
- output_reasoning_tokens: 0,
- ...prices,
- });
- }}
- >
- OpenAI
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => {
- form.setValue(`pricingTiers.${tierIndex}.prices`, {
- input: 0,
- input_tokens: 0,
- output: 0,
- output_tokens: 0,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- input_cache_creation_5m: 0,
- input_cache_creation_1h: 0,
- ...prices,
- });
- }}
- >
- Anthropic
- </Button>
- </div>
- </div>
- );
-}
diff --git a/web/src/features/models/components/pricing-tiers/TierPriceEditor.tsx b/web/src/features/models/components/pricing-tiers/TierPriceEditor.tsx
deleted file mode 100644
index 50b5bc1489..0000000000
--- a/web/src/features/models/components/pricing-tiers/TierPriceEditor.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { MinusCircle, PlusCircle } from "lucide-react";
-import { Button } from "@/src/components/ui/button";
-import { Input } from "@/src/components/ui/input";
-import { FormLabel } from "@/src/components/ui/form";
-import { PricePreview } from "../PricePreview";
-import type { UseFormReturn } from "react-hook-form";
-import type { FormUpsertModel } from "../../validation";
-
-type TierPriceEditorProps = {
- tierIndex: number;
- form: UseFormReturn<FormUpsertModel>;
- isDefault: boolean;
-};
-
-export type { TierPriceEditorProps };
-
-export function TierPriceEditor({
- tierIndex,
- form,
- isDefault,
-}: TierPriceEditorProps) {
- const prices = form.watch(`pricingTiers.${tierIndex}.prices`) || {};
-
- return (
- <div className="space-y-3">
- <FormLabel>Prices</FormLabel>
- <div className="text-muted-foreground grid grid-cols-2 gap-1 text-sm">
- <span>Usage type</span>
- <span>Price</span>
- </div>
- {Object.entries(prices).map(([key, value], index) => (
- <div key={index} className="grid grid-cols-2 gap-1">
- <Input
- placeholder="Key (e.g. input, output)"
- value={key}
- disabled={!isDefault}
- onChange={(e) => {
- const newKey = e.target.value;
-
- // Prevent overwriting existing keys (unless it's the same key)
- if (newKey !== key && prices[newKey] !== undefined) {
- return; // Don't allow the change
- }
-
- const newPrices = { ...prices };
- const oldValue = newPrices[key];
- delete newPrices[key];
- newPrices[newKey] = oldValue;
- form.setValue(`pricingTiers.${tierIndex}.prices`, newPrices);
- }}
- className={!isDefault ? "bg-muted cursor-not-allowed" : ""}
- />
- <div className="flex gap-1">
- <Input
- type="number"
- placeholder="Price per unit"
- value={value as number}
- step="0.000001"
- onChange={(e) => {
- form.setValue(`pricingTiers.${tierIndex}.prices`, {
- ...prices,
- [key]: parseFloat(e.target.value),
- });
- }}
- />
- {isDefault && (
- <Button
- type="button"
- variant="outline"
- title="Remove price"
- size="icon"
- onClick={() => {
- const newPrices = { ...prices };
- delete newPrices[key];
- form.setValue(`pricingTiers.${tierIndex}.prices`, newPrices);
- }}
- >
- <MinusCircle className="h-4 w-4" />
- </Button>
- )}
- </div>
- </div>
- ))}
- {isDefault && (
- <Button
- type="button"
- variant="ghost"
- onClick={() => {
- // Generate unique key name
- let counter = 1;
- let newKey = "new_usage_type";
- while (prices[newKey] !== undefined) {
- newKey = `new_usage_type_${counter}`;
- counter++;
- }
- form.setValue(`pricingTiers.${tierIndex}.prices`, {
- ...prices,
- [newKey]: 0.000001,
- });
- }}
- className="flex items-center gap-1"
- >
- <PlusCircle className="h-4 w-4" />
- <span>Add Price</span>
- </Button>
- )}
- <PricePreview prices={prices} />
- </div>
- );
-}
diff --git a/web/src/features/models/components/test-match/MatchedTierCard.tsx b/web/src/features/models/components/test-match/MatchedTierCard.tsx
index b62694fa5b..f3fe857215 100644
--- a/web/src/features/models/components/test-match/MatchedTierCard.tsx
+++ b/web/src/features/models/components/test-match/MatchedTierCard.tsx
@@ -8,7 +8,7 @@ import { Badge } from "@/src/components/ui/badge";
import { useMemo } from "react";
import { usePriceUnitMultiplier } from "@/src/features/models/hooks/usePriceUnitMultiplier";
import Decimal from "decimal.js";
-import { getMaxDecimals } from "@/src/features/models/utils";
+import { getMaxDecimals } from "@/src/features/models/fns/getMaxDecimals";
type MatchedTierCardProps = {
tier: {
diff --git a/web/src/features/models/fns/buildFormValues.ts b/web/src/features/models/fns/buildFormValues.ts
new file mode 100644
index 0000000000..9846b228f4
--- /dev/null
+++ b/web/src/features/models/fns/buildFormValues.ts
@@ -0,0 +1,95 @@
+import Decimal from "decimal.js";
+
+import { matchPatternFor } from "@/src/features/models/fns/matchPatternFor";
+import {
+ type FormPricingTier,
+ type FormUpsertModel,
+ type FormUsageType,
+ type GetModelResult,
+} from "@/src/features/models/validation";
+
+/** What the dialog knows about the model being created, edited or cloned. */
+export type ModelFormSource =
+ | {
+ action: "create";
+ prefilledModelData?: {
+ modelName?: string;
+ prices?: Record<string, number>;
+ };
+ }
+ | { action: "edit" | "clone"; modelData: GetModelResult };
+
+const CREATE_DEFAULT_PRICES: Record<string, number> = {
+ input: 0.000001,
+ output: 0.000002,
+};
+
+/** Full decimal notation — `String(1e-7)` would put "1e-7" in the input. */
+const formatPrice = (price: number) => new Decimal(price).toFixed();
+
+const toUsageTypeRows = (names: string[]): FormUsageType[] =>
+ names.map((name, index) => ({ key: `u${index}`, name }));
+
+const pricesByRowKey = (
+ usageTypes: FormUsageType[],
+ prices: Record<string, number>,
+): FormPricingTier["prices"] =>
+ Object.fromEntries(
+ usageTypes.map((row) => {
+ const price = prices[row.name];
+ return [row.key, price === undefined ? "" : formatPrice(price)];
+ }),
+ );
+
+export const buildFormValues = (source: ModelFormSource): FormUpsertModel => {
+ if (source.action === "create") {
+ const modelName = source.prefilledModelData?.modelName ?? "";
+ // A generation whose usage details only carry `total` prefills {} — that
+ // would open the dialog with no price rows at all.
+ const prefilled = source.prefilledModelData?.prices;
+ const prices =
+ prefilled && Object.keys(prefilled).length > 0
+ ? prefilled
+ : CREATE_DEFAULT_PRICES;
+ const usageTypes = toUsageTypeRows(Object.keys(prices));
+
+ return {
+ modelName,
+ matchPattern: modelName ? matchPatternFor(modelName) : "",
+ tokenizerId: null,
+ tokenizerConfig: null,
+ usageTypes,
+ pricingTiers: [
+ {
+ name: "Standard",
+ isDefault: true,
+ conditions: [],
+ prices: pricesByRowKey(usageTypes, prices),
+ },
+ ],
+ };
+ }
+
+ const { modelData } = source;
+ const tiers = [...modelData.pricingTiers].sort(
+ (a, b) => Number(b.isDefault) - Number(a.isDefault),
+ );
+ // Union across tiers, default tier first: never silently drop a priced key.
+ const usageTypes = toUsageTypeRows([
+ ...new Set(tiers.flatMap((tier) => Object.keys(tier.prices))),
+ ]);
+
+ return {
+ modelName: modelData.modelName,
+ matchPattern: modelData.matchPattern,
+ tokenizerId: modelData.tokenizerId,
+ tokenizerConfig: JSON.stringify(modelData.tokenizerConfig ?? {}),
+ usageTypes,
+ pricingTiers: tiers.map((tier) => ({
+ name: tier.name,
+ isDefault: tier.isDefault,
+ conditions: tier.conditions,
+ prices: pricesByRowKey(usageTypes, tier.prices),
+ })),
+ };
+};
diff --git a/web/src/features/models/fns/derivePriorities.ts b/web/src/features/models/fns/derivePriorities.ts
new file mode 100644
index 0000000000..913ba36773
--- /dev/null
+++ b/web/src/features/models/fns/derivePriorities.ts
@@ -0,0 +1,5 @@
+/** Priority is derived from tier order, so it can never drift or collide. */
+export const derivePriorities = (tiers: { isDefault: boolean }[]): number[] => {
+ let next = 1;
+ return tiers.map((tier) => (tier.isDefault ? 0 : next++));
+};
diff --git a/web/src/features/models/utils.ts b/web/src/features/models/fns/getMaxDecimals.ts
similarity index 100%
rename from web/src/features/models/utils.ts
rename to web/src/features/models/fns/getMaxDecimals.ts
diff --git a/web/src/features/models/fns/makeUsageTypeKeys.ts b/web/src/features/models/fns/makeUsageTypeKeys.ts
new file mode 100644
index 0000000000..8dc9ad1b98
--- /dev/null
+++ b/web/src/features/models/fns/makeUsageTypeKeys.ts
@@ -0,0 +1,16 @@
+import { type FormUsageType } from "@/src/features/models/validation";
+
+/** Row keys are opaque and only need to be unique within one form instance. */
+export const makeUsageTypeKeys = (
+ existing: Pick<FormUsageType, "key">[],
+ count: number,
+): string[] => {
+ const used = new Set(existing.map((row) => row.key));
+ const keys: string[] = [];
+ let candidate = existing.length;
+ while (keys.length < count) {
+ const key = `u${candidate++}`;
+ if (!used.has(key)) keys.push(key);
+ }
+ return keys;
+};
diff --git a/web/src/features/models/fns/matchPatternFor.ts b/web/src/features/models/fns/matchPatternFor.ts
new file mode 100644
index 0000000000..7c7ea105d7
--- /dev/null
+++ b/web/src/features/models/fns/matchPatternFor.ts
@@ -0,0 +1,2 @@
+/** The exact, case-insensitive Postgres pattern for one model name. */
+export const matchPatternFor = (modelName: string) => `(?i)^(${modelName})$`;
diff --git a/web/src/features/models/fns/parsePriceInput.ts b/web/src/features/models/fns/parsePriceInput.ts
new file mode 100644
index 0000000000..df16e2d58a
--- /dev/null
+++ b/web/src/features/models/fns/parsePriceInput.ts
@@ -0,0 +1,7 @@
+/** Returns the price as a number, or null when the input is not a usable price. */
+export const parsePriceInput = (raw: string | undefined): number | null => {
+ const trimmed = raw?.trim();
+ if (!trimmed) return null;
+ const parsed = Number(trimmed);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
+};
diff --git a/web/src/features/models/fns/toPricingTierInputs.ts b/web/src/features/models/fns/toPricingTierInputs.ts
new file mode 100644
index 0000000000..08f360e716
--- /dev/null
+++ b/web/src/features/models/fns/toPricingTierInputs.ts
@@ -0,0 +1,28 @@
+import { type PricingTierInput } from "@langfuse/shared";
+
+import { derivePriorities } from "@/src/features/models/fns/derivePriorities";
+import { parsePriceInput } from "@/src/features/models/fns/parsePriceInput";
+import { type FormUpsertModel } from "@/src/features/models/validation";
+
+/** Form values -> the API's per-tier price maps, keyed by usage type name. */
+export const toPricingTierInputs = (
+ values: Pick<FormUpsertModel, "usageTypes" | "pricingTiers">,
+): PricingTierInput[] => {
+ const priorities = derivePriorities(values.pricingTiers);
+
+ return values.pricingTiers.map((tier, tierIndex) => ({
+ name: tier.name.trim(),
+ isDefault: tier.isDefault,
+ priority: priorities[tierIndex],
+ conditions: tier.conditions.map((condition) => ({
+ ...condition,
+ caseSensitive: condition.caseSensitive ?? false,
+ })),
+ prices: Object.fromEntries(
+ values.usageTypes.flatMap((row) => {
+ const price = parsePriceInput(tier.prices[row.key]);
+ return price === null ? [] : [[row.name.trim(), price] as const];
+ }),
+ ),
+ }));
+};
diff --git a/web/src/features/models/validation.ts b/web/src/features/models/validation.ts
index 7d569aad0f..808075e86f 100644
--- a/web/src/features/models/validation.ts
+++ b/web/src/features/models/validation.ts
@@ -1,23 +1,24 @@
import { z } from "zod";
+
+import { parsePriceInput } from "@/src/features/models/fns/parsePriceInput";
import {
PricingTierConditionSchema,
PricingTierInputSchema,
validatePricingTiers,
} from "@langfuse/shared";
-export const UsageTypeSchema = z.string().regex(/^[a-zA-Z0-9_-]+$/);
+const USAGE_TYPE_PATTERN = /^[a-zA-Z0-9_-]+$/;
+export const UsageTypeSchema = z.string().regex(USAGE_TYPE_PATTERN);
export const PriceSchema = z.number().nonnegative();
export const TokenizerSchema = z.enum(["openai", "claude"]).nullish();
// Input version: allows optional prices for form
-export const PriceMapInputSchema = z.record(
- UsageTypeSchema,
- PriceSchema.optional(),
-);
+const PriceMapInputSchema = z.record(UsageTypeSchema, PriceSchema.optional());
-// Output version: filtered to only defined prices
+// Output version: filtered to only defined prices. A price of 0 is a real,
+// deliberate price — dropping it deleted the usage type on the next save.
export const PriceMapSchema = PriceMapInputSchema.transform((obj) => {
return Object.fromEntries(
- Object.entries(obj).filter(([_, value]) => Boolean(value)),
+ Object.entries(obj).filter(([_, value]) => value != null),
) as Record<string, number>;
}).pipe(z.record(UsageTypeSchema, PriceSchema));
@@ -32,14 +33,25 @@ export const PricingTierSchema = z.object({
export type PricingTier = z.infer<typeof PricingTierSchema>;
-// Form-level tier schema (includes optional id for edit mode)
+/**
+ * A usage type row is identified by its opaque `key`, never by its name: the
+ * name is the value being edited, and deriving row identity from it is what
+ * broke renames in two earlier attempts at this editor.
+ */
+const FormUsageTypeSchema = z.object({
+ key: z.string(),
+ name: z.string(),
+});
+
+export type FormUsageType = z.infer<typeof FormUsageTypeSchema>;
+
+// Form-level tier schema. Prices are keyed by usage type row key and held as
+// strings, so a half-typed "0." or "0.0000025" survives every keystroke.
export const FormPricingTierSchema = z.object({
- id: z.string().optional(), // For existing tiers in edit mode
name: z.string().min(1, "Tier name is required"),
isDefault: z.boolean(),
- priority: z.number().int(),
conditions: z.array(PricingTierConditionSchema),
- prices: PriceMapInputSchema, // Use input schema for form
+ prices: z.record(z.string(), z.string()),
});
// Use input type for form (allows optional/default fields)
@@ -90,29 +102,98 @@ export const UpsertModelSchema = z
);
export type UpsertModel = z.infer<typeof UpsertModelSchema>;
-export const FormUpsertModelSchema = z.object({
- modelName: z.string().min(1),
- matchPattern: z.string().min(1),
- tokenizerId: z.enum(["openai", "claude", "None"]).nullish(),
- tokenizerConfig: z
- .string()
- .refine(
- (value) => {
- try {
- JSON.parse(value);
- return true;
- } catch {
- return false;
+export const FormUpsertModelSchema = z
+ .object({
+ modelName: z.string().min(1),
+ matchPattern: z.string().min(1),
+ tokenizerId: z.enum(["openai", "claude", "None"]).nullish(),
+ tokenizerConfig: z
+ .string()
+ .refine(
+ (value) => {
+ try {
+ JSON.parse(value);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ {
+ message: "Tokenizer config needs to be valid JSON",
+ },
+ )
+ .transform((value) => (value === "{}" ? undefined : value))
+ .nullish(),
+ // Usage types are model-level: the API requires every tier to price the
+ // same set of keys, so the form models them once instead of per tier.
+ usageTypes: z.array(FormUsageTypeSchema).min(1),
+ pricingTiers: z.array(FormPricingTierSchema).min(1),
+ })
+ .superRefine(({ usageTypes, pricingTiers }, ctx) => {
+ const seenUsageTypes = new Set<string>();
+ usageTypes.forEach((row, index) => {
+ const path = ["usageTypes", index, "name"];
+ const name = row.name.trim();
+
+ if (!name) {
+ ctx.addIssue({ code: "custom", path, message: "Usage type required" });
+ } else if (!USAGE_TYPE_PATTERN.test(name)) {
+ ctx.addIssue({
+ code: "custom",
+ path,
+ message: "Only letters, numbers, hyphens and underscores",
+ });
+ } else if (seenUsageTypes.has(name)) {
+ ctx.addIssue({
+ code: "custom",
+ path,
+ message: `Duplicate usage type "${name}"`,
+ });
+ }
+ seenUsageTypes.add(name);
+ });
+
+ const seenTierNames = new Set<string>();
+ pricingTiers.forEach((tier, tierIndex) => {
+ // Compared trimmed, like usage types: whitespace must not sneak a second
+ // tier past this check and render as an identical label.
+ const tierName = tier.name.trim();
+ const tierNamePath = ["pricingTiers", tierIndex, "name"];
+
+ if (!tierName) {
+ ctx.addIssue({
+ code: "custom",
+ path: tierNamePath,
+ message: "Tier name is required",
+ });
+ } else if (seenTierNames.has(tierName)) {
+ ctx.addIssue({
+ code: "custom",
+ path: tierNamePath,
+ message: "Tier names must be unique",
+ });
+ }
+ seenTierNames.add(tierName);
+
+ if (!tier.isDefault && tier.conditions.length === 0) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["pricingTiers", tierIndex, "conditions"],
+ message: "Non-default tiers need at least one condition",
+ });
+ }
+
+ usageTypes.forEach((row) => {
+ if (parsePriceInput(tier.prices[row.key]) === null) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["pricingTiers", tierIndex, "prices", row.key],
+ message: "Enter a price of 0 or more",
+ });
}
- },
- {
- message: "Tokenizer config needs to be valid JSON",
- },
- )
- .transform((value) => (value === "{}" ? undefined : value))
- .nullish(),
- pricingTiers: z.array(FormPricingTierSchema),
-});
+ });
+ });
+ });
// Use input type for form (allows optional/default fields from Zod schemas)
export type FormUpsertModel = z.input<typeof FormUpsertModelSchema>;
diff --git a/web/src/features/traces/components/BreakdownTooltip.tsx b/web/src/features/traces/components/BreakdownTooltip.tsx
index dcb734790e..b746ce6542 100644
--- a/web/src/features/traces/components/BreakdownTooltip.tsx
+++ b/web/src/features/traces/components/BreakdownTooltip.tsx
@@ -6,7 +6,7 @@ import {
} from "@/src/components/ui/tooltip";
import { useState } from "react";
import Decimal from "decimal.js";
-import { getMaxDecimals } from "@/src/features/models/utils";
+import { getMaxDecimals } from "@/src/features/models/fns/getMaxDecimals";
import { type Details } from "@/src/features/traces/fns/calculateAggregatedUsage";
interface BreakdownTooltipProps {
diff --git a/web/src/features/traces/components/ObservationDetailView/components/ModelBadge.tsx b/web/src/features/traces/components/ObservationDetailView/components/ModelBadge.tsx
index 639300013e..23cef2f890 100644
--- a/web/src/features/traces/components/ObservationDetailView/components/ModelBadge.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/components/ModelBadge.tsx
@@ -6,7 +6,7 @@
import { Badge } from "@/src/components/ui/badge";
import { ExternalLinkIcon, PlusCircle } from "lucide-react";
import Link from "next/link";
-import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog/UpsertModelFormDialog";
export function ModelBadge({
model,
diff --git a/web/src/pages/project/[projectId]/settings/models/[modelId].tsx b/web/src/pages/project/[projectId]/settings/models/[modelId].tsx
index e2e5090a33..d4a5b1925b 100644
--- a/web/src/pages/project/[projectId]/settings/models/[modelId].tsx
+++ b/web/src/pages/project/[projectId]/settings/models/[modelId].tsx
@@ -14,7 +14,7 @@ import { TestModelMatchButton } from "@/src/features/models/components/test-matc
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import Link from "next/link";
import { Button } from "@/src/components/ui/button";
-import { getMaxDecimals } from "@/src/features/models/utils";
+import { getMaxDecimals } from "@/src/features/models/fns/getMaxDecimals";
import Decimal from "decimal.js";
import { PriceUnitSelector } from "@/src/features/models/components/PriceUnitSelector";
import { useMemo, useState } from "react";