Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { AuthSettingsWriteScope, type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
3import { ChevronDownIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react";
4import { AsyncResult, Atom } from "effect/reactivity";
5import { useRef, useState } from "react";
6
7import { cn } from "../../lib/utils";
8import { environmentPresentations } from "../../state/presentation";
9import { serverEnvironment } from "../../state/server";
10import { environmentSession, readEnvironmentScope } from "../../state/session";
11import { useAtomCommand } from "../../state/use-atom-command";
12import type { EnvironmentUsageStatus } from "../../state/usage";
13import { Button } from "../ui/button";
14import {
15 Dialog,
16 DialogDescription,
17 DialogFooter,
18 DialogHeader,
19 DialogPanel,
20 DialogPopup,
21 DialogTitle,
22} from "../ui/dialog";
23import { Input } from "../ui/input";
24import { Label } from "../ui/label";
25import { Menu, MenuCheckboxItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu";
26import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
27import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
28import { isUsagePriceEdit, USAGE_PRICE_FIELDS } from "./usagePriceForm";
29import {
30 isEmptyUsagePriceDraft,
31 usageAliasCell,
32 usagePriceCell,
33 usagePriceTableChanges,
34 usagePriceTableErrors,
35 type UsagePriceDraft,
36 type UsagePriceField,
37} from "./usagePriceTable";
38import {
39 writeUsagePrices,
40 type UsagePriceTarget,
41 type UsagePriceWriteResult,
42} from "./usagePriceTargets";
43
44const priceTargetsAtom = Atom.make((get): readonly UsagePriceTarget[] =>
45 [...get(environmentPresentations.presentationsAtom)].map(([environmentId, environment]) => {
46 const settings = get(serverEnvironment.settingsValueAtom(environmentId));
47 const session = get(environmentSession.sessionStateAtom(environmentId));
48 const sessionData = AsyncResult.getOrElse(session, () => null);
49 const access =
50 session._tag === "Failure"
51 ? "denied"
52 : sessionData === null
53 ? session.waiting
54 ? "pending"
55 : "denied"
56 : sessionGrantsScope(sessionData, AuthSettingsWriteScope)
57 ? "granted"
58 : "denied";
59 return {
60 environmentId,
61 label: environment.entry.target.label,
62 prices: settings?.usagePriceOverrides ?? null,
63 aliases:
64 environment.serverConfig?.environment.capabilities.usageModelAliases === true
65 ? (settings?.usageModelAliases ?? null)
66 : null,
67 unavailable:
68 environment.connection.phase !== "connected"
69 ? "Offline"
70 : settings === null
71 ? "Prices not loaded"
72 : access === "pending"
73 ? "Checking permissions…"
74 : access === "denied"
75 ? "Read-only access"
76 : null,
77 };
78 }),
79);
80
81type SaveAttempt = {
82 readonly drafts: readonly UsagePriceDraft[];
83 readonly destinations: readonly {
84 readonly environmentId: EnvironmentId;
85 readonly label: string;
86 }[];
87 readonly results: ReadonlyMap<
88 EnvironmentId,
89 UsagePriceWriteResult | { readonly status: "saving" }
90 >;
91};
92
93export function UsagePriceOverrides({
94 usage,
95 initialSelectedEnvironmentIds,
96 initialModel,
97 onOpenChange,
98}: {
99 readonly usage: readonly EnvironmentUsageStatus[];
100 readonly initialSelectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
101 readonly initialModel?: string | undefined;
102 readonly onOpenChange: (open: boolean) => void;
103}) {
104 const environments = useAtomValue(priceTargetsAtom);
105 const [selectedIds, setSelectedIds] = useState(initialSelectedEnvironmentIds);
106 const selected = environments.filter(
107 (environment) => selectedIds === null || selectedIds.has(environment.environmentId),
108 );
109 const [drafts, setDrafts] = useState<readonly UsagePriceDraft[]>(() =>
110 initialModel === undefined ||
111 selected.some(
112 (environment) =>
113 Object.hasOwn(environment.prices ?? {}, initialModel) ||
114 Object.hasOwn(environment.aliases ?? {}, initialModel),
115 )
116 ? []
117 : [{ id: "new:initial", model: initialModel, isNew: true, values: {} }],
118 );
119 const [pending, setPending] = useState(false);
120 const [attempt, setAttempt] = useState<SaveAttempt | null>(null);
121 const focusRowRef = useRef<string | null>(null);
122 const nextRowId = useRef(0);
123 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
124 const customModels = [
125 ...new Set(
126 selected.flatMap((environment) => [
127 ...Object.keys(environment.prices ?? {}),
128 ...Object.keys(environment.aliases ?? {}),
129 ]),
130 ),
131 ].sort();
132 const models = [
133 ...new Set([
134 ...customModels,
135 ...usage
136 .filter((environment) =>
137 selected.some((target) => target.environmentId === environment.environmentId),
138 )
139 .flatMap((environment) => environment.summary?.buckets.map((bucket) => bucket.model) ?? []),
140 ]),
141 ].sort();
142 const newModels = new Set(
143 drafts.filter((draft) => draft.isNew).map((draft) => draft.model.trim()),
144 );
145 const rows: readonly UsagePriceDraft[] = [
146 ...customModels
147 .filter((model) => attempt === null || !newModels.has(model))
148 .map(
149 (model) =>
150 drafts.find((draft) => draft.id === `model:${model}`) ?? {
151 id: `model:${model}`,
152 model,
153 isNew: false,
154 values: {},
155 },
156 ),
157 ...drafts.filter((draft) => draft.isNew),
158 ];
159 const stagedDrafts = drafts.filter((draft) => !isEmptyUsagePriceDraft(draft));
160 const errors = usagePriceTableErrors(selected, stagedDrafts);
161 for (const draft of stagedDrafts) {
162 if (!draft.isNew) continue;
163 if (draft.model.trim() === "") errors.set(draft.id, "Enter a model ID.");
164 else if (
165 attempt === null &&
166 (customModels.includes(draft.model.trim()) ||
167 drafts.some((other) => other.id !== draft.id && other.model.trim() === draft.model.trim()))
168 )
169 errors.set(draft.id, "This model already has a row. Edit its prices there.");
170 }
171 const failedDestinations =
172 attempt?.destinations.filter(
173 (destination) => attempt.results.get(destination.environmentId)?.status === "failed",
174 ) ?? [];
175 const locked = pending || failedDestinations.length > 0;
176 const hasChanges = stagedDrafts.length > 0;
177 const destinationLabel =
178 selected.length === 1 ? selected[0]!.label : `${selected.length} environments`;
179 const selectionLabel = selectedIds === null ? "All environments" : destinationLabel;
180 const discard = () => {
181 setDrafts([]);
182 setAttempt(null);
183 };
184 const selectEnvironments = (ids: ReadonlySet<EnvironmentId> | null) => {
185 setSelectedIds(ids);
186 setAttempt(null);
187 };
188 const updateDraft = (draft: UsagePriceDraft) => {
189 setDrafts((previous) =>
190 previous.some((entry) => entry.id === draft.id)
191 ? previous.map((entry) => (entry.id === draft.id ? draft : entry))
192 : [...previous, draft],
193 );
194 setAttempt(null);
195 };
196 const matchesSaved = (
197 row: UsagePriceDraft,
198 cell: { value: string; placeholder: string },
199 value: string,
200 ) =>
201 !row.isNew &&
202 cell.placeholder !== "Mixed" &&
203 cell.placeholder !== "Unavailable" &&
204 value === cell.value;
205 const updateOrDropDraft = (draft: UsagePriceDraft) => {
206 if (!draft.isNew && Object.keys(draft.values).length === 0 && draft.alias === undefined)
207 setDrafts((previous) => previous.filter((entry) => entry.id !== draft.id));
208 else updateDraft(draft);
209 };
210 const editCell = (row: UsagePriceDraft, field: UsagePriceField, value: string) => {
211 const values = { ...row.values, [field]: value };
212 const original = usagePriceCell(selected, row.model, field);
213 if (matchesSaved(row, original, value)) delete values[field];
214 updateOrDropDraft({ ...row, values });
215 };
216 const editAlias = (row: UsagePriceDraft, value: string) => {
217 const { alias: _alias, ...rest } = row;
218 const original = usageAliasCell(selected, row.model);
219 updateOrDropDraft(matchesSaved(row, original, value) ? rest : { ...rest, alias: value });
220 };
221 const save = async (retry = false) => {
222 if (pending) return;
223 const destinations = retry ? failedDestinations : selected;
224 const edits = retry && attempt ? attempt.drafts : stagedDrafts;
225 if (destinations.length === 0 || edits.length === 0) return;
226 const targets = destinations.map(
227 (destination) =>
228 environments.find(
229 (environment) => environment.environmentId === destination.environmentId,
230 ) ?? { ...destination, prices: null, aliases: null, unavailable: "Environment removed" },
231 );
232 const changes = new Map(
233 targets.map((target) => [target.environmentId, usagePriceTableChanges(target, edits)]),
234 );
235 setPending(true);
236 setAttempt((previous) => ({
237 drafts: edits,
238 destinations: retry && previous ? previous.destinations : targets,
239 results: new Map([
240 ...(retry && previous ? previous.results : []),
241 ...targets.map((target) => [target.environmentId, { status: "saving" } as const] as const),
242 ]),
243 }));
244 let failed = false;
245 await writeUsagePrices({
246 targets: targets.map((target) => ({
247 ...target,
248 unavailable:
249 target.unavailable ?? [...changes.get(target.environmentId)!.errors.values()][0] ?? null,
250 })),
251 changes: new Map([...changes].map(([id, plan]) => [id, plan.changes])),
252 write: async (input) =>
253 readEnvironmentScope(input.environmentId, AuthSettingsWriteScope)
254 ? updateSettings(input)
255 : { _tag: "Failure" },
256 onResult: (environmentId, result) => {
257 if (result.status === "failed") failed = true;
258 setAttempt((previous) =>
259 previous === null
260 ? null
261 : { ...previous, results: new Map(previous.results).set(environmentId, result) },
262 );
263 },
264 });
265 setPending(false);
266 if (!failed) setDrafts([]);
267 };
268
269 return (
270 <Dialog
271 open
272 onOpenChange={(open) => {
273 if (!pending) onOpenChange(open);
274 }}
275 >
276 <DialogPopup className="max-w-4xl">
277 <DialogHeader>
278 <DialogTitle>Custom model prices</DialogTitle>
279 <DialogDescription>
280 Prices and mappings apply to all past and future usage on the environments you select.
281 </DialogDescription>
282 </DialogHeader>
283 <DialogPanel>
284 <div className="flex flex-wrap items-center justify-between gap-2">
285 <div className="flex min-w-0 items-center gap-2">
286 <Label id="usage-prices-apply-label" className="shrink-0">
287 Apply to
288 </Label>
289 <Menu>
290 <MenuTrigger
291 render={<Button variant="outline" size="sm" className="min-w-0" />}
292 aria-labelledby="usage-prices-apply-label usage-prices-selection"
293 disabled={pending || hasChanges}
294 >
295 <span id="usage-prices-selection" className="truncate">
296 {selectionLabel}
297 </span>
298 <ChevronDownIcon className="size-3.5 shrink-0" aria-hidden />
299 </MenuTrigger>
300 <MenuPopup align="start">
301 <MenuCheckboxItem
302 checked={selectedIds === null}
303 closeOnClick={false}
304 onCheckedChange={(checked) => selectEnvironments(checked ? null : new Set())}
305 >
306 All environments
307 </MenuCheckboxItem>
308 <MenuSeparator />
309 {environments.map((environment) => (
310 <MenuCheckboxItem
311 key={environment.environmentId}
312 checked={selectedIds === null || selectedIds.has(environment.environmentId)}
313 closeOnClick={false}
314 onCheckedChange={(checked) => {
315 const next = new Set(selected.map((target) => target.environmentId));
316 if (checked) next.add(environment.environmentId);
317 else next.delete(environment.environmentId);
318 selectEnvironments(next.size === environments.length ? null : next);
319 }}
320 >
321 <span className="flex min-w-0 items-center gap-3">
322 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
323 {environment.unavailable ? (
324 <span className="text-xs text-muted-foreground">
325 {environment.unavailable}
326 </span>
327 ) : null}
328 </span>
329 </MenuCheckboxItem>
330 ))}
331 </MenuPopup>
332 </Menu>
333 </div>
334 <span className="text-xs text-muted-foreground">USD / million tokens</span>
335 </div>
336 {selected.length === 0 ? (
337 <p className="text-sm text-muted-foreground">
338 {environments.length === 0
339 ? "Connect an environment to set model prices."
340 : "Select an environment to see and change its model prices."}
341 </p>
342 ) : (
343 <>
344 <div className="min-w-0 overflow-hidden rounded-lg border border-border">
345 <Table className="min-w-180 table-fixed" aria-label="Custom model prices">
346 <colgroup>
347 <col className="w-[22%]" />
348 <col className="w-[18%]" />
349 {USAGE_PRICE_FIELDS.map((field) => (
350 <col key={field.key} />
351 ))}
352 <col className="w-10" />
353 </colgroup>
354 <TableHeader>
355 <TableRow>
356 <TableHead>Model ID</TableHead>
357 <TableHead>Map to</TableHead>
358 {USAGE_PRICE_FIELDS.map((field) => (
359 <TableHead key={field.key}>{field.label}</TableHead>
360 ))}
361 <TableHead>
362 <Button
363 size="icon-xs"
364 variant="ghost"
365 aria-label="Add model price"
366 disabled={locked}
367 onClick={() => {
368 const id = `new:${nextRowId.current++}`;
369 focusRowRef.current = id;
370 updateDraft({ id, model: "", isNew: true, values: {} });
371 }}
372 >
373 <PlusIcon aria-hidden />
374 </Button>
375 </TableHead>
376 </TableRow>
377 </TableHeader>
378 <TableBody>
379 {rows.length === 0 ? (
380 <TableRow>
381 <TableCell colSpan={7} className="text-center whitespace-normal">
382 <p className="py-6 text-muted-foreground">
383 {selected.some((environment) => environment.prices === null)
384 ? "Some environment prices are unavailable."
385 : "No custom prices or mappings. Add a row to set one."}
386 </p>
387 </TableCell>
388 </TableRow>
389 ) : (
390 rows.map((row) => {
391 const aliasCell = usageAliasCell(selected, row.model);
392 const alias = (row.alias ?? aliasCell.value).trim();
393 return (
394 <TableRow key={row.id} data-row-id={row.id}>
395 <TableCell className="whitespace-normal">
396 {row.isNew ? (
397 <Input
398 size="compact"
399 value={row.model}
400 ref={(node) => {
401 if (node && focusRowRef.current === row.id) {
402 node.focus();
403 focusRowRef.current = null;
404 }
405 }}
406 aria-label="New model ID"
407 aria-invalid={
408 (row.model.trim() !== "" && errors.has(row.id)) || undefined
409 }
410 list="usage-price-models"
411 placeholder="Model ID"
412 autoComplete="off"
413 spellCheck={false}
414 disabled={locked}
415 onChange={(event) =>
416 updateDraft({ ...row, model: event.target.value })
417 }
418 />
419 ) : (
420 <span
421 className={cn(
422 "block break-all",
423 row.removed && "text-muted-foreground line-through",
424 )}
425 >
426 {row.model}
427 </span>
428 )}
429 {errors.has(row.id) &&
430 (row.model.trim() !== "" ||
431 Object.values(row.values).some((value) => value !== "")) ? (
432 <p role="alert" className="mt-1 text-xs text-destructive">
433 {errors.get(row.id)}
434 </p>
435 ) : null}
436 </TableCell>
437 {row.removed ? (
438 <TableCell colSpan={5}>
439 <span className="text-muted-foreground">
440 Automatic pricing after saving
441 </span>
442 </TableCell>
443 ) : (
444 <TableCell>
445 <Input
446 size="compact"
447 value={row.alias ?? aliasCell.value}
448 aria-label={`Map ${row.model || "new model"} to model`}
449 list="usage-alias-models"
450 placeholder={row.isNew ? "Optional" : aliasCell.placeholder}
451 autoComplete="off"
452 spellCheck={false}
453 disabled={locked}
454 onChange={(event) => editAlias(row, event.target.value)}
455 />
456 </TableCell>
457 )}
458 {row.removed ? null : alias !== "" ? (
459 <TableCell colSpan={4} className="whitespace-normal">
460 <span className="break-all text-muted-foreground">
461 Counted as {alias}
462 </span>
463 </TableCell>
464 ) : (
465 USAGE_PRICE_FIELDS.map((field) => {
466 const cell = usagePriceCell(selected, row.model, field.key);
467 const value =
468 row.values[field.key] ?? (row.isNew ? "" : cell.value);
469 return (
470 <TableCell key={field.key}>
471 <Input
472 size="compact"
473 inputMode="decimal"
474 aria-label={`${field.label} price for ${row.model || "new model"}`}
475 value={value}
476 placeholder={
477 row.isNew
478 ? field.optional
479 ? "Input rate"
480 : "0.00"
481 : cell.placeholder
482 }
483 autoComplete="off"
484 disabled={locked}
485 font="mono"
486 onChange={(event) => {
487 if (isUsagePriceEdit(value, event.target.value))
488 editCell(row, field.key, event.target.value);
489 }}
490 />
491 </TableCell>
492 );
493 })
494 )}
495 <TableCell>
496 <Tooltip>
497 <TooltipTrigger
498 render={<Button size="icon-xs" variant="ghost" />}
499 disabled={locked}
500 aria-label={
501 row.removed
502 ? `Undo reset for ${row.model}`
503 : row.isNew
504 ? "Remove new model"
505 : `Reset price for ${row.model} to automatic`
506 }
507 onClick={() => {
508 if (row.isNew)
509 setDrafts((previous) =>
510 previous.filter((entry) => entry.id !== row.id),
511 );
512 else if (row.removed)
513 updateOrDropDraft({ ...row, removed: false });
514 else updateDraft({ ...row, removed: true });
515 }}
516 >
517 {row.isNew ? (
518 <XIcon aria-hidden />
519 ) : (
520 <RotateCcwIcon aria-hidden />
521 )}
522 </TooltipTrigger>
523 <TooltipPopup>
524 {row.removed
525 ? "Undo reset"
526 : row.isNew
527 ? "Remove row"
528 : "Reset to automatic"}
529 </TooltipPopup>
530 </Tooltip>
531 </TableCell>
532 </TableRow>
533 );
534 })
535 )}
536 </TableBody>
537 </Table>
538 </div>
539 <datalist id="usage-price-models">
540 {models
541 .filter((model) => !customModels.includes(model))
542 .map((model) => (
543 <option key={model} value={model} />
544 ))}
545 </datalist>
546 <datalist id="usage-alias-models">
547 {models
548 .filter((model) =>
549 selected.every(
550 (environment) => !Object.hasOwn(environment.aliases ?? {}, model),
551 ),
552 )
553 .map((model) => (
554 <option key={model} value={model} />
555 ))}
556 </datalist>
557 <p className="text-xs text-muted-foreground">
558 Blank cache rates use the input price. Enter 0 for free tokens. A mapped model’s
559 usage counts as the model it maps to.
560 {selected.length > 1
561 ? " Mixed cells keep each environment’s rate until you edit them."
562 : ""}
563 </p>
564 </>
565 )}
566 {attempt ? (
567 <div role="status" className="grid gap-1 text-xs">
568 {attempt.destinations.map((destination) => {
569 const result = attempt.results.get(destination.environmentId);
570 return (
571 <div key={destination.environmentId} className="flex justify-between gap-3">
572 <span className="truncate text-muted-foreground">{destination.label}</span>
573 <span
574 className={
575 result?.status === "failed"
576 ? "text-right text-destructive"
577 : "text-muted-foreground"
578 }
579 >
580 {result?.status === "failed"
581 ? `Not saved · ${result.error}`
582 : result?.status === "saved"
583 ? "Saved"
584 : "Saving…"}
585 </span>
586 </div>
587 );
588 })}
589 </div>
590 ) : null}
591 </DialogPanel>
592 <DialogFooter variant="bare" className="items-center sm:justify-between">
593 <span className="text-xs text-muted-foreground">
594 {hasChanges ? `Changes apply to ${destinationLabel}` : ""}
595 </span>
596 <div className="flex w-full flex-wrap justify-end gap-2 sm:w-auto">
597 {hasChanges ? (
598 <Button variant="ghost" disabled={pending} onClick={discard}>
599 {failedDestinations.length > 0 ? "Discard pending changes" : "Discard changes"}
600 </Button>
601 ) : null}
602 <Button
603 disabled={
604 pending ||
605 (!hasChanges && failedDestinations.length === 0) ||
606 (failedDestinations.length === 0 && (errors.size > 0 || selected.length === 0))
607 }
608 onClick={() => void save(failedDestinations.length > 0)}
609 >
610 {pending
611 ? "Saving…"
612 : failedDestinations.length > 0
613 ? "Retry failed saves"
614 : "Save changes"}
615 </Button>
616 </div>
617 </DialogFooter>
618 </DialogPopup>
619 </Dialog>
620 );
621}