feat(usage): fold preview model IDs into the model they belong to (#15333)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-10-03 14:55:47 -07:00
1 parent a21702d0e5
commit b05adb70b0
14 files changed
+472 -161

No files matched your search

@@ -233,6 +233,7 @@ export const make = Effect.gen(function* () {
environmentThemes: true,
usageLimitSources: true,
usagePriceOverrides: true,
usageModelAliases: true,
threadPinning: true,
threadPinReorder: true,
threadActiveReorder: true,
+8 -10
View File
@@ -53,7 +53,7 @@ import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEn
import { readOpenCodeUsage } from "./opencodeUsageReader.ts";
import { readAntigravityUsage } from "./antigravityUsageReader.ts";
import { readCursorAccountUsage } from "./cursorUsageReader.ts";
import { UsageAggregator } from "./usageAggregation.ts";
import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
import {
listTranscriptFiles,
@@ -821,6 +821,7 @@ export const make = Effect.gen(function* () {
...hourlyWindow,
rates,
priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
modelAliases: resolveModelAliases(settings.usageModelAliases),
});
const sources: UsageSource[] = [];
@@ -925,17 +926,13 @@ export const make = Effect.gen(function* () {
});
/**
* In-flight scans by window and custom prices, so concurrent identical requests (the usage
* In-flight scans by window and usage settings, so concurrent identical requests (the usage
* page open on two clients at once) share one scan instead of racing over
* the same corpus twice.
*/
const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
const scanKey = (
input: UsageSummaryInput,
priceOverrides: ServerSettingsValue["usagePriceOverrides"],
cursorKeychainUsageEnabled: boolean,
): string =>
const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
JSON.stringify([
input.timeZone,
input.sinceDay,
@@ -943,13 +940,14 @@ export const make = Effect.gen(function* () {
input.resolution ?? "day",
input.sinceTime ?? null,
input.untilTime ?? null,
priceOverrides,
cursorKeychainUsageEnabled,
settings.usagePriceOverrides,
settings.usageModelAliases,
settings.cursorKeychainUsageEnabled,
]);
const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
const settings = yield* readSettings;
const key = scanKey(input, settings.usagePriceOverrides, settings.cursorKeychainUsageEnabled);
const key = scanKey(input, settings);
const deferred = yield* Effect.uninterruptible(
Effect.gen(function* () {
const existing = inflightScans.get(key);
+40 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "@effect/vitest";
import { UsageAggregator } from "./usageAggregation.ts";
import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
import type { RateTable } from "./usagePricing.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
@@ -253,6 +253,25 @@ describe("UsageAggregator", () => {
expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false);
});
it("folds a mapped model into its target and prices it there", () => {
const aggregator = new UsageAggregator({
timeZone: "UTC",
sinceDay: "2026-08-01",
untilDay: "2026-08-31",
rates,
modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }),
});
aggregator.add(record());
aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" }));
const result = aggregator.finish();
expect(result.buckets).toHaveLength(1);
expect(result.buckets[0]?.model).toBe("claude-fable-5");
expect(result.buckets[0]?.records).toBe(2);
expect(result.buckets[0]?.costUsd).toBeCloseTo(0.00925, 9);
expect(result.buckets[0]?.unpricedRecords).toBe(0);
});
it("separates providers and models into their own buckets", () => {
const result = aggregate([
record(),
@@ -263,3 +282,23 @@ describe("UsageAggregator", () => {
expect(result.buckets).toHaveLength(3);
});
});
describe("resolveModelAliases", () => {
it("follows chains to the final model and drops chains that enter a loop", () => {
expect(
resolveModelAliases({
"preview[1m]": "preview",
preview: "example-model",
loop: "back",
back: "loop",
intoLoop: "loop",
self: "self",
}),
).toEqual(
new Map([
["preview[1m]", "example-model"],
["preview", "example-model"],
]),
);
});
});
+34 -1
View File
@@ -89,11 +89,35 @@ export interface AggregateOptions {
readonly untilDay: string;
readonly rates: RateTable;
readonly priceOverrides?: RateTable;
/** From {@link resolveModelAliases}. Mapped records bucket and price as their target. */
readonly modelAliases?: ReadonlyMap<string, string>;
readonly resolution?: UsageResolution;
readonly sinceTimeMs?: number;
readonly untilTimeMs?: number;
}
/**
* Resolves user model mappings to their final target, so `a -> b` and
* `b -> c` both land on `c`. A model whose chain enters a loop is left
* unmapped.
*/
export function resolveModelAliases(
aliases: Readonly<Record<string, string>>,
): ReadonlyMap<string, string> {
const resolved = new Map<string, string>();
for (const model of Object.keys(aliases)) {
const seen = new Set([model]);
let target = aliases[model]!;
while (Object.hasOwn(aliases, target) && !seen.has(target)) {
seen.add(target);
target = aliases[target]!;
}
// Stopping on a mapped model means the chain entered a loop.
if (!Object.hasOwn(aliases, target)) resolved.set(model, target);
}
return resolved;
}
export interface AggregateResult {
readonly buckets: readonly UsageBucket[];
/** Records dropped because an earlier record carried the same dedupe key. */
@@ -147,7 +171,8 @@ export class UsageAggregator {
* can derive per-window facts (distinct sessions, for one) from the records
* that landed rather than everything the mtime prefilter happened to admit.
*/
add(record: UsageRecord, sourcePath?: string): boolean {
add(input: UsageRecord, sourcePath?: string): boolean {
const record = this.#mapModel(input);
if (record.dedupeKey !== null) {
if (this.#seen.has(record.dedupeKey)) {
this.#duplicatesDropped += 1;
@@ -217,6 +242,14 @@ export class UsageAggregator {
return true;
}
/** The target's own rate applies, so a provider-specific `rateModel` is dropped. */
#mapModel(record: UsageRecord): UsageRecord {
const model = this.#options.modelAliases?.get(record.model);
if (model === undefined) return record;
const { rateModel: _rateModel, ...rest } = record;
return { ...rest, model };
}
/**
* Records arrive file by file in time order, so most land in the bucket the
* previous record used. Checking that first skips building and hashing a
@@ -34,6 +34,7 @@ import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
import { USAGE_PRICE_FIELDS } from "./usagePriceForm";
import {
isEmptyUsagePriceDraft,
usageAliasCell,
usagePriceCell,
usagePriceTableChanges,
usagePriceTableErrors,
@@ -63,6 +64,10 @@ const priceTargetsAtom = Atom.make((get): readonly UsagePriceTarget[] =>
environmentId,
label: environment.entry.target.label,
prices: settings?.usagePriceOverrides ?? null,
aliases:
environment.serverConfig?.environment.capabilities.usageModelAliases === true
? (settings?.usageModelAliases ?? null)
: null,
unavailable:
environment.connection.phase !== "connected"
? "Offline"
@@ -91,7 +96,10 @@ type SaveAttempt = {
>;
};
/** Edits custom model prices. `initialModel` opens with a new row for that model. */
/**
* Edits custom model prices and mappings. A mapped model's usage counts as its
* target model. `initialModel` opens with a new row for that model.
*/
export function UsagePriceOverrides({
usage,
initialSelectedEnvironmentIds,
@@ -108,12 +116,13 @@ export function UsagePriceOverrides({
const selected = environments.filter(
(environment) => selectedIds === null || selectedIds.has(environment.environmentId),
);
// A model that already has a custom price somewhere is edited in its existing row.
// A model that already has a custom price or mapping is edited in its existing row.
const [drafts, setDrafts] = useState<readonly UsagePriceDraft[]>(() =>
initialModel === undefined ||
selected.some(
(environment) =>
environment.prices !== null && Object.hasOwn(environment.prices, initialModel),
Object.hasOwn(environment.prices ?? {}, initialModel) ||
Object.hasOwn(environment.aliases ?? {}, initialModel),
)
? []
: [{ id: "new:initial", model: initialModel, isNew: true, values: {} }],
@@ -124,7 +133,12 @@ export function UsagePriceOverrides({
const nextRowId = useRef(0);
const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
const customModels = [
...new Set(selected.flatMap((environment) => Object.keys(environment.prices ?? {}))),
...new Set(
selected.flatMap((environment) => [
...Object.keys(environment.prices ?? {}),
...Object.keys(environment.aliases ?? {}),
]),
),
].sort();
const models = [
...new Set([
@@ -191,19 +205,31 @@ export function UsagePriceOverrides({
);
setAttempt(null);
};
// An existing row edited back to its saved values has nothing left to save.
const matchesSaved = (
row: UsagePriceDraft,
cell: { value: string; placeholder: string },
value: string,
) =>
!row.isNew &&
cell.placeholder !== "Mixed" &&
cell.placeholder !== "Unavailable" &&
value === cell.value;
const updateOrDropDraft = (draft: UsagePriceDraft) => {
if (!draft.isNew && Object.keys(draft.values).length === 0 && draft.alias === undefined)
setDrafts((previous) => previous.filter((entry) => entry.id !== draft.id));
else updateDraft(draft);
};
const editCell = (row: UsagePriceDraft, field: UsagePriceField, value: string) => {
const values = { ...row.values, [field]: value };
const original = usagePriceCell(selected, row.model, field);
if (
!row.isNew &&
original.placeholder !== "Mixed" &&
original.placeholder !== "Unavailable" &&
value === original.value
)
delete values[field];
if (!row.isNew && Object.keys(values).length === 0)
setDrafts((previous) => previous.filter((entry) => entry.id !== row.id));
else updateDraft({ ...row, values });
if (matchesSaved(row, original, value)) delete values[field];
updateOrDropDraft({ ...row, values });
};
const editAlias = (row: UsagePriceDraft, value: string) => {
const { alias: _alias, ...rest } = row;
const original = usageAliasCell(selected, row.model);
updateOrDropDraft(matchesSaved(row, original, value) ? rest : { ...rest, alias: value });
};
const save = async (retry = false) => {
if (pending) return;
@@ -214,7 +240,7 @@ export function UsagePriceOverrides({
(destination) =>
environments.find(
(environment) => environment.environmentId === destination.environmentId,
) ?? { ...destination, prices: null, unavailable: "Environment removed" },
) ?? { ...destination, prices: null, aliases: null, unavailable: "Environment removed" },
);
const changes = new Map(
targets.map((target) => [target.environmentId, usagePriceTableChanges(target, edits)]),
@@ -257,11 +283,11 @@ export function UsagePriceOverrides({
if (!pending) onOpenChange(open);
}}
>
<DialogPopup className="max-w-3xl">
<DialogPopup className="max-w-4xl">
<DialogHeader>
<DialogTitle>Custom model prices</DialogTitle>
<DialogDescription>
Prices apply to all past and future usage on the environments you select.
Prices and mappings apply to all past and future usage on the environments you select.
</DialogDescription>
</DialogHeader>
<DialogPanel>
@@ -326,9 +352,10 @@ export function UsagePriceOverrides({
) : (
<>
<div className="min-w-0 overflow-hidden rounded-lg border border-border">
<Table className="min-w-160 table-fixed" aria-label="Custom model prices">
<Table className="min-w-180 table-fixed" aria-label="Custom model prices">
<colgroup>
<col className="w-[34%]" />
<col className="w-[22%]" />
<col className="w-[18%]" />
{USAGE_PRICE_FIELDS.map((field) => (
<col key={field.key} />
))}
@@ -337,6 +364,7 @@ export function UsagePriceOverrides({
<TableHeader>
<TableRow>
<TableHead>Model ID</TableHead>
<TableHead>Map to</TableHead>
{USAGE_PRICE_FIELDS.map((field) => (
<TableHead key={field.key}>{field.label}</TableHead>
))}
@@ -360,132 +388,157 @@ export function UsagePriceOverrides({
<TableBody>
{rows.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center whitespace-normal">
<TableCell colSpan={7} className="text-center whitespace-normal">
<p className="py-6 text-muted-foreground">
{selected.some((environment) => environment.prices === null)
? "Some environment prices are unavailable."
: "No custom prices. Add a row to override automatic pricing."}
: "No custom prices or mappings. Add a row to set one."}
</p>
</TableCell>
</TableRow>
) : (
rows.map((row) => (
<TableRow key={row.id} data-row-id={row.id}>
<TableCell className="whitespace-normal">
{row.isNew ? (
<Input
size="compact"
value={row.model}
ref={(node) => {
if (node && focusRowRef.current === row.id) {
node.focus();
focusRowRef.current = null;
rows.map((row) => {
const aliasCell = usageAliasCell(selected, row.model);
const alias = (row.alias ?? aliasCell.value).trim();
return (
<TableRow key={row.id} data-row-id={row.id}>
<TableCell className="whitespace-normal">
{row.isNew ? (
<Input
size="compact"
value={row.model}
ref={(node) => {
if (node && focusRowRef.current === row.id) {
node.focus();
focusRowRef.current = null;
}
}}
aria-label="New model ID"
aria-invalid={
(row.model.trim() !== "" && errors.has(row.id)) || undefined
}
}}
aria-label="New model ID"
aria-invalid={
(row.model.trim() !== "" && errors.has(row.id)) || undefined
}
list="usage-price-models"
placeholder="Model ID"
autoComplete="off"
spellCheck={false}
disabled={locked}
onChange={(event) =>
updateDraft({ ...row, model: event.target.value })
}
/>
) : (
<span
className={cn(
"block break-all",
row.removed && "text-muted-foreground line-through",
)}
>
{row.model}
</span>
)}
{errors.has(row.id) &&
(row.model.trim() !== "" ||
Object.values(row.values).some((value) => value !== "")) ? (
<p role="alert" className="mt-1 text-xs text-destructive">
{errors.get(row.id)}
</p>
) : null}
</TableCell>
{row.removed ? (
<TableCell colSpan={4}>
<span className="text-muted-foreground">
Automatic pricing after saving
</span>
list="usage-price-models"
placeholder="Model ID"
autoComplete="off"
spellCheck={false}
disabled={locked}
onChange={(event) =>
updateDraft({ ...row, model: event.target.value })
}
/>
) : (
<span
className={cn(
"block break-all",
row.removed && "text-muted-foreground line-through",
)}
>
{row.model}
</span>
)}
{errors.has(row.id) &&
(row.model.trim() !== "" ||
Object.values(row.values).some((value) => value !== "")) ? (
<p role="alert" className="mt-1 text-xs text-destructive">
{errors.get(row.id)}
</p>
) : null}
</TableCell>
) : (
USAGE_PRICE_FIELDS.map((field) => {
const cell = usagePriceCell(selected, row.model, field.key);
return (
<TableCell key={field.key}>
<Input
size="compact"
inputMode="decimal"
aria-label={`${field.label} price for ${row.model || "new model"}`}
value={row.values[field.key] ?? (row.isNew ? "" : cell.value)}
placeholder={
row.isNew
? field.optional
? "Input rate"
: "0.00"
: cell.placeholder
}
autoComplete="off"
disabled={locked}
font="mono"
onChange={(event) =>
editCell(row, field.key, event.target.value)
}
/>
</TableCell>
);
})
)}
<TableCell>
<Tooltip>
<TooltipTrigger
render={<Button size="icon-xs" variant="ghost" />}
disabled={locked}
aria-label={
row.removed
? `Undo reset for ${row.model}`
: row.isNew
? "Remove new model"
: `Reset price for ${row.model} to automatic`
}
onClick={() => {
if (row.isNew)
setDrafts((previous) =>
previous.filter((entry) => entry.id !== row.id),
);
else if (row.removed) {
if (Object.keys(row.values).length === 0)
{row.removed ? (
<TableCell colSpan={5}>
<span className="text-muted-foreground">
Automatic pricing after saving
</span>
</TableCell>
) : (
<TableCell>
<Input
size="compact"
value={row.alias ?? aliasCell.value}
aria-label={`Map ${row.model || "new model"} to model`}
list="usage-alias-models"
placeholder={row.isNew ? "Optional" : aliasCell.placeholder}
autoComplete="off"
spellCheck={false}
disabled={locked}
onChange={(event) => editAlias(row, event.target.value)}
/>
</TableCell>
)}
{row.removed ? null : alias !== "" ? (
<TableCell colSpan={4} className="whitespace-normal">
<span className="break-all text-muted-foreground">
Counted as {alias}
</span>
</TableCell>
) : (
USAGE_PRICE_FIELDS.map((field) => {
const cell = usagePriceCell(selected, row.model, field.key);
return (
<TableCell key={field.key}>
<Input
size="compact"
inputMode="decimal"
aria-label={`${field.label} price for ${row.model || "new model"}`}
value={row.values[field.key] ?? (row.isNew ? "" : cell.value)}
placeholder={
row.isNew
? field.optional
? "Input rate"
: "0.00"
: cell.placeholder
}
autoComplete="off"
disabled={locked}
font="mono"
onChange={(event) =>
editCell(row, field.key, event.target.value)
}
/>
</TableCell>
);
})
)}
<TableCell>
<Tooltip>
<TooltipTrigger
render={<Button size="icon-xs" variant="ghost" />}
disabled={locked}
aria-label={
row.removed
? `Undo reset for ${row.model}`
: row.isNew
? "Remove new model"
: `Reset price for ${row.model} to automatic`
}
onClick={() => {
if (row.isNew)
setDrafts((previous) =>
previous.filter((entry) => entry.id !== row.id),
);
else updateDraft({ ...row, removed: false });
} else updateDraft({ ...row, removed: true });
}}
>
{row.isNew ? <XIcon aria-hidden /> : <RotateCcwIcon aria-hidden />}
</TooltipTrigger>
<TooltipPopup>
{row.removed
? "Undo reset"
: row.isNew
? "Remove row"
: "Reset to automatic"}
</TooltipPopup>
</Tooltip>
</TableCell>
</TableRow>
))
else if (row.removed)
updateOrDropDraft({ ...row, removed: false });
else updateDraft({ ...row, removed: true });
}}
>
{row.isNew ? (
<XIcon aria-hidden />
) : (
<RotateCcwIcon aria-hidden />
)}
</TooltipTrigger>
<TooltipPopup>
{row.removed
? "Undo reset"
: row.isNew
? "Remove row"
: "Reset to automatic"}
</TooltipPopup>
</Tooltip>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
@@ -497,8 +550,20 @@ export function UsagePriceOverrides({
<option key={model} value={model} />
))}
</datalist>
<datalist id="usage-alias-models">
{models
.filter((model) =>
selected.every(
(environment) => !Object.hasOwn(environment.aliases ?? {}, model),
),
)
.map((model) => (
<option key={model} value={model} />
))}
</datalist>
<p className="text-xs text-muted-foreground">
Blank cache rates use the input price. Enter 0 for free tokens.
Blank cache rates use the input price. Enter 0 for free tokens. A mapped model’s
usage counts as the model it maps to.
{selected.length > 1
? " Mixed cells keep each environment’s rate until you edit them."
: ""}
@@ -1,6 +1,7 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
usageAliasCell,
usagePriceCell,
usagePriceTableChanges,
usagePriceTableErrors,
@@ -9,10 +10,15 @@ import {
import type { UsagePriceTarget } from "./usagePriceTargets";
const price = { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 };
const target = (name: string, prices: UsagePriceTarget["prices"]): UsagePriceTarget => ({
const target = (
name: string,
prices: UsagePriceTarget["prices"],
aliases: UsagePriceTarget["aliases"] = {},
): UsagePriceTarget => ({
environmentId: EnvironmentId.make(name),
label: name,
prices,
aliases,
unavailable: null,
});
const draft = (values: UsagePriceDraft["values"]): UsagePriceDraft => ({
@@ -167,4 +173,55 @@ describe("price table edits", () => {
usagePriceTableChanges(environment, [draft({ outputCostPerMillionTokens: "" })]).errors.size,
).toBe(1);
});
it("mapping a model drops its own price and resetting removes the mapping", () => {
const priced = target("a", { example: price });
expect(usagePriceTableChanges(priced, [{ ...draft({}), alias: " example-model " }])).toEqual({
changes: [
{ model: "example", alias: "example-model" },
{ model: "example", price: null },
],
errors: new Map(),
});
const mapped = target("b", {}, { example: "example-model" });
expect(usagePriceTableChanges(mapped, [{ ...draft({}), removed: true }]).changes).toEqual([
{ model: "example", alias: null },
]);
expect(
usagePriceTableChanges(mapped, [{ ...draft({}), alias: "example" }]).errors.get(
"model:example",
),
).toBe("Map to a different model.");
});
it("clearing a mapping returns to automatic pricing unless prices are entered", () => {
const mapped = target("a", {}, { example: "example-model" });
expect(usagePriceTableChanges(mapped, [{ ...draft({}), alias: "" }]).changes).toEqual([
{ model: "example", alias: null },
]);
expect(
usagePriceTableChanges(mapped, [
{
...draft({ inputCostPerMillionTokens: "2", outputCostPerMillionTokens: "8" }),
alias: "",
},
]).changes,
).toEqual([
{ model: "example", alias: null },
{ model: "example", price },
]);
});
it("keeps each environment's mapping when the column is untouched", () => {
const edits = [draft({ inputCostPerMillionTokens: "3" })];
expect(
usagePriceTableChanges(target("a", {}, { example: "example-model" }), edits).changes,
).toEqual([]);
expect(
usageAliasCell(
[target("a", {}, { example: "example-model" }), target("b", { example: price })],
"example",
),
).toEqual({ value: "", placeholder: "Mixed" });
});
});
@@ -13,6 +13,8 @@ export interface UsagePriceDraft {
readonly model: string;
readonly isNew: boolean;
readonly values: Partial<Pick<UsagePriceForm, UsagePriceField>>;
/** Edited "Map to" model. Absent keeps each environment's mapping; blank removes it. */
readonly alias?: string;
readonly removed?: boolean;
}
@@ -20,6 +22,7 @@ export function isEmptyUsagePriceDraft(draft: UsagePriceDraft) {
return (
draft.isNew &&
draft.model.trim() === "" &&
(draft.alias ?? "").trim() === "" &&
Object.values(draft.values).every((value) => value.trim() === "")
);
}
@@ -28,6 +31,19 @@ function modelPrice(target: UsagePriceTarget, model: string) {
return target.prices && Object.hasOwn(target.prices, model) ? target.prices[model] : undefined;
}
function modelAlias(target: UsagePriceTarget, model: string) {
return target.aliases && Object.hasOwn(target.aliases, model) ? target.aliases[model] : undefined;
}
/** The "Map to" cell across the selected environments, read like a price cell. */
export function usageAliasCell(targets: readonly UsagePriceTarget[], model: string) {
if (targets.some((target) => target.aliases === null))
return { value: "", placeholder: "Unavailable" };
const values = targets.map((target) => modelAlias(target, model) ?? "");
if (values.some((value) => value !== values[0])) return { value: "", placeholder: "Mixed" };
return { value: values[0] ?? "", placeholder: "None" };
}
export function usagePriceCell(
targets: readonly UsagePriceTarget[],
model: string,
@@ -56,10 +72,32 @@ export function usagePriceTableChanges(
for (const draft of drafts) {
if (isEmptyUsagePriceDraft(draft)) continue;
const model = draft.model.trim();
const currentAlias = modelAlias(target, model);
if (draft.removed) {
if (modelPrice(target, model)) changes.push({ model, price: null });
if (currentAlias !== undefined) changes.push({ model, alias: null });
continue;
}
// A mapped model is priced as its target, so mapping it drops its own price.
const alias = (draft.alias ?? currentAlias ?? "").trim();
if (alias !== "") {
if (model === "") errors.set(draft.id, "Enter a model ID.");
else if (alias === model) errors.set(draft.id, "Map to a different model.");
else {
if (alias !== currentAlias) changes.push({ model, alias });
if (modelPrice(target, model)) changes.push({ model, price: null });
}
continue;
}
if (currentAlias !== undefined) {
changes.push({ model, alias: null });
// Clearing a mapping without entering prices returns to automatic pricing.
if (
!modelPrice(target, model) &&
Object.values(draft.values).every((value) => value.trim() === "")
)
continue;
}
const original = usagePriceForm(model, modelPrice(target, model));
const form = { ...original, ...draft.values };
const parsed = parseUsagePriceForm(form);
@@ -12,6 +12,7 @@ const target = (id: string, overrides: Partial<UsagePriceTarget> = {}): UsagePri
environmentId: EnvironmentId.make(id),
label: id,
prices: { example: price },
aliases: {},
unavailable: null,
...overrides,
});
@@ -140,4 +141,35 @@ describe("model price writes", () => {
error: "Update server to edit prices",
});
});
it("sends mappings beside prices and fails servers that cannot store them", async () => {
const write = vi.fn(async () => ({ _tag: "Success" as const }));
const onResult = vi.fn();
const changes = [
{ model: "example", alias: "example-model" },
{ model: "example", price: null },
];
await writeUsagePrices({
targets: [target("current"), target("old", { aliases: null })],
changes: new Map([
[EnvironmentId.make("current"), changes],
[EnvironmentId.make("old"), changes],
]),
write,
onResult,
});
expect(write).toHaveBeenCalledExactlyOnceWith({
environmentId: "current",
input: {
patch: {
usagePriceOverrides: { example: null },
usageModelAliases: { example: "example-model" },
},
},
});
expect(onResult).toHaveBeenCalledWith("old", {
status: "failed",
error: "Update server to map models",
});
});
});
@@ -8,19 +8,24 @@ export interface UsagePriceTarget {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly prices: Readonly<Record<string, UsageModelPriceOverride>> | null;
/** Model mappings. `null` when they are not loaded or the server cannot store them. */
readonly aliases: Readonly<Record<string, string>> | null;
readonly unavailable: string | null;
}
export interface UsagePriceChange {
readonly model: string;
readonly price: UsageModelPriceOverride | null;
}
/** `null` removes the model's custom price or mapping. */
export type UsagePriceChange =
| { readonly model: string; readonly price: UsageModelPriceOverride | null }
| { readonly model: string; readonly alias: string | null };
export type UsagePriceWriteResult =
| { readonly status: "saved" }
| { readonly status: "failed"; readonly error: string };
/** Each destination settles independently; retry callers pass only the failed destinations. */
/**
* Each destination settles independently; retry callers pass only the failed destinations.
* Prices and mappings for one destination go out in a single patch.
*/
export async function writeUsagePrices(input: {
readonly targets: readonly UsagePriceTarget[];
readonly changes: ReadonlyMap<EnvironmentId, readonly UsagePriceChange[]>;
@@ -33,11 +38,19 @@ export async function writeUsagePrices(input: {
await Promise.all(
input.targets.map(async (target) => {
let result: UsagePriceWriteResult;
const changes = input.changes.get(target.environmentId) ?? [];
const prices = changes.flatMap((change) =>
"price" in change ? [[change.model, change.price] as const] : [],
);
const aliases = changes.flatMap((change) =>
"alias" in change ? [[change.model, change.alias] as const] : [],
);
if (target.unavailable !== null) {
result = { status: "failed", error: target.unavailable };
} else if (aliases.length > 0 && target.aliases === null) {
result = { status: "failed", error: "Update server to map models" };
} else {
try {
const changes = input.changes.get(target.environmentId) ?? [];
const saved =
changes.length === 0
? { _tag: "Success" as const }
@@ -45,9 +58,12 @@ export async function writeUsagePrices(input: {
environmentId: target.environmentId,
input: {
patch: {
usagePriceOverrides: Object.fromEntries(
changes.map((change) => [change.model, change.price]),
),
...(prices.length > 0
? { usagePriceOverrides: Object.fromEntries(prices) }
: {}),
...(aliases.length > 0
? { usageModelAliases: Object.fromEntries(aliases) }
: {}),
},
},
});
+5
View File
@@ -61,6 +61,11 @@ edited rows. Untouched cells keep each environment's rate. Select one environmen
prices. **Reset to automatic** marks a model's override for removal when you save; you can undo
it before saving.
To count one model as another, such as a preview model under its released name, enter the target
model ID under **Map to**. The mapped model no longer appears on **Usage**: its tokens and cost
move to the target model and use the target's price. Clear **Map to** or reset the row to show
the model on its own again.
Each destination reports whether the change saved. Offline or unavailable environments are
marked **Not saved**. Reconnect them and choose **Retry failed saves** to finish the same change
without writing again to environments that already saved. Changes are not queued after you close
+10 -5
View File
@@ -936,12 +936,17 @@ export function createServerEnvironmentAtoms<R, E>(
}).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),
);
const usageScanSettingsAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make((get) =>
JSON.stringify([
Atom.make((get) => {
const settings = get(settingsValueAtom(environmentId));
const aliases = settings?.usageModelAliases ?? {};
return JSON.stringify([
get(usagePricesAtom(environmentId)),
get(settingsValueAtom(environmentId))?.cursorKeychainUsageEnabled ?? false,
]),
).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
Object.keys(aliases)
.sort()
.map((model) => [model, aliases[model]]),
settings?.cursorKeychainUsageEnabled ?? false,
]);
}).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
);
const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
+2
View File
@@ -136,6 +136,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
usageLimitSources: Schema.optionalKey(Schema.Boolean),
/** Server persists custom model rates and applies them to usage summaries. */
usagePriceOverrides: Schema.optionalKey(Schema.Boolean),
/** Server persists model mappings and folds mapped usage into the target model. */
usageModelAliases: Schema.optionalKey(Schema.Boolean),
/** Server understands thread.pin / thread.unpin commands. Same
version-skew contract as threadSettlement. */
threadPinning: Schema.optionalKey(Schema.Boolean),
+11
View File
@@ -1404,6 +1404,13 @@ export const ServerSettings = Schema.Struct({
usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe(
Schema.withDecodingDefault(Effect.succeed({})),
),
/**
* Exact model ID to the model its usage counts as, such as a preview slug to
* its released name. The mapped model is priced and reported as its target.
*/
usageModelAliases: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString).pipe(
Schema.withDecodingDefault(Effect.succeed({})),
),
});
export type ServerSettings = typeof ServerSettings.Type;
@@ -1700,6 +1707,10 @@ export const ServerSettingsPatch = Schema.Struct({
usagePriceOverrides: Schema.optionalKey(
Schema.Record(TrimmedNonEmptyString, Schema.NullOr(UsageModelPriceOverride)),
),
/** Each entry replaces one model's mapping; `null` removes it. */
usageModelAliases: Schema.optionalKey(
Schema.Record(TrimmedNonEmptyString, Schema.NullOr(TrimmedNonEmptyString)),
),
});
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
+9
View File
@@ -280,6 +280,7 @@ export function applyServerSettingsPatch(
// Merged per entry below; its `null` removals must not reach deepMerge.
usageLimitSources: usageLimitSourcesPatch,
usagePriceOverrides: usagePriceOverridesPatch,
usageModelAliases: usageModelAliasesPatch,
// Entry replacement: deepMerge would keep keys the client meant to clear.
projectSettingsOverrides: projectSettingsOverridesPatch,
// Already translated into `projectSettingsOverrides` above; the legacy
@@ -394,6 +395,14 @@ export function applyServerSettingsPatch(
),
}
: {}),
...(usageModelAliasesPatch !== undefined
? {
usageModelAliases: mergeSettingsEntries(
current.usageModelAliases,
usageModelAliasesPatch,
),
}
: {}),
...(patch.sourceControlWriterModelSelection !== undefined
? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
: {}),