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