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