Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsagePriceOverrides.tsx

667 lines28.0 KB

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, plural, part } 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`${plural(
193 { count: selected.length },
194 {
195 one: part`${{ count: selected.length }} environments`,
196 other: part`${{ count: selected.length }} environments`,
197 },
198 )}`;
199 const selectionLabel = selectedIds === null ? gt`All environments` : destinationLabel;
200 const discard = () => {
201 setDrafts([]);
202 setAttempt(null);
203 };
204 const selectEnvironments = (ids: ReadonlySet<EnvironmentId> | null) => {
205 setSelectedIds(ids);
206 setAttempt(null);
207 };
208 const updateDraft = (draft: UsagePriceDraft) => {
209 setDrafts((previous) =>
210 previous.some((entry) => entry.id === draft.id)
211 ? previous.map((entry) => (entry.id === draft.id ? draft : entry))
212 : [...previous, draft],
213 );
214 setAttempt(null);
215 };
216 const matchesSaved = (
217 row: UsagePriceDraft,
218 cell: { value: string; placeholder: string },
219 value: string,
220 ) =>
221 !row.isNew &&
222 cell.placeholder !== gt`Mixed` &&
223 cell.placeholder !== gt`Unavailable` &&
224 value === cell.value;
225 const updateOrDropDraft = (draft: UsagePriceDraft) => {
226 if (!draft.isNew && Object.keys(draft.values).length === 0 && draft.alias === undefined)
227 setDrafts((previous) => previous.filter((entry) => entry.id !== draft.id));
228 else updateDraft(draft);
229 };
230 const editCell = (row: UsagePriceDraft, field: UsagePriceField, value: string) => {
231 const values = { ...row.values, [field]: value };
232 const original = usagePriceCell(selected, row.model, field, messages);
233 if (matchesSaved(row, original, value)) delete values[field];
234 updateOrDropDraft({ ...row, values });
235 };
236 const editAlias = (row: UsagePriceDraft, value: string) => {
237 const { alias: _alias, ...rest } = row;
238 const original = usageAliasCell(selected, row.model, messages);
239 updateOrDropDraft(
240 matchesSaved(row, original, value)
241 ? // A restored mapping hides the price inputs, so their typed values go too.
242 { ...rest, values: value === "" ? rest.values : {} }
243 : { ...rest, alias: value },
244 );
245 };
246 const save = async (retry = false) => {
247 if (pending) return;
248 const destinations = retry ? failedDestinations : selected;
249 const edits = retry && attempt ? attempt.drafts : stagedDrafts;
250 if (destinations.length === 0 || edits.length === 0) return;
251 const targets = destinations.map(
252 (destination) =>
253 environments.find(
254 (environment) => environment.environmentId === destination.environmentId,
255 ) ?? {
256 ...destination,
257 prices: null,
258 aliases: null,
259 unavailable: gt`Environment removed`,
260 },
261 );
262 const changes = new Map(
263 targets.map((target) => [
264 target.environmentId,
265 usagePriceTableChanges(target, edits, messages),
266 ]),
267 );
268 setPending(true);
269 setAttempt((previous) => ({
270 drafts: edits,
271 destinations: retry && previous ? previous.destinations : targets,
272 results: new Map([
273 ...(retry && previous ? previous.results : []),
274 ...targets.map((target) => [target.environmentId, { status: "saving" } as const] as const),
275 ]),
276 }));
277 let failed = false;
278 await writeUsagePrices({
279 targets: targets.map((target) => ({
280 ...target,
281 unavailable:
282 target.unavailable ?? [...changes.get(target.environmentId)!.errors.values()][0] ?? null,
283 })),
284 changes: new Map([...changes].map(([id, plan]) => [id, plan.changes])),
285 write: async (input) =>
286 readEnvironmentScope(input.environmentId, AuthSettingsWriteScope)
287 ? updateSettings(input)
288 : { _tag: "Failure" },
289 onResult: (environmentId, result) => {
290 if (result.status === "failed") failed = true;
291 setAttempt((previous) =>
292 previous === null
293 ? null
294 : { ...previous, results: new Map(previous.results).set(environmentId, result) },
295 );
296 },
297 });
298 setPending(false);
299 if (!failed) setDrafts([]);
300 };
301​
302 return (
303 <Dialog
304 open
305 onOpenChange={(open) => {
306 if (!pending) onOpenChange(open);
307 }}
308 >
309 <DialogPopup className="max-w-4xl">
310 <DialogHeader>
311 <DialogTitle>
312 <T>Custom model prices</T>
313 </DialogTitle>
314 <DialogDescription>
315 <T>
316 Prices and mappings apply to all past and future usage on the environments you select.
317 </T>
318 </DialogDescription>
319 </DialogHeader>
320 <DialogPanel>
321 <div className="flex flex-wrap items-center justify-between gap-2">
322 <div className="flex min-w-0 items-center gap-2">
323 <Label id="usage-prices-apply-label" className="shrink-0">
324 <T>Apply to</T>
325 </Label>
326 <Menu>
327 <MenuTrigger
328 render={<Button variant="outline" size="sm" className="min-w-0" />}
329 aria-labelledby="usage-prices-apply-label usage-prices-selection"
330 disabled={pending || hasChanges}
331 >
332 <span id="usage-prices-selection" className="truncate">
333 {selectionLabel}
334 </span>
335 <ChevronDownIcon className="size-3.5 shrink-0" aria-hidden />
336 </MenuTrigger>
337 <MenuPopup align="start">
338 <MenuCheckboxItem
339 checked={selectedIds === null}
340 closeOnClick={false}
341 onCheckedChange={(checked) => selectEnvironments(checked ? null : new Set())}
342 >
343 <T>All environments</T>
344 </MenuCheckboxItem>
345 <MenuSeparator />
346 {environments.map((environment) => (
347 <MenuCheckboxItem
348 key={environment.environmentId}
349 checked={selectedIds === null || selectedIds.has(environment.environmentId)}
350 closeOnClick={false}
351 onCheckedChange={(checked) => {
352 const next = new Set(selected.map((target) => target.environmentId));
353 if (checked) next.add(environment.environmentId);
354 else next.delete(environment.environmentId);
355 selectEnvironments(next.size === environments.length ? null : next);
356 }}
357 >
358 <span className="flex min-w-0 items-center gap-3">
359 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
360 {environment.unavailable ? (
361 <span className="text-xs text-muted-foreground">
362 {environment.unavailable}
363 </span>
364 ) : null}
365 </span>
366 </MenuCheckboxItem>
367 ))}
368 </MenuPopup>
369 </Menu>
370 </div>
371 <span className="text-xs text-muted-foreground">
372 <T>USD / million tokens</T>
373 </span>
374 </div>
375 {selected.length === 0 ? (
376 <p className="text-sm text-muted-foreground">
377 {environments.length === 0
378 ? gt`Connect an environment to set model prices.`
379 : gt`Select an environment to see and change its model prices.`}
380 </p>
381 ) : (
382 <>
383 <div className="min-w-0 overflow-hidden rounded-lg border border-border">
384 <Table className="min-w-180 table-fixed" aria-label={gt`Custom model prices`}>
385 <colgroup>
386 <col className="w-[22%]" />
387 <col className="w-[18%]" />
388 {USAGE_PRICE_FIELDS.map((field) => (
389 <col key={field.key} />
390 ))}
391 <col className="w-10" />
392 </colgroup>
393 <TableHeader>
394 <TableRow>
395 <TableHead>
396 <T>Model ID</T>
397 </TableHead>
398 <TableHead>
399 <T>Map to</T>
400 </TableHead>
401 {USAGE_PRICE_FIELDS.map((field) => (
402 <TableHead key={field.key}>{messages(field.label)}</TableHead>
403 ))}
404 <TableHead>
405 <Button
406 size="icon-xs"
407 variant="ghost"
408 aria-label={gt`Add model price`}
409 disabled={locked}
410 onClick={() => {
411 const id = `new:${nextRowId.current++}`;
412 focusRowRef.current = id;
413 updateDraft({ id, model: "", isNew: true, values: {} });
414 }}
415 >
416 <PlusIcon aria-hidden />
417 </Button>
418 </TableHead>
419 </TableRow>
420 </TableHeader>
421 <TableBody>
422 {rows.length === 0 ? (
423 <TableRow>
424 <TableCell colSpan={7} className="text-center whitespace-normal">
425 <p className="py-6 text-muted-foreground">
426 {selected.some((environment) => environment.prices === null)
427 ? gt`Some environment prices are unavailable.`
428 : gt`No custom prices or mappings. Add a row to set one.`}
429 </p>
430 </TableCell>
431 </TableRow>
432 ) : (
433 rows.map((row) => {
434 const aliasCell = usageAliasCell(selected, row.model, messages);
435 const alias = (row.alias ?? aliasCell.value).trim();
436 const error = awaitingPrice.has(row.id) ? undefined : errors.get(row.id);
437 return (
438 <TableRow key={row.id} data-row-id={row.id}>
439 <TableCell className="whitespace-normal">
440 {row.isNew ? (
441 <Input
442 size="compact"
443 value={row.model}
444 ref={(node) => {
445 if (node && focusRowRef.current === row.id) {
446 node.focus();
447 focusRowRef.current = null;
448 }
449 }}
450 aria-label={gt`New model ID`}
451 aria-invalid={error !== undefined || undefined}
452 list="usage-price-models"
453 placeholder={gt`Model ID`}
454 autoComplete="off"
455 spellCheck={false}
456 disabled={locked}
457 onChange={(event) =>
458 updateDraft({ ...row, model: event.target.value })
459 }
460 />
461 ) : (
462 <span
463 className={cn(
464 "block break-all",
465 row.removed && "text-muted-foreground line-through",
466 )}
467 >
468 {row.model}
469 </span>
470 )}
471 {error !== undefined ? (
472 <p role="alert" className="mt-1 text-xs text-destructive">
473 {error}
474 </p>
475 ) : null}
476 </TableCell>
477 {row.removed ? (
478 <TableCell colSpan={5}>
479 <span className="text-muted-foreground">
480 <T>Automatic pricing after saving</T>
481 </span>
482 </TableCell>
483 ) : (
484 <TableCell>
485 <Input
486 size="compact"
487 value={row.alias ?? aliasCell.value}
488 aria-label={gt`Map ${{ model: row.model || gt`new model` }} to model`}
489 list="usage-alias-models"
490 placeholder={row.isNew ? gt`Optional` : aliasCell.placeholder}
491 autoComplete="off"
492 spellCheck={false}
493 disabled={locked}
494 onChange={(event) => editAlias(row, event.target.value)}
495 />
496 </TableCell>
497 )}
498 {row.removed ? null : alias !== "" ? (
499 <TableCell colSpan={4} className="whitespace-normal">
500 <span className="break-all text-muted-foreground">
501 <T>
502 Counted as <Var>{alias}</Var>
503 </T>
504 </span>
505 </TableCell>
506 ) : (
507 USAGE_PRICE_FIELDS.map((field) => {
508 const cell = usagePriceCell(
509 selected,
510 row.model,
511 field.key,
512 messages,
513 );
514 const value =
515 row.values[field.key] ?? (row.isNew ? "" : cell.value);
516 return (
517 <TableCell key={field.key}>
518 <Input
519 size="compact"
520 inputMode="decimal"
521 aria-label={gt`${{ field: messages(field.label) }} price for ${{ model: row.model || gt`new model` }}`}
522 value={value}
523 placeholder={
524 row.isNew
525 ? field.optional
526 ? gt`Input rate`
527 : "0.00"
528 : cell.placeholder
529 }
530 autoComplete="off"
531 disabled={locked}
532 font="mono"
533 onChange={(event) => {
534 if (isUsagePriceEdit(value, event.target.value))
535 editCell(row, field.key, event.target.value);
536 }}
537 />
538 </TableCell>
539 );
540 })
541 )}
542 <TableCell>
543 <Tooltip>
544 <TooltipTrigger
545 render={<Button size="icon-xs" variant="ghost" />}
546 disabled={locked}
547 aria-label={
548 row.removed
549 ? gt`Undo reset for ${{ model: row.model }}`
550 : row.isNew
551 ? gt`Remove new model`
552 : gt`Reset price for ${{ model: row.model }} to automatic`
553 }
554 onClick={() => {
555 if (row.isNew)
556 setDrafts((previous) =>
557 previous.filter((entry) => entry.id !== row.id),
558 );
559 else if (row.removed)
560 updateOrDropDraft({ ...row, removed: false });
561 else updateDraft({ ...row, removed: true });
562 }}
563 >
564 {row.isNew ? (
565 <XIcon aria-hidden />
566 ) : (
567 <RotateCcwIcon aria-hidden />
568 )}
569 </TooltipTrigger>
570 <TooltipPopup>
571 {row.removed
572 ? gt`Undo reset`
573 : row.isNew
574 ? gt`Remove row`
575 : gt`Reset to automatic`}
576 </TooltipPopup>
577 </Tooltip>
578 </TableCell>
579 </TableRow>
580 );
581 })
582 )}
583 </TableBody>
584 </Table>
585 </div>
586 <datalist id="usage-price-models">
587 {models
588 .filter((model) => !customModels.includes(model))
589 .map((model) => (
590 <option key={model} value={model} />
591 ))}
592 </datalist>
593 <datalist id="usage-alias-models">
594 {models
595 .filter((model) =>
596 selected.every(
597 (environment) => !Object.hasOwn(environment.aliases ?? {}, model),
598 ),
599 )
600 .map((model) => (
601 <option key={model} value={model} />
602 ))}
603 </datalist>
604 <p className="text-xs text-muted-foreground">
605 {gt`Blank cache rates use the input price. Enter 0 for free tokens. A mapped model’s usage counts as the model it maps to.`}
606 {selected.length > 1
607 ? ` ${gt`Mixed cells keep each environment’s rate until you edit them.`}`
608 : ""}
609 </p>
610 </>
611 )}
612 {attempt ? (
613 <div role="status" className="grid gap-1 text-xs">
614 {attempt.destinations.map((destination) => {
615 const result = attempt.results.get(destination.environmentId);
616 return (
617 <div key={destination.environmentId} className="flex justify-between gap-3">
618 <span className="truncate text-muted-foreground">{destination.label}</span>
619 <span
620 className={
621 result?.status === "failed"
622 ? "text-right text-destructive"
623 : "text-muted-foreground"
624 }
625 >
626 {result?.status === "failed"
627 ? gt`Not saved · ${{ error: result.error }}`
628 : result?.status === "saved"
629 ? gt`Saved`
630 : gt`Saving…`}
631 </span>
632 </div>
633 );
634 })}
635 </div>
636 ) : null}
637 </DialogPanel>
638 <DialogFooter variant="bare" className="items-center sm:justify-between">
639 <span className="text-xs text-muted-foreground sm:flex-1">
640 {hasChanges ? gt`Changes apply to ${{ destination: destinationLabel }}` : ""}
641 </span>
642 <div className="flex w-full flex-wrap justify-end gap-2 sm:w-auto">
643 {hasChanges ? (
644 <Button variant="ghost" disabled={pending} onClick={discard}>
645 {failedDestinations.length > 0 ? gt`Discard pending changes` : gt`Discard changes`}
646 </Button>
647 ) : null}
648 <Button
649 disabled={
650 pending ||
651 (!hasChanges && failedDestinations.length === 0) ||
652 (failedDestinations.length === 0 && (errors.size > 0 || selected.length === 0))
653 }
654 onClick={() => void save(failedDestinations.length > 0)}
655 >
656 {pending
657 ? gt`Saving…`
658 : failedDestinations.length > 0
659 ? gt`Retry failed saves`
660 : gt`Save changes`}
661 </Button>
662 </div>
663 </DialogFooter>
664 </DialogPopup>
665 </Dialog>
666 );