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

UsagePriceOverrides.tsx

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