improve budget editor component

This commit is contained in:
miloschwartz
2026-08-14 10:27:08 -04:00
parent 03118f1ede
commit c49c6f5837
6 changed files with 526 additions and 469 deletions
+5 -5
View File
@@ -1099,7 +1099,7 @@
"accessRoleErrorNewRequired": "New role is required", "accessRoleErrorNewRequired": "New role is required",
"accessRoleErrorRemove": "Failed to remove role", "accessRoleErrorRemove": "Failed to remove role",
"accessRoleErrorRemoveDescription": "An error occurred while removing the role.", "accessRoleErrorRemoveDescription": "An error occurred while removing the role.",
"accessRoleInferenceBudget": "Inference Budget", "accessRoleInferenceBudget": "AI Budget",
"accessRoleInferenceBudgetDescription": "Configure how members of this role restrict AI usage based on spending or token limits", "accessRoleInferenceBudgetDescription": "Configure how members of this role restrict AI usage based on spending or token limits",
"accessRoleName": "Role Name", "accessRoleName": "Role Name",
"accessRoleQuestionRemove": "You're about to delete the `{name}` role. You cannot undo this action.", "accessRoleQuestionRemove": "You're about to delete the `{name}` role. You cannot undo this action.",
@@ -1720,7 +1720,7 @@
"virtualApiKeysErrorFetchSecret": "Error loading secret", "virtualApiKeysErrorFetchSecret": "Error loading secret",
"virtualApiKeysErrorFetchSecretDescription": "Failed to load the virtual API key secret", "virtualApiKeysErrorFetchSecretDescription": "Failed to load the virtual API key secret",
"virtualApiKeysFilterUnassigned": "Unassigned", "virtualApiKeysFilterUnassigned": "Unassigned",
"virtualApiKeysInferenceBudget": "Inference Budget", "virtualApiKeysInferenceBudget": "Budget",
"virtualApiKeysInferenceBudgetDescription": "Configure how this key restricts AI usage based on spending or token limits", "virtualApiKeysInferenceBudgetDescription": "Configure how this key restricts AI usage based on spending or token limits",
"myVirtualApiKeysTitle": "Your API Keys", "myVirtualApiKeysTitle": "Your API Keys",
"myVirtualApiKeysDescription": "View your identity key and any virtual API keys attributed to you in this organization", "myVirtualApiKeysDescription": "View your identity key and any virtual API keys attributed to you in this organization",
@@ -1924,10 +1924,10 @@
"aiProviderModelsSourceAll": "Matches every model key", "aiProviderModelsSourceAll": "Matches every model key",
"aiProviderModelsBudgetConfigured": "Budget configured", "aiProviderModelsBudgetConfigured": "Budget configured",
"aiProviderModelsEditTitle": "Edit Model", "aiProviderModelsEditTitle": "Edit Model",
"aiProviderModelsEditDescription": "Update the model key or configure its inference budget.", "aiProviderModelsEditDescription": "Update the model key or configure its budget.",
"aiProviderModelsBudgetTab": "Inference Budget", "aiProviderModelsBudgetTab": "Budget",
"aiProviderModelsBudgetDescription": "Configure how this model restricts usage based on spending or token limits", "aiProviderModelsBudgetDescription": "Configure how this model restricts usage based on spending or token limits",
"aiProviderModelsBudgetUnsaved": "Save this model first to configure its inference budget.", "aiProviderModelsBudgetUnsaved": "Save this model first to configure its budget.",
"aiProviderModelsKeyLabel": "Model Key", "aiProviderModelsKeyLabel": "Model Key",
"aiProviderModelsKeyRequired": "Enter a model key", "aiProviderModelsKeyRequired": "Enter a model key",
"aiProviderModelsKeyDuplicate": "This model key is already on a list", "aiProviderModelsKeyDuplicate": "This model key is already on a list",
+1 -2
View File
@@ -964,8 +964,7 @@ function EditModelCredenza({
rows={pendingBudgetRows} rows={pendingBudgetRows}
onChange={setPendingBudgetRows} onChange={setPendingBudgetRows}
disabled={ disabled={
budgetsQuery.isLoading || budgetsQuery.isLoading
savingBudgets
} }
attemptedSave={ attemptedSave={
attemptedBudgetsSave attemptedBudgetsSave
+196 -147
View File
@@ -1,6 +1,8 @@
"use client"; "use client";
import { import {
SettingsFormCell,
SettingsFormGrid,
SettingsSection, SettingsSection,
SettingsSectionBody, SettingsSectionBody,
SettingsSectionDescription, SettingsSectionDescription,
@@ -9,7 +11,6 @@ import {
SettingsSectionTitle SettingsSectionTitle
} from "@app/components/Settings"; } from "@app/components/Settings";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { DataTableEmptyState } from "@app/components/ui/data-table-empty-state";
import { Input } from "@app/components/ui/input"; import { Input } from "@app/components/ui/input";
import { import {
Select, Select,
@@ -18,14 +19,6 @@ import {
SelectTrigger, SelectTrigger,
SelectValue SelectValue
} from "@app/components/ui/select"; } from "@app/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow
} from "@app/components/ui/table";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { createApiClient, formatAxiosError } from "@app/lib/api"; import { createApiClient, formatAxiosError } from "@app/lib/api";
@@ -37,6 +30,7 @@ import {
type AiBudgetScope, type AiBudgetScope,
type AiBudgetUnit type AiBudgetUnit
} from "@app/lib/aiBudgetScope"; } from "@app/lib/aiBudgetScope";
import { cn } from "@app/lib/cn";
import { aiBudgetQueries } from "@app/lib/queries"; import { aiBudgetQueries } from "@app/lib/queries";
import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { AiBudget } from "@server/db"; import type { AiBudget } from "@server/db";
@@ -127,6 +121,113 @@ export function getBudgetRowsErrors(rows: BudgetRow[]): {
return { conflictingKeys, invalidAmountKeys }; return { conflictingKeys, invalidAmountKeys };
} }
type BudgetRowFieldProps = {
row: BudgetRow;
disabled: boolean;
showInvalidAmount: boolean;
showConflict: boolean;
unitLabels: Record<AiBudgetUnit, string>;
periodLabels: Record<AiBudgetPeriod, string>;
amountPlaceholder: string;
onUpdate: (patch: Partial<BudgetRow>) => void;
};
function BudgetRowAmountInput({
row,
disabled,
showInvalidAmount,
amountPlaceholder,
onUpdate,
className
}: Pick<
BudgetRowFieldProps,
"row" | "disabled" | "showInvalidAmount" | "amountPlaceholder" | "onUpdate"
> & { className?: string }) {
return (
<Input
type="number"
min="0"
step="any"
placeholder={amountPlaceholder}
value={row.amount}
aria-invalid={showInvalidAmount}
disabled={disabled}
onChange={(e) => onUpdate({ amount: e.target.value })}
className={cn("w-full min-w-0", className)}
/>
);
}
function BudgetRowUnitSelect({
row,
disabled,
showConflict,
unitLabels,
onUpdate,
className
}: Pick<
BudgetRowFieldProps,
"row" | "disabled" | "showConflict" | "unitLabels" | "onUpdate"
> & { className?: string }) {
return (
<Select
value={row.unit}
onValueChange={(value) => onUpdate({ unit: value as AiBudgetUnit })}
disabled={disabled}
>
<SelectTrigger
className={cn("w-full min-w-0", className)}
aria-invalid={showConflict}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{AI_BUDGET_UNITS.map((unit) => (
<SelectItem key={unit} value={unit}>
{unitLabels[unit]}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
function BudgetRowPeriodSelect({
row,
disabled,
showConflict,
periodLabels,
onUpdate,
className
}: Pick<
BudgetRowFieldProps,
"row" | "disabled" | "showConflict" | "periodLabels" | "onUpdate"
> & { className?: string }) {
return (
<Select
value={row.period}
onValueChange={(value) =>
onUpdate({ period: value as AiBudgetPeriod })
}
disabled={disabled}
>
<SelectTrigger
className={cn("w-full min-w-0", className)}
aria-invalid={showConflict}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{AI_BUDGET_PERIODS.map((period) => (
<SelectItem key={period} value={period}>
{periodLabels[period]}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
export function BudgetRowsFields({ export function BudgetRowsFields({
rows, rows,
onChange, onChange,
@@ -173,6 +274,8 @@ export function BudgetRowsFields({
tokens: t("aiBudgetUnitTokens") tokens: t("aiBudgetUnitTokens")
}; };
const amountPlaceholder = t("aiBudgetAmountPlaceholder");
const addRowButton = ( const addRowButton = (
<Button <Button
type="button" type="button"
@@ -185,148 +288,90 @@ export function BudgetRowsFields({
</Button> </Button>
); );
return ( const errorMessage =
<div className="space-y-4"> conflictingKeys.size > 0 ||
<Table> (attemptedSave && invalidAmountKeys.size > 0) ? (
<TableHeader> <p className="text-destructive text-sm">
<TableRow>
<TableHead>{t("aiBudgetAmount")}</TableHead>
<TableHead>{t("aiBudgetUnit")}</TableHead>
<TableHead>{t("aiBudgetPeriod")}</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.length === 0 ? (
<DataTableEmptyState
colSpan={4}
message={t("aiBudgetEmpty")}
action={addRowButton}
compact
/>
) : (
rows.map((row) => {
const showConflict = conflictingKeys.has(row.key);
const showInvalidAmount =
attemptedSave &&
invalidAmountKeys.has(row.key);
return (
<TableRow key={row.key}>
<TableCell>
<Input
type="number"
min="0"
step="any"
placeholder={t(
"aiBudgetAmountPlaceholder"
)}
value={row.amount}
aria-invalid={showInvalidAmount}
disabled={disabled}
onChange={(e) =>
updateRow(row.key, {
amount: e.target.value
})
}
className="w-full min-w-0"
/>
</TableCell>
<TableCell>
<Select
value={row.unit}
onValueChange={(value) =>
updateRow(row.key, {
unit: value as AiBudgetUnit
})
}
disabled={disabled}
>
<SelectTrigger
className="w-full min-w-0"
aria-invalid={showConflict}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{AI_BUDGET_UNITS.map(
(unit) => (
<SelectItem
key={unit}
value={unit}
>
{
unitLabels[
unit
]
}
</SelectItem>
)
)}
</SelectContent>
</Select>
</TableCell>
<TableCell>
<Select
value={row.period}
onValueChange={(value) =>
updateRow(row.key, {
period: value as AiBudgetPeriod
})
}
disabled={disabled}
>
<SelectTrigger
className="w-full min-w-0"
aria-invalid={showConflict}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{AI_BUDGET_PERIODS.map(
(period) => (
<SelectItem
key={period}
value={period}
>
{
periodLabels[
period
]
}
</SelectItem>
)
)}
</SelectContent>
</Select>
</TableCell>
<TableCell>
<div className="flex items-center justify-end space-x-2">
<Button
type="button"
variant="outline"
disabled={disabled}
onClick={() =>
removeRow(row.key)
}
>
Delete
</Button>
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
{(conflictingKeys.size > 0 ||
(attemptedSave && invalidAmountKeys.size > 0)) && (
<p className="text-xs text-destructive">
{conflictingKeys.size > 0 {conflictingKeys.size > 0
? t("aiBudgetConflictError") ? t("aiBudgetConflictError")
: t("aiBudgetInvalidAmountError")} : t("aiBudgetInvalidAmountError")}
</p> </p>
) : null;
function rowFieldProps(row: BudgetRow): BudgetRowFieldProps {
return {
row,
disabled,
showInvalidAmount: attemptedSave && invalidAmountKeys.has(row.key),
showConflict: conflictingKeys.has(row.key),
unitLabels,
periodLabels,
amountPlaceholder,
onUpdate: (patch) => updateRow(row.key, patch)
};
}
return (
<div className="space-y-3">
{rows.length === 0 ? (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
{t("aiBudgetEmpty")}
</p>
{addRowButton}
</div>
) : (
<div className="space-y-2">
{rows.map((row) => {
const fields = rowFieldProps(row);
return (
<div
key={row.key}
className="flex items-center gap-2"
>
<div
className={cn(
"flex h-9 min-w-0 flex-1 overflow-hidden rounded-md border border-input",
"focus-within:border-ring",
(fields.showInvalidAmount ||
fields.showConflict) &&
"border-destructive"
)} )}
>
<BudgetRowUnitSelect
{...fields}
className="h-full w-28 min-w-28 shrink-0 rounded-none border-0 px-2 shadow-none focus-visible:ring-0"
/>
<div
className="w-px shrink-0 bg-border"
aria-hidden
/>
<BudgetRowAmountInput
{...fields}
className="h-full min-w-0 flex-1 rounded-none border-0 text-sm shadow-none focus-visible:border-transparent focus-visible:ring-0"
/>
</div>
<BudgetRowPeriodSelect
{...fields}
className="h-9 w-32 min-w-32 shrink-0"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="shrink-0"
disabled={disabled}
onClick={() => removeRow(row.key)}
aria-label={t("delete")}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
);
})}
</div>
)}
{errorMessage}
{rows.length > 0 && addRowButton} {rows.length > 0 && addRowButton}
</div> </div>
); );
@@ -474,12 +519,16 @@ export function BudgetsEditor({
const body = ( const body = (
<> <>
<SettingsSectionBody> <SettingsSectionBody>
<SettingsFormGrid>
<SettingsFormCell span="half">
<BudgetRowsFields <BudgetRowsFields
rows={rows} rows={rows}
onChange={setRows} onChange={setRows}
disabled={saveLoading || budgetsQuery.isLoading} disabled={budgetsQuery.isLoading}
attemptedSave={attemptedSave} attemptedSave={attemptedSave}
/> />
</SettingsFormCell>
</SettingsFormGrid>
</SettingsSectionBody> </SettingsSectionBody>
<SettingsSectionFooter> <SettingsSectionFooter>
+22 -14
View File
@@ -99,9 +99,7 @@ export default function CreateVirtualApiKeyForm({
const [selectedResources, setSelectedResources] = useState< const [selectedResources, setSelectedResources] = useState<
SelectedResource[] SelectedResource[]
>([]); >([]);
const [pendingBudgetRows, setPendingBudgetRows] = useState<BudgetRow[]>( const [pendingBudgetRows, setPendingBudgetRows] = useState<BudgetRow[]>([]);
[]
);
const [attemptedBudgetsSave, setAttemptedBudgetsSave] = useState(false); const [attemptedBudgetsSave, setAttemptedBudgetsSave] = useState(false);
const formSchema = z.object({ const formSchema = z.object({
@@ -204,10 +202,7 @@ export default function CreateVirtualApiKeyForm({
toast({ toast({
variant: "destructive", variant: "destructive",
title: t("aiBudgetErrorSave"), title: t("aiBudgetErrorSave"),
description: formatAxiosError( description: formatAxiosError(e, t("aiBudgetErrorSave"))
e,
t("aiBudgetErrorSave")
)
}); });
} }
} }
@@ -302,7 +297,9 @@ export default function CreateVirtualApiKeyForm({
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel> <FormLabel>
{t("virtualApiKeysName")} {t(
"virtualApiKeysName"
)}
</FormLabel> </FormLabel>
<FormControl> <FormControl>
<Input {...field} /> <Input {...field} />
@@ -349,14 +346,20 @@ export default function CreateVirtualApiKeyForm({
> >
{selectedUser?.text {selectedUser?.text
? selectedUser.text ? selectedUser.text
: t("userSelect")} : t(
"userSelect"
)}
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" /> <CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="p-0 w-[var(--radix-popover-trigger-width)]"> <PopoverContent className="p-0 w-[var(--radix-popover-trigger-width)]">
<UserSelector <UserSelector
orgId={org.org.orgId} orgId={
selectedUser={selectedUser} org.org.orgId
}
selectedUser={
selectedUser
}
onSelectUser={ onSelectUser={
setSelectedUser setSelectedUser
} }
@@ -375,7 +378,9 @@ export default function CreateVirtualApiKeyForm({
<Checkbox <Checkbox
id="all-resources" id="all-resources"
checked={allResources} checked={allResources}
onCheckedChange={(val) => { onCheckedChange={(
val
) => {
setAllResources( setAllResources(
val as boolean val as boolean
); );
@@ -412,7 +417,9 @@ export default function CreateVirtualApiKeyForm({
)} )}
</FormLabel> </FormLabel>
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger
asChild
>
<Button <Button
variant="outline" variant="outline"
role="combobox" role="combobox"
@@ -436,7 +443,8 @@ export default function CreateVirtualApiKeyForm({
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0"> <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
<MultiResourcesSelector <MultiResourcesSelector
orgId={ orgId={
org.org.orgId org.org
.orgId
} }
selectedResources={ selectedResources={
selectedResources selectedResources
+15 -10
View File
@@ -112,9 +112,7 @@ export default function EditVirtualApiKeyForm({
>([]); >([]);
const [credential, setCredential] = useState<string | null>(null); const [credential, setCredential] = useState<string | null>(null);
const [credentialLoading, setCredentialLoading] = useState(false); const [credentialLoading, setCredentialLoading] = useState(false);
const [pendingBudgetRows, setPendingBudgetRows] = useState<BudgetRow[]>( const [pendingBudgetRows, setPendingBudgetRows] = useState<BudgetRow[]>([]);
[]
);
const [attemptedBudgetsSave, setAttemptedBudgetsSave] = useState(false); const [attemptedBudgetsSave, setAttemptedBudgetsSave] = useState(false);
const budgetScope = { const budgetScope = {
@@ -350,9 +348,7 @@ export default function EditVirtualApiKeyForm({
<div className="flex flex-col gap-y-4 px-1"> <div className="flex flex-col gap-y-4 px-1">
<Form {...form}> <Form {...form}>
<form <form
onSubmit={form.handleSubmit( onSubmit={form.handleSubmit(handleFormSubmit)}
handleFormSubmit
)}
className="space-y-4" className="space-y-4"
id="edit-virtual-api-key-form" id="edit-virtual-api-key-form"
> >
@@ -396,8 +392,12 @@ export default function EditVirtualApiKeyForm({
<PopoverContent className="p-0 w-[var(--radix-popover-trigger-width)]"> <PopoverContent className="p-0 w-[var(--radix-popover-trigger-width)]">
<UserSelector <UserSelector
orgId={org.org.orgId} orgId={org.org.orgId}
selectedUser={selectedUser} selectedUser={
onSelectUser={setSelectedUser} selectedUser
}
onSelectUser={
setSelectedUser
}
/> />
</PopoverContent> </PopoverContent>
</Popover> </Popover>
@@ -427,7 +427,9 @@ export default function EditVirtualApiKeyForm({
field.onChange( field.onChange(
val as boolean val as boolean
); );
if (val) { if (
val
) {
setSelectedResources( setSelectedResources(
[] []
); );
@@ -488,7 +490,10 @@ export default function EditVirtualApiKeyForm({
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0"> <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
<MultiResourcesSelector <MultiResourcesSelector
orgId={org.org.orgId} orgId={
org.org
.orgId
}
selectedResources={ selectedResources={
selectedResources selectedResources
} }
+2 -6
View File
@@ -219,9 +219,7 @@ export function RoleForm({
useState<PendingTextImport | null>(null); useState<PendingTextImport | null>(null);
const [dragOverField, setDragOverField] = const [dragOverField, setDragOverField] =
useState<RoleTextImportField | null>(null); useState<RoleTextImportField | null>(null);
const [pendingBudgetRows, setPendingBudgetRows] = useState<BudgetRow[]>( const [pendingBudgetRows, setPendingBudgetRows] = useState<BudgetRow[]>([]);
[]
);
const [attemptedBudgetsSave, setAttemptedBudgetsSave] = useState(false); const [attemptedBudgetsSave, setAttemptedBudgetsSave] = useState(false);
const budgetsQuery = useQuery({ const budgetsQuery = useQuery({
@@ -702,7 +700,6 @@ export function RoleForm({
</div> </div>
)} )}
{/* Inference Budget tab */}
<div className="space-y-4 mt-4"> <div className="space-y-4 mt-4">
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{t("accessRoleInferenceBudgetDescription")} {t("accessRoleInferenceBudgetDescription")}
@@ -711,8 +708,7 @@ export function RoleForm({
rows={pendingBudgetRows} rows={pendingBudgetRows}
onChange={setPendingBudgetRows} onChange={setPendingBudgetRows}
disabled={ disabled={
variant === "edit" && variant === "edit" && budgetsQuery.isLoading
budgetsQuery.isLoading
} }
attemptedSave={attemptedBudgetsSave} attemptedSave={attemptedBudgetsSave}
/> />