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

UsagePriceOverrides.tsx

318 lines11.6 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { EnvironmentId, UsageModelPriceOverride } from "@t3tools/contracts";
3import { useState } from "react";
4​
5import { isElectron } from "../../env";
6import {
7 type EnvironmentPresentation,
8 useEnvironments,
9 usePrimaryEnvironmentId,
10} from "../../state/environments";
11import { serverEnvironment } from "../../state/server";
12import { useEnvironmentSessionState } from "../../state/session";
13import { useAtomCommand } from "../../state/use-atom-command";
14import type { EnvironmentUsageStatus } from "../../state/usage";
15import {
16 resolvePrimaryOperateAccess,
17 resolveRemoteOperateAccess,
18} from "../settings/ProviderSettingsPanel.logic";
19import { Button } from "../ui/button";
20import {
21 Dialog,
22 DialogDescription,
23 DialogHeader,
24 DialogPanel,
25 DialogPopup,
26 DialogTitle,
27} from "../ui/dialog";
28import { Input } from "../ui/input";
29import { Label } from "../ui/label";
30import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
31import { parseUsagePriceForm, USAGE_PRICE_FIELDS, usagePriceForm } from "./usagePriceForm";
32​
33export function UsagePriceOverrides({
34 usage,
35}: {
36 readonly usage: readonly EnvironmentUsageStatus[];
37}) {
38 const [open, setOpen] = useState(false);
39 return (
40 <>
41 <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
42 Model prices
43 </Button>
44 {open ? <ModelPricesDialog usage={usage} onOpenChange={setOpen} /> : null}
45 </>
46 );
48​
49function ModelPricesDialog({
50 usage,
51 onOpenChange,
52}: {
53 readonly usage: readonly EnvironmentUsageStatus[];
54 readonly onOpenChange: (open: boolean) => void;
55}) {
56 const { environments } = useEnvironments();
57 const primaryEnvironmentId = usePrimaryEnvironmentId();
58 const [selectedId, setSelectedId] = useState<EnvironmentId | null>(primaryEnvironmentId);
59 const environment =
60 environments.find((entry) => entry.environmentId === selectedId) ?? environments[0];
61 const summary = usage.find(
62 (entry) => entry.environmentId === environment?.environmentId,
63 )?.summary;
64 const models = [...new Set(summary?.buckets.map((bucket) => bucket.model) ?? [])].sort();
65​
66 return (
67 <Dialog open onOpenChange={onOpenChange}>
68 <DialogPopup className="max-w-xl">
69 <DialogHeader>
70 <DialogTitle>Model prices</DialogTitle>
71 <DialogDescription>
72 Override estimated costs using USD per million tokens. Prices apply to all saved history
73 on the selected environment.
74 </DialogDescription>
75 </DialogHeader>
76 <DialogPanel className="grid gap-5 pb-6">
77 {environment ? (
78 <>
79 <div className="grid gap-1.5">
80 <Label htmlFor="usage-prices-environment">Environment</Label>
81 <Select
82 value={environment.environmentId}
83 onValueChange={(value) => {
84 const next = environments.find((entry) => entry.environmentId === value);
85 if (next) setSelectedId(next.environmentId);
86 }}
87 >
88 <SelectTrigger id="usage-prices-environment">
89 <SelectValue>{environment.label}</SelectValue>
90 </SelectTrigger>
91 <SelectPopup>
92 {environments.map((entry) => (
93 <SelectItem key={entry.environmentId} value={entry.environmentId}>
94 {entry.label}
95 </SelectItem>
96 ))}
97 </SelectPopup>
98 </Select>
99 </div>
100 <EnvironmentModelPrices
101 key={environment.environmentId}
102 environment={environment}
103 models={models}
104 />
105 </>
106 ) : (
107 <p className="text-sm text-muted-foreground">
108 Connect an environment to set model prices.
109 </p>
110 )}
111 </DialogPanel>
112 </DialogPopup>
113 </Dialog>
114 );
116​
117function EnvironmentModelPrices({
118 environment,
119 models,
120}: {
121 readonly environment: EnvironmentPresentation;
122 readonly models: readonly string[];
123}) {
124 const settings = useAtomValue(serverEnvironment.settingsValueAtom(environment.environmentId));
125 const session = useEnvironmentSessionState(environment.environmentId);
126 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
127 const [form, setForm] = useState(usagePriceForm());
128 const [editingModel, setEditingModel] = useState<string | null>(null);
129 const [pending, setPending] = useState(false);
130 const [error, setError] = useState<string | null>(null);
131 const prices = settings?.usagePriceOverrides ?? {};
132 const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
133 const access = isPrimary
134 ? resolvePrimaryOperateAccess({
135 isPrimary,
136 hasDesktopBridge: isElectron,
137 session: session.data,
138 isPending: session.isPending,
139 hasError: session.hasError,
140 })
141 : resolveRemoteOperateAccess({
142 session: session.data,
143 isPending: session.isPending,
144 hasError: session.hasError,
145 });
146 const supportsOverrides =
147 environment.serverConfig?.environment.capabilities.usagePriceOverrides === true;
148 const unavailable =
149 environment.connection.phase !== "connected"
150 ? "Connect this environment to change its model prices."
151 : settings === null
152 ? "Loading model prices..."
153 : !supportsOverrides
154 ? "Update this environment's server to set model prices."
155 : access === "pending"
156 ? "Checking permissions..."
157 : access === "denied"
158 ? "This session can view model prices but cannot change them."
159 : null;
160 const readOnly = unavailable !== null || pending;
161 const parsed = parseUsagePriceForm(form);
162 const duplicate = editingModel === null && parsed !== null && Object.hasOwn(prices, parsed.model);
163​
164 const reset = () => {
165 setEditingModel(null);
166 setForm(usagePriceForm());
167 setError(null);
168 };
169 const save = async (model: string, price: UsageModelPriceOverride | null) => {
170 if (readOnly) return;
171 setPending(true);
172 setError(null);
173 try {
174 const result = await updateSettings({
175 environmentId: environment.environmentId,
176 input: { patch: { usagePriceOverrides: { [model]: price } } },
177 });
178 if (result._tag === "Failure") {
179 setError("Could not save model prices. Try again.");
180 } else if (price !== null || editingModel === model) {
181 reset();
182 }
183 } finally {
184 setPending(false);
185 }
186 };
187​
188 return (
189 <>
190 {Object.keys(prices).length > 0 ? (
191 <ul className="divide-y divide-border rounded-lg border border-border">
192 {Object.entries(prices)
193 .sort(([left], [right]) => left.localeCompare(right))
194 .map(([model, price]) => (
195 <li key={model} className="flex flex-wrap items-center gap-3 p-3">
196 <div className="min-w-0 flex-1">
197 <p className="break-all text-sm font-medium">{model}</p>
198 <p className="text-xs text-muted-foreground">
199 Input ${price.inputCostPerMillionTokens} · Output $
200 {price.outputCostPerMillionTokens}
201 <br />
202 Cache read $
203 {price.cacheReadCostPerMillionTokens ?? price.inputCostPerMillionTokens}
204 {" · "}Cache write $
205 {price.cacheWriteCostPerMillionTokens ?? price.inputCostPerMillionTokens}
206 </p>
207 </div>
208 <Button
209 variant="ghost"
210 size="xs"
211 disabled={readOnly}
212 aria-label={`Edit price for ${model}`}
213 onClick={() => {
214 setEditingModel(model);
215 setForm(usagePriceForm(model, price));
216 setError(null);
217 }}
218 >
219 Edit
220 </Button>
221 <Button
222 variant="ghost"
223 size="xs"
224 disabled={readOnly}
225 aria-label={`Remove price for ${model}`}
226 onClick={() => void save(model, null)}
227 >
228 Remove
229 </Button>
230 </li>
231 ))}
232 </ul>
233 ) : (
234 <p className="text-sm text-muted-foreground">
235 No custom prices. Public model pricing is used when available.
236 </p>
237 )}
238 {unavailable ? <p className="text-sm text-muted-foreground">{unavailable}</p> : null}
239 <form
240 className="grid gap-4"
241 onSubmit={(event) => {
242 event.preventDefault();
243 if (parsed && !duplicate) void save(parsed.model, parsed.price);
244 }}
245 >
246 <fieldset disabled={readOnly} className="grid min-w-0 gap-4">
247 <legend className="mb-3 text-sm font-medium">
248 {editingModel === null ? "Add model price" : "Edit model price"}
249 </legend>
250 <div className="grid gap-1.5">
251 <Label htmlFor="usage-price-model">Model ID</Label>
252 <Input
253 id="usage-price-model"
254 list="usage-price-models"
255 value={form.model}
256 disabled={editingModel !== null}
257 placeholder="Exact model ID from usage"
258 autoComplete="off"
259 spellCheck={false}
260 required
261 onChange={(event) => setForm({ ...form, model: event.target.value })}
262 />
263 <datalist id="usage-price-models">
264 {models.map((model) => (
265 <option key={model} value={model} />
266 ))}
267 </datalist>
268 {duplicate ? (
269 <p role="alert" className="text-xs text-destructive">
270 This model already has a price. Use Edit to change it.
271 </p>
272 ) : null}
273 </div>
274 <div className="grid grid-cols-2 gap-3">
275 {USAGE_PRICE_FIELDS.map((field) => (
276 <div key={field.key} className="grid gap-1.5">
277 <Label htmlFor={`usage-price-${field.key}`}>
278 {field.label}
279 {field.optional ? " (optional)" : ""}
280 </Label>
281 <Input
282 id={`usage-price-${field.key}`}
283 type="number"
284 min="0"
285 step="any"
286 inputMode="decimal"
287 required={!field.optional}
288 value={form[field.key]}
289 placeholder={field.optional ? "Use input rate" : "0.00"}
290 onChange={(event) => setForm({ ...form, [field.key]: event.target.value })}
291 />
292 </div>
293 ))}
294 </div>
295 <p className="text-xs text-muted-foreground">
296 Blank cache rates use the input price. Enter 0 for free tokens. Model IDs match exactly.
297 Remove a price to restore automatic pricing.
298 </p>
299 {error ? (
300 <p role="alert" className="text-sm text-destructive">
301 {error}
302 </p>
303 ) : null}
304 <div className="flex justify-end gap-2">
305 {editingModel !== null ? (
306 <Button variant="outline" onClick={reset}>
307 Cancel
308 </Button>
309 ) : null}
310 <Button type="submit" disabled={parsed === null || duplicate || readOnly}>
311 {pending ? "Saving..." : editingModel === null ? "Add price" : "Save price"}
312 </Button>
313 </div>
314 </fieldset>
315 </form>
316 </>
317 );