feat(quota): add 2-level database-backed resource quota system (#318)

* feat(quota): add database-backed resource quota system

* feat(webui): add resource quota management in team settings (#319)

* feat(webui): add resource quota settings in team management

* refactor(webui): update quotas list to full row layout and restrict skill/mcp to select list

* feat(quota): refactor quota system to 2-level rules and records

* fix(webui): fix overflow and scroll area in quota usage records dialog

* fix(webui): ensure quota records scroll area has explicit max height

* feat(webui): improve quota cards interaction and restrict editable fields in edit mode

* fix(quota): serialize initial records, validate merged updates, and reset on dimension changes (#320)

* feat(quota): replace network quota with agent tools quota (#321)

* feat(webui): show remaining time until next refresh in quota usage records

* fix(webui): rename bash quota resource to Agent Bash Calls

* refactor(quota): remove unused reserved field from quota records

* refactor(quota): remove quota rule cache (#322)
This commit is contained in:
Yiling-J
2026-08-17 20:24:05 +08:00
committed by GitHub
parent dd82daf65c
commit eed0264b9c
200 changed files with 13118 additions and 50 deletions
@@ -0,0 +1,852 @@
import React, { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Button } from '@/ui/components/ui/button'
import { Switch } from '@/ui/components/ui/switch'
import { Checkbox } from '@/ui/components/ui/checkbox'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import {
Cpu,
DollarSign,
Puzzle,
Server,
Terminal,
Wrench,
Loader2,
Trash2,
Users,
UserCheck,
User,
Clock,
Search,
ChevronDown,
} from 'lucide-react'
import { toast } from 'sonner'
import { m } from '@/ui/paraglide/messages.js'
import type {
QuotaRuleResponse,
QuotaScopeModeEnum,
QuotaResourceTypeEnum,
QuotaPeriodEnum,
QuotaRole,
} from '@shumai/dtos'
import { formatQuotaPeriod } from '@shumai/dtos'
interface QuotaRuleDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
teamId: string
rule?: QuotaRuleResponse | null
onSuccess?: () => void
}
const STANDARD_TOOLS = [
{ value: 'analyze_image', label: () => m.agent_tool_analyze_image_name() },
{ value: 'screenshot', label: () => m.agent_tool_screenshot_name() },
{ value: 'read_pdf_pages', label: () => m.agent_tool_read_pdf_pages_name() },
{ value: 'list_assets', label: () => m.agent_tool_list_assets_name() },
{ value: 'create_folder', label: () => m.agent_tool_create_folder_name() },
{ value: 'create_file', label: () => m.agent_tool_create_file_name() },
{ value: 'create_version', label: () => m.agent_tool_create_version_name() },
]
/* eslint-disable @typescript-eslint/naming-convention */
const RESOURCE_CONFIG = {
agent_total_tokens: {
label: () => m.quota_resource_agent_total_tokens(),
icon: Cpu,
unit: 'tokens',
defaultLimit: 100000,
},
agent_cost: {
label: () => m.quota_resource_agent_cost(),
icon: DollarSign,
unit: '$',
defaultLimit: 10,
},
agent_skill_call_count: {
label: () => m.quota_resource_agent_skill_call_count(),
icon: Puzzle,
unit: 'calls',
defaultLimit: 100,
},
agent_mcp_call_count: {
label: () => m.quota_resource_agent_mcp_call_count(),
icon: Server,
unit: 'calls',
defaultLimit: 100,
},
agent_bash_call_count: {
label: () => m.quota_resource_agent_bash_call_count(),
icon: Terminal,
unit: 'calls',
defaultLimit: 50,
},
agent_tool_call_count: {
label: () => m.quota_resource_agent_tool_call_count(),
icon: Wrench,
unit: 'calls',
defaultLimit: 100,
},
} as const
/* eslint-enable @typescript-eslint/naming-convention */
export const QuotaRuleDialog: React.FC<QuotaRuleDialogProps> = ({
open,
onOpenChange,
teamId,
rule,
onSuccess,
}) => {
const queryClient = useQueryClient()
const isEditing = !!rule
const [scopeMode, setScopeMode] = useState<QuotaScopeModeEnum>('each_member')
const [roleScope, setRoleScope] = useState<string>('team') // 'team' | 'owner' | 'editor' | 'reviewer'
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([])
const [resource, setResource] = useState<QuotaResourceTypeEnum>('agent_total_tokens')
const [skillId, setSkillId] = useState<string>('')
const [mcpServerId, setMcpServerId] = useState<string>('')
const [bashMatch, setBashMatch] = useState<string>('*')
const [toolName, setToolName] = useState<string>('analyze_image')
const [limit, setLimit] = useState<number>(100000)
const [period, setPeriod] = useState<QuotaPeriodEnum>('1day')
const [enabled, setEnabled] = useState<boolean>(true)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState<boolean>(false)
const [memberSearch, setMemberSearch] = useState<string>('')
// Fetch team members
const { data: members = [] } = useQuery({
queryKey: ['teams', teamId, 'members'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].members.$get({
param: { teamId },
query: {},
})
if (!res.ok) return []
return await res.json()
},
enabled: open,
})
// Fetch team skills when needed
const { data: skillsData } = useQuery({
queryKey: ['teams', teamId, 'skills'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].skills.$get({ param: { teamId } })
if (!res.ok) return { skills: [] }
return await res.json()
},
enabled: open && resource === 'agent_skill_call_count',
})
const skills = skillsData?.skills || []
// Fetch team MCP servers when needed
const { data: mcpData } = useQuery({
queryKey: ['teams', teamId, 'mcp', 'servers'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].mcp.servers.$get({ param: { teamId } })
if (!res.ok) return { servers: [] }
return await res.json()
},
enabled: open && resource === 'agent_mcp_call_count',
})
const mcpServers = mcpData?.servers || []
// Reset or populate form values on open/rule change
useEffect(() => {
if (rule) {
setScopeMode(rule.scopeMode)
setRoleScope(rule.role || 'team')
setSelectedUserIds(rule.userIds || [])
setResource(rule.resource)
const resData = (rule.resourceData as Record<string, unknown> | null) || {}
setSkillId(typeof resData.id === 'string' ? resData.id : '')
setMcpServerId(typeof resData.id === 'string' ? resData.id : '')
setBashMatch(typeof resData.match === 'string' ? resData.match : '*')
setToolName(
typeof resData.name === 'string'
? resData.name
: typeof resData.toolName === 'string'
? resData.toolName
: 'analyze_image',
)
setLimit(rule.limit)
setPeriod(formatQuotaPeriod(rule.period) as QuotaPeriodEnum)
setEnabled(rule.enabled)
} else {
setScopeMode('each_member')
setRoleScope('team')
setSelectedUserIds([])
setResource('agent_total_tokens')
setSkillId('')
setMcpServerId('')
setBashMatch('*')
setToolName('analyze_image')
setLimit(RESOURCE_CONFIG.agent_total_tokens.defaultLimit)
setPeriod('1day')
setEnabled(true)
}
}, [rule, open])
// Handle resource change limit defaults
const handleResourceChange = (newRes: QuotaResourceTypeEnum) => {
setResource(newRes)
if (!isEditing) {
setLimit(RESOURCE_CONFIG[newRes]?.defaultLimit || 100)
}
}
// Create mutation
const createMutation = useMutation({
mutationFn: async () => {
const resourceData: Record<string, unknown> = {}
if (resource === 'agent_skill_call_count') {
resourceData.id = skillId
} else if (resource === 'agent_mcp_call_count') {
resourceData.id = mcpServerId
} else if (resource === 'agent_bash_call_count') {
resourceData.match = bashMatch.trim() || '*'
} else if (resource === 'agent_tool_call_count') {
resourceData.name = toolName || 'analyze_image'
}
const res = await client.api.teams[':teamId'].quotas.$post({
param: { teamId },
json: {
scopeMode,
role:
scopeMode !== 'selected_members' && roleScope !== 'team'
? (roleScope as QuotaRole)
: null,
userIds: scopeMode === 'selected_members' ? selectedUserIds : null,
resource,
resourceData: Object.keys(resourceData).length > 0 ? resourceData : null,
limit: Number(limit),
period,
enabled,
},
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
throw new Error((err as any)?.message || m.failed_to_create_quota())
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
toast.success(m.quota_created_successfully())
onOpenChange(false)
onSuccess?.()
},
onError: (err) => {
console.error('CREATE MUTATION ERROR:', err)
toast.error(err instanceof Error ? err.message : m.failed_to_create_quota())
},
})
// Update mutation
const updateMutation = useMutation({
mutationFn: async () => {
if (!rule) return
const resourceData: Record<string, unknown> = {}
if (resource === 'agent_skill_call_count') {
resourceData.id = skillId
} else if (resource === 'agent_mcp_call_count') {
resourceData.id = mcpServerId
} else if (resource === 'agent_bash_call_count') {
resourceData.match = bashMatch.trim() || '*'
} else if (resource === 'agent_tool_call_count') {
resourceData.name = toolName || 'analyze_image'
}
const res = await client.api.teams[':teamId'].quotas[':id'].$put({
param: { teamId, id: rule.id },
json: {
scopeMode,
role:
scopeMode !== 'selected_members' && roleScope !== 'team'
? (roleScope as QuotaRole)
: null,
userIds: scopeMode === 'selected_members' ? selectedUserIds : null,
resource,
resourceData: Object.keys(resourceData).length > 0 ? resourceData : null,
limit: Number(limit),
period,
enabled,
},
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
throw new Error((err as any)?.message || m.failed_to_update_quota())
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
toast.success(m.quota_updated_successfully())
onOpenChange(false)
onSuccess?.()
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : m.failed_to_update_quota())
},
})
// Delete mutation
const deleteMutation = useMutation({
mutationFn: async () => {
if (!rule) return
const res = await client.api.teams[':teamId'].quotas[':id'].$delete({
param: { teamId, id: rule.id },
})
if (!res.ok) throw new Error(m.failed_to_delete_quota())
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
toast.success(m.quota_deleted_successfully())
setIsDeleteDialogOpen(false)
onOpenChange(false)
onSuccess?.()
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : m.failed_to_delete_quota())
},
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (scopeMode === 'selected_members' && selectedUserIds.length === 0) {
toast.error(m.select_user())
return
}
if (resource === 'agent_skill_call_count' && !skillId.trim()) {
toast.error(m.enter_skill_id())
return
}
if (resource === 'agent_mcp_call_count' && !mcpServerId.trim()) {
toast.error(m.enter_mcp_id())
return
}
if (limit <= 0) {
toast.error('Limit must be greater than 0')
return
}
if (isEditing) {
updateMutation.mutate()
} else {
createMutation.mutate()
}
}
const isPending = createMutation.isPending || updateMutation.isPending || deleteMutation.isPending
const filteredMembers = members.filter((member) => {
if (!memberSearch.trim()) return true
const q = memberSearch.toLowerCase()
return (
member.name.toLowerCase().includes(q) ||
(member.email && member.email.toLowerCase().includes(q))
)
})
const toggleUserSelection = (userId: string) => {
setSelectedUserIds((prev) =>
prev.includes(userId) ? prev.filter((id) => id !== userId) : [...prev, userId],
)
}
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[540px] max-h-[90vh] flex flex-col p-0 overflow-hidden">
<DialogHeader className="p-6 pb-4 border-b border-border/60 shrink-0">
<DialogTitle className="text-xl font-bold">
{isEditing ? m.edit_quota_rule() : m.create_quota_rule()}
</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground">
{isEditing ? m.edit_quota_rule_description() : m.create_quota_rule_description()}
</DialogDescription>
</DialogHeader>
<form
onSubmit={handleSubmit}
noValidate
className="flex-1 overflow-y-auto min-h-0 p-6 space-y-5"
>
{/* Step 1: Scope Mode Selector */}
<div className="space-y-2">
<Label className="text-sm font-semibold">{m.quota_scope_mode()}</Label>
<div className="grid grid-cols-3 gap-2">
<Button
type="button"
variant={scopeMode === 'each_member' ? 'default' : 'outline'}
size="sm"
disabled={isEditing || isPending}
onClick={() => setScopeMode('each_member')}
className="flex flex-col h-auto py-2.5 px-2 gap-1 items-center justify-center text-xs"
>
<User className="w-4 h-4" />
<span className="font-semibold">{m.quota_scope_mode_each_member()}</span>
</Button>
<Button
type="button"
variant={scopeMode === 'all_members' ? 'default' : 'outline'}
size="sm"
disabled={isEditing || isPending}
onClick={() => setScopeMode('all_members')}
className="flex flex-col h-auto py-2.5 px-2 gap-1 items-center justify-center text-xs"
>
<Users className="w-4 h-4" />
<span className="font-semibold">{m.quota_scope_mode_all_members()}</span>
</Button>
<Button
type="button"
variant={scopeMode === 'selected_members' ? 'default' : 'outline'}
size="sm"
disabled={isEditing || isPending}
onClick={() => setScopeMode('selected_members')}
className="flex flex-col h-auto py-2.5 px-2 gap-1 items-center justify-center text-xs"
>
<UserCheck className="w-4 h-4" />
<span className="font-semibold">{m.quota_scope_mode_selected_members()}</span>
</Button>
</div>
<p className="text-xs text-muted-foreground pt-0.5">
{scopeMode === 'each_member' && m.quota_scope_mode_each_member_desc()}
{scopeMode === 'all_members' && m.quota_scope_mode_all_members_desc()}
{scopeMode === 'selected_members' && m.quota_scope_mode_selected_members_desc()}
</p>
</div>
{/* Step 2: Target Scope or Multi-Select Users */}
{scopeMode !== 'selected_members' ? (
<div className="space-y-2">
<Label htmlFor="quota-role-scope" className="text-sm font-semibold">
{m.quota_scope()}
</Label>
<Select
value={roleScope}
onValueChange={setRoleScope}
disabled={isEditing || isPending}
>
<SelectTrigger id="quota-role-scope" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="team">{m.quota_scope_team()}</SelectItem>
<SelectItem value="owner">{m.quota_scope_role()}: Owner</SelectItem>
<SelectItem value="editor">{m.quota_scope_role()}: Editor</SelectItem>
<SelectItem value="reviewer">{m.quota_scope_role()}: Reviewer</SelectItem>
</SelectContent>
</Select>
</div>
) : (
<div className="space-y-2">
<Label className="text-sm font-semibold">{m.select_members()}</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
disabled={isPending}
className="w-full justify-between text-left font-normal h-10"
>
<span className="truncate">
{selectedUserIds.length === 0
? m.select_members()
: m.quota_selected_users_count({ count: selectedUserIds.length })}
</span>
<ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[320px] p-2" align="start">
<div className="space-y-2">
<div className="relative">
<Search className="w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder={m.quota_search_members()}
value={memberSearch}
onChange={(e) => setMemberSearch(e.target.value)}
className="h-8 pl-8 text-xs"
/>
</div>
<ScrollArea className="h-48">
<div className="space-y-1 pr-2">
{filteredMembers.map((member) => {
const isChecked = selectedUserIds.includes(member.id)
return (
<div
key={member.id}
onClick={() => toggleUserSelection(member.id)}
className="flex items-center gap-2 p-1.5 rounded-lg hover:bg-muted/60 cursor-pointer text-xs"
>
<Checkbox
checked={isChecked}
onCheckedChange={() => toggleUserSelection(member.id)}
/>
<Avatar className="w-5 h-5">
<AvatarImage src={member.image || undefined} />
<AvatarFallback className="text-[10px]">
{member.name?.[0]?.toUpperCase() || 'U'}
</AvatarFallback>
</Avatar>
<div className="truncate flex-1">
<span className="font-medium text-foreground block truncate">
{member.name}
</span>
{member.email && (
<span className="text-[10px] text-muted-foreground block truncate">
{member.email}
</span>
)}
</div>
</div>
)
})}
</div>
</ScrollArea>
</div>
</PopoverContent>
</Popover>
</div>
)}
{/* Resource Type */}
<div className="space-y-2">
<Label htmlFor="quota-resource" className="text-sm font-semibold">
{m.quota_resource()}
</Label>
<Select
value={resource}
onValueChange={(val) => handleResourceChange(val as QuotaResourceTypeEnum)}
disabled={isEditing || isPending}
>
<SelectTrigger id="quota-resource" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="agent_total_tokens">
<div className="flex items-center gap-2">
<Cpu className="w-4 h-4 text-primary" />
<span>{m.quota_resource_agent_total_tokens()}</span>
</div>
</SelectItem>
<SelectItem value="agent_cost">
<div className="flex items-center gap-2">
<DollarSign className="w-4 h-4 text-emerald-500" />
<span>{m.quota_resource_agent_cost()}</span>
</div>
</SelectItem>
<SelectItem value="agent_skill_call_count">
<div className="flex items-center gap-2">
<Puzzle className="w-4 h-4 text-amber-500" />
<span>{m.quota_resource_agent_skill_call_count()}</span>
</div>
</SelectItem>
<SelectItem value="agent_mcp_call_count">
<div className="flex items-center gap-2">
<Server className="w-4 h-4 text-blue-500" />
<span>{m.quota_resource_agent_mcp_call_count()}</span>
</div>
</SelectItem>
<SelectItem value="agent_bash_call_count">
<div className="flex items-center gap-2">
<Terminal className="w-4 h-4 text-purple-500" />
<span>{m.quota_resource_agent_bash_call_count()}</span>
</div>
</SelectItem>
<SelectItem value="agent_tool_call_count">
<div className="flex items-center gap-2">
<Wrench className="w-4 h-4 text-cyan-500" />
<span>{m.quota_resource_agent_tool_call_count()}</span>
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
{/* Resource Specific Fields */}
{resource === 'agent_skill_call_count' && (
<div className="space-y-2">
<Label htmlFor="quota-skill" className="text-sm font-semibold">
{m.select_skill()}
</Label>
{skills.length > 0 ? (
<Select
value={skillId}
onValueChange={setSkillId}
disabled={isEditing || isPending}
>
<SelectTrigger id="quota-skill" className="w-full">
<SelectValue placeholder={m.select_skill()} />
</SelectTrigger>
<SelectContent>
{skills.map((s: { id: string; name: string }) => (
<SelectItem key={s.id} value={s.id}>
{s.name} ({s.id})
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Input
id="quota-skill"
value={skillId}
onChange={(e) => setSkillId(e.target.value)}
placeholder={m.enter_skill_id()}
disabled={isEditing || isPending}
/>
)}
</div>
)}
{resource === 'agent_mcp_call_count' && (
<div className="space-y-2">
<Label htmlFor="quota-mcp" className="text-sm font-semibold">
{m.select_mcp_server()}
</Label>
{mcpServers.length > 0 ? (
<Select
value={mcpServerId}
onValueChange={setMcpServerId}
disabled={isEditing || isPending}
>
<SelectTrigger id="quota-mcp" className="w-full">
<SelectValue placeholder={m.select_mcp_server()} />
</SelectTrigger>
<SelectContent>
{mcpServers.map((s: { id: string; name: string }) => (
<SelectItem key={s.id} value={s.id}>
{s.name} ({s.id})
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Input
id="quota-mcp"
value={mcpServerId}
onChange={(e) => setMcpServerId(e.target.value)}
placeholder={m.enter_mcp_id()}
disabled={isEditing || isPending}
/>
)}
</div>
)}
{resource === 'agent_bash_call_count' && (
<div className="space-y-1.5">
<Label htmlFor="quota-bash" className="text-sm font-semibold">
{m.bash_command_pattern()}
</Label>
<Input
id="quota-bash"
value={bashMatch}
onChange={(e) => setBashMatch(e.target.value)}
placeholder={m.bash_command_pattern_placeholder()}
disabled={isPending}
/>
<p className="text-xs text-muted-foreground">{m.quota_bash_hint()}</p>
</div>
)}
{resource === 'agent_tool_call_count' && (
<div className="space-y-2">
<Label htmlFor="quota-tool" className="text-sm font-semibold">
{m.select_tool()}
</Label>
<Select
value={toolName}
onValueChange={setToolName}
disabled={isEditing || isPending}
>
<SelectTrigger id="quota-tool" className="w-full">
<SelectValue placeholder={m.select_tool()} />
</SelectTrigger>
<SelectContent>
{STANDARD_TOOLS.map((t) => (
<SelectItem key={t.value} value={t.value}>
{t.label()}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{m.quota_tool_hint()}</p>
</div>
)}
{/* Limit and Period Row */}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="quota-limit" className="text-sm font-semibold">
{m.quota_limit()} ({RESOURCE_CONFIG[resource]?.unit || ''})
</Label>
<Input
id="quota-limit"
type="number"
min="0.01"
step={resource === 'agent_cost' ? '0.01' : '1'}
value={limit}
onChange={(e) => setLimit(Number(e.target.value))}
placeholder={m.quota_limit_placeholder()}
disabled={isPending}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="quota-period" className="text-sm font-semibold">
{m.quota_period()}
</Label>
<Select
value={period}
onValueChange={(val) => setPeriod(val as QuotaPeriodEnum)}
disabled={isPending}
>
<SelectTrigger id="quota-period" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1hour">
<div className="flex items-center gap-2">
<Clock className="w-3.5 h-3.5 text-muted-foreground" />
<span>{m.quota_period_1hour()}</span>
</div>
</SelectItem>
<SelectItem value="5hour">
<div className="flex items-center gap-2">
<Clock className="w-3.5 h-3.5 text-muted-foreground" />
<span>{m.quota_period_5hour()}</span>
</div>
</SelectItem>
<SelectItem value="1day">
<div className="flex items-center gap-2">
<Clock className="w-3.5 h-3.5 text-muted-foreground" />
<span>{m.quota_period_1day()}</span>
</div>
</SelectItem>
<SelectItem value="7day">
<div className="flex items-center gap-2">
<Clock className="w-3.5 h-3.5 text-muted-foreground" />
<span>{m.quota_period_7day()}</span>
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Enabled Switch */}
<div className="flex items-center justify-between p-3 rounded-lg border bg-muted/20">
<div className="space-y-0.5">
<Label htmlFor="quota-enabled" className="text-sm font-medium cursor-pointer">
{enabled ? m.quota_enabled() : m.quota_disabled()}
</Label>
<p className="text-xs text-muted-foreground">
{enabled
? 'Active and enforcing limits'
: 'Inactive, requests will bypass this quota'}
</p>
</div>
<Switch
id="quota-enabled"
checked={enabled}
onCheckedChange={setEnabled}
disabled={isPending}
/>
</div>
<DialogFooter className="pt-4 flex items-center justify-between gap-2 sm:justify-between border-t border-border/60">
{isEditing ? (
<Button
type="button"
variant="destructive"
size="sm"
onClick={() => setIsDeleteDialogOpen(true)}
disabled={isPending}
className="gap-1.5"
>
<Trash2 className="w-4 h-4" />
<span>{m.delete_quota()}</span>
</Button>
) : (
<div />
)}
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isPending}
>
{m.cancel()}
</Button>
<Button type="submit" disabled={isPending} className="gap-2">
{isPending && <Loader2 className="w-4 h-4 animate-spin" />}
{isEditing ? m.save() : m.create()}
</Button>
</div>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
{/* Delete Confirmation Alert Dialog */}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.delete_quota()}</AlertDialogTitle>
<AlertDialogDescription>{m.delete_quota_confirm()}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isPending}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault()
deleteMutation.mutate()
}}
disabled={isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isPending && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.delete()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
@@ -0,0 +1,280 @@
import React, { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { Badge } from '@/ui/components/ui/badge'
import { Progress } from '@/ui/components/ui/progress'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import {
Cpu,
DollarSign,
Puzzle,
Server,
Terminal,
Wrench,
Loader2,
Users,
Search,
CheckCircle2,
Clock,
Activity,
} from 'lucide-react'
import { m } from '@/ui/paraglide/messages.js'
import { formatRemainingTime } from '@/ui/lib/time'
import type { QuotaRuleResponse, QuotaResourceTypeEnum, QuotaRecordResponse } from '@shumai/dtos'
import { formatQuotaPeriod } from '@shumai/dtos'
interface QuotaUsageRecordsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
teamId: string
rule: QuotaRuleResponse
}
/* eslint-disable @typescript-eslint/naming-convention */
const RESOURCE_META: Record<
QuotaResourceTypeEnum,
{ label: () => string; icon: React.ElementType; unit: string }
> = {
agent_total_tokens: {
label: () => m.quota_resource_agent_total_tokens(),
icon: Cpu,
unit: 'tokens',
},
agent_cost: {
label: () => m.quota_resource_agent_cost(),
icon: DollarSign,
unit: '$',
},
agent_skill_call_count: {
label: () => m.quota_resource_agent_skill_call_count(),
icon: Puzzle,
unit: 'calls',
},
agent_mcp_call_count: {
label: () => m.quota_resource_agent_mcp_call_count(),
icon: Server,
unit: 'calls',
},
agent_bash_call_count: {
label: () => m.quota_resource_agent_bash_call_count(),
icon: Terminal,
unit: 'calls',
},
agent_tool_call_count: {
label: () => m.quota_resource_agent_tool_call_count(),
icon: Wrench,
unit: 'calls',
},
}
/* eslint-enable @typescript-eslint/naming-convention */
function formatResourceValue(resource: QuotaResourceTypeEnum, val: number): string {
if (resource === 'agent_cost') {
return `$${val.toFixed(2)}`
}
return val.toLocaleString()
}
function getPeriodLabel(period: string): string {
const norm = formatQuotaPeriod(period)
switch (norm) {
case '1hour':
return m.quota_period_1hour()
case '5hour':
return m.quota_period_5hour()
case '1day':
return m.quota_period_1day()
case '7day':
return m.quota_period_7day()
default:
return norm
}
}
export const QuotaUsageRecordsDialog: React.FC<QuotaUsageRecordsDialogProps> = ({
open,
onOpenChange,
teamId,
rule,
}) => {
const [search, setSearch] = useState('')
const { data, isLoading } = useQuery({
queryKey: ['teams', teamId, 'quotas', rule.id, 'records'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].quotas[':id'].records.$get({
param: { teamId, id: rule.id },
})
if (!res.ok) return { records: [], total: 0 }
return await res.json()
},
enabled: open,
refetchInterval: 10000,
})
const records: QuotaRecordResponse[] = data?.records || []
const meta = RESOURCE_META[rule.resource]
const Icon = meta?.icon || Activity
const filteredRecords = records.filter((r) => {
if (!search.trim()) return true
const q = search.toLowerCase()
if (r.user?.name.toLowerCase().includes(q)) return true
if (r.user?.email.toLowerCase().includes(q)) return true
return false
})
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[620px] p-0 gap-0 overflow-hidden">
<DialogHeader className="p-6 pb-4 border-b border-border/60">
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-primary/10 text-primary shrink-0">
<Icon className="w-5 h-5" />
</div>
<div>
<DialogTitle className="text-lg font-bold flex items-center gap-2">
<span>{m.quota_usage_records()}</span>
<Badge variant="outline" className="text-xs font-normal">
{meta?.label ? meta.label() : rule.resource} -{' '}
{formatResourceValue(rule.resource, rule.limit)} {meta?.unit} /{' '}
{getPeriodLabel(rule.period)}
</Badge>
</DialogTitle>
<DialogDescription className="text-xs text-muted-foreground mt-0.5">
{m.quota_usage_records_description()}
</DialogDescription>
</div>
</div>
</DialogHeader>
{rule.scopeMode !== 'all_members' && records.length > 3 && (
<div className="px-6 pt-4 pb-2">
<div className="relative">
<Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={m.quota_search_members()}
className="pl-9 h-9 text-sm"
/>
</div>
</div>
)}
<ScrollArea className="max-h-[60vh] p-6 pt-3">
{isLoading ? (
<div className="flex justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
</div>
) : filteredRecords.length === 0 ? (
<div className="text-center py-10 text-sm text-muted-foreground">
{records.length === 0 ? m.no_quotas_title() : 'No matching records found'}
</div>
) : (
<div className="space-y-3">
{filteredRecords.map((record, index) => {
const percent = record.percent
const isOverLimit = percent >= 100
const isSharedPool = rule.scopeMode === 'all_members'
return (
<div
key={record.id || record.userId || `record-${index}`}
className="p-4 rounded-xl border border-border/70 bg-card text-card-foreground shadow-2xs space-y-3"
>
{/* Top Row: User / Pool Info & Status Badge */}
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-3 min-w-0">
{isSharedPool ? (
<div className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Users className="w-5 h-5" />
</div>
) : (
<Avatar className="w-9 h-9 border border-border/50 shrink-0">
<AvatarImage src={record.user?.image || undefined} />
<AvatarFallback className="text-xs font-semibold">
{record.user?.name?.[0]?.toUpperCase() || 'U'}
</AvatarFallback>
</Avatar>
)}
<div className="min-w-0">
<div className="font-semibold text-sm text-foreground truncate">
{isSharedPool
? rule.role
? `${m.quota_role_shared_pool()}: ${rule.role}`
: m.quota_team_shared_pool()
: record.user?.name || record.userId}
</div>
{!isSharedPool && record.user?.email && (
<div className="text-xs text-muted-foreground truncate">
{record.user.email}
</div>
)}
</div>
</div>
{/* Status Badge */}
<div className="shrink-0">
{record.isWindowActive && record.periodEnd ? (
<Badge
variant="outline"
className="gap-1 text-xs text-primary border-primary/30 bg-primary/5"
>
<Clock className="w-3 h-3" />
<span>
{m.quota_refreshes_in({
time: formatRemainingTime(record.periodEnd),
})}
</span>
</Badge>
) : (
<Badge
variant="secondary"
className="gap-1 text-xs text-muted-foreground bg-muted"
>
<CheckCircle2 className="w-3 h-3 text-emerald-500" />
<span>{m.quota_available()}</span>
</Badge>
)}
</div>
</div>
{/* Progress Bar & Details */}
<div className="space-y-1.5 pt-1">
<Progress value={Math.min(100, Math.max(0, percent))} className="h-2" />
<div className="flex items-center justify-between text-xs font-medium">
<span
className={isOverLimit ? 'text-destructive font-bold' : 'text-foreground'}
>
{formatResourceValue(rule.resource, record.consumed)} /{' '}
{formatResourceValue(rule.resource, rule.limit)} {meta?.unit}
</span>
<span
className={
isOverLimit ? 'text-destructive font-bold' : 'text-muted-foreground'
}
>
{percent}%
</span>
</div>
</div>
</div>
)
})}
</div>
)}
</ScrollArea>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,409 @@
import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Button } from '@/ui/components/ui/button'
import { Badge } from '@/ui/components/ui/badge'
import { Switch } from '@/ui/components/ui/switch'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import {
Gauge,
Plus,
Loader2,
MoreVertical,
Trash2,
Cpu,
DollarSign,
Puzzle,
Server,
Terminal,
Wrench,
Users,
UserCheck,
User,
Clock,
Eye,
} from 'lucide-react'
import { toast } from 'sonner'
import { m } from '@/ui/paraglide/messages.js'
import type { QuotaRuleResponse, QuotaResourceTypeEnum } from '@shumai/dtos'
import { formatQuotaPeriod } from '@shumai/dtos'
import { QuotaRuleDialog } from './QuotaRuleDialog'
import { QuotaUsageRecordsDialog } from './QuotaUsageRecordsDialog'
interface QuotasSettingsProps {
teamId: string
}
/* eslint-disable @typescript-eslint/naming-convention */
const RESOURCE_META: Record<
QuotaResourceTypeEnum,
{ label: () => string; icon: React.ElementType; unit: string }
> = {
agent_total_tokens: {
label: () => m.quota_resource_agent_total_tokens(),
icon: Cpu,
unit: 'tokens',
},
agent_cost: {
label: () => m.quota_resource_agent_cost(),
icon: DollarSign,
unit: '$',
},
agent_skill_call_count: {
label: () => m.quota_resource_agent_skill_call_count(),
icon: Puzzle,
unit: 'calls',
},
agent_mcp_call_count: {
label: () => m.quota_resource_agent_mcp_call_count(),
icon: Server,
unit: 'calls',
},
agent_bash_call_count: {
label: () => m.quota_resource_agent_bash_call_count(),
icon: Terminal,
unit: 'calls',
},
agent_tool_call_count: {
label: () => m.quota_resource_agent_tool_call_count(),
icon: Wrench,
unit: 'calls',
},
}
/* eslint-enable @typescript-eslint/naming-convention */
function getPeriodLabel(period: string): string {
const norm = formatQuotaPeriod(period)
switch (norm) {
case '1hour':
return m.quota_period_1hour()
case '5hour':
return m.quota_period_5hour()
case '1day':
return m.quota_period_1day()
case '7day':
return m.quota_period_7day()
default:
return norm
}
}
function formatResourceValue(resource: QuotaResourceTypeEnum, val: number): string {
if (resource === 'agent_cost') {
return `$${val.toFixed(2)}`
}
return val.toLocaleString()
}
export const QuotasSettings: React.FC<QuotasSettingsProps> = ({ teamId }) => {
const queryClient = useQueryClient()
const [isCreateOpen, setIsCreateOpen] = useState(false)
const [selectedRule, setSelectedRule] = useState<QuotaRuleResponse | null>(null)
const [viewingUsageRule, setViewingUsageRule] = useState<QuotaRuleResponse | null>(null)
const [deletingRule, setDeletingRule] = useState<QuotaRuleResponse | null>(null)
// Fetch quota rules
const { data, isLoading } = useQuery({
queryKey: ['teams', teamId, 'quotas'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].quotas.$get({ param: { teamId } })
if (!res.ok) throw new Error(m.failed_load_settings())
return await res.json()
},
})
// Quick toggle enabled mutation
const toggleMutation = useMutation({
mutationFn: async ({ id, enabled }: { id: string; enabled: boolean }) => {
const res = await client.api.teams[':teamId'].quotas[':id'].$put({
param: { teamId, id },
json: { enabled },
})
if (!res.ok) throw new Error(m.failed_to_update_quota())
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
toast.success(m.quota_status_updated())
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : m.failed_to_update_quota())
},
})
// Delete rule mutation
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await client.api.teams[':teamId'].quotas[':id'].$delete({
param: { teamId, id },
})
if (!res.ok) throw new Error(m.failed_to_delete_quota())
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
toast.success(m.quota_deleted_successfully())
setDeletingRule(null)
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : m.failed_to_delete_quota())
},
})
const rules: QuotaRuleResponse[] = data?.rules || []
return (
<ScrollArea className="h-full">
<div className="space-y-6 pr-4 pb-10">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-6">
<div className="flex items-center gap-3">
<div className="p-2 bg-primary/10 text-primary rounded-lg">
<Gauge className="w-6 h-6" />
</div>
<div>
<CardTitle className="text-xl font-bold">{m.resource_quotas()}</CardTitle>
<CardDescription>{m.resource_quotas_description()}</CardDescription>
</div>
</div>
<Button onClick={() => setIsCreateOpen(true)} className="gap-2">
<Plus className="w-4 h-4" /> {m.add_quota()}
</Button>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
</div>
) : rules.length === 0 ? (
<div className="text-center py-12 border-2 border-dashed border-border rounded-xl">
<div className="mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center mb-4 text-muted-foreground">
<Gauge className="w-6 h-6" />
</div>
<h3 className="text-base font-semibold text-foreground mb-1">
{m.no_quotas_title()}
</h3>
<p className="text-sm text-muted-foreground max-w-md mx-auto mb-6">
{m.no_quotas_description()}
</p>
<Button onClick={() => setIsCreateOpen(true)} className="gap-2">
<Plus className="w-4 h-4" /> {m.add_quota()}
</Button>
</div>
) : (
<div className="flex flex-col gap-4">
{rules.map((rule) => {
const meta = RESOURCE_META[rule.resource]
const resData = (rule.resourceData as Record<string, unknown> | null) || {}
return (
<div
key={rule.id}
onClick={() => setSelectedRule(rule)}
className={`group relative flex flex-col justify-between p-5 rounded-xl border bg-card text-card-foreground shadow-2xs transition-all hover:border-primary/40 hover:shadow-xs cursor-pointer ${
!rule.enabled ? 'opacity-60 bg-muted/20' : ''
}`}
>
{/* Top Row: Resource, Details, Switch, Actions */}
<div className="space-y-3">
<div className="flex items-start justify-between gap-2">
<div>
<div className="font-semibold text-base text-foreground group-hover:text-primary transition-colors flex items-center gap-2">
<span>{meta?.label ? meta.label() : rule.resource}</span>
</div>
{/* Subtitle / target details */}
<div className="text-xs text-muted-foreground line-clamp-1">
{rule.resource === 'agent_skill_call_count' && (
<span>Skill: {String(resData.id || '')}</span>
)}
{rule.resource === 'agent_mcp_call_count' && (
<span>Server: {String(resData.id || '')}</span>
)}
{rule.resource === 'agent_bash_call_count' && (
<span>Match: {String(resData.match || '*')}</span>
)}
{rule.resource === 'agent_tool_call_count' && (
<span>Tool: {String(resData.name || resData.toolName || '*')}</span>
)}
</div>
</div>
{/* Quick Switch & Card Menu */}
<div
className="flex items-center gap-2"
onClick={(e) => e.stopPropagation()}
>
<Switch
checked={rule.enabled}
onCheckedChange={(checked) =>
toggleMutation.mutate({ id: rule.id, enabled: checked })
}
disabled={toggleMutation.isPending}
/>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
aria-label="Quota actions"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
>
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setDeletingRule(rule)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="w-4 h-4 mr-2" />
{m.delete()}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Badges Row & View Usage Action */}
<div className="flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-border/50">
<div className="flex flex-wrap items-center gap-1.5">
{/* Scope Mode & Role badge */}
{rule.scopeMode === 'all_members' && (
<Badge variant="secondary" className="gap-1 text-xs">
<Users className="w-3 h-3" />
<span>
{m.quota_scope_mode_all_members()}
{rule.role ? ` (${rule.role})` : ` (${m.quota_scope_team()})`}
</span>
</Badge>
)}
{rule.scopeMode === 'each_member' && (
<Badge variant="secondary" className="gap-1 text-xs">
<User className="w-3 h-3" />
<span>
{m.quota_scope_mode_each_member()}
{rule.role ? ` (${rule.role})` : ` (${m.quota_scope_team()})`}
</span>
</Badge>
)}
{rule.scopeMode === 'selected_members' && (
<Badge variant="secondary" className="gap-1 text-xs">
<UserCheck className="w-3 h-3" />
<span>
{m.quota_scope_mode_selected_members()} (
{rule.userIds?.length || 0})
</span>
</Badge>
)}
{/* Limit & Period badge */}
<Badge variant="outline" className="gap-1 text-xs">
<Clock className="w-3 h-3" />
<span>
{formatResourceValue(rule.resource, rule.limit)} {meta?.unit} /{' '}
{getPeriodLabel(rule.period)}
</span>
</Badge>
</div>
{/* View Usage Button */}
<Button
variant="outline"
size="sm"
onClick={(e) => {
e.stopPropagation()
setViewingUsageRule(rule)
}}
className="gap-1.5 text-xs h-7 px-2.5"
>
<Eye className="w-3.5 h-3.5 text-primary" />
<span>{m.quota_view_usage()}</span>
</Button>
</div>
</div>
</div>
)
})}
</div>
)}
</CardContent>
</Card>
</div>
{/* Create / Edit Rule Dialog */}
{(isCreateOpen || !!selectedRule) && (
<QuotaRuleDialog
open={isCreateOpen || !!selectedRule}
onOpenChange={(open) => {
if (!open) {
setIsCreateOpen(false)
setSelectedRule(null)
}
}}
teamId={teamId}
rule={selectedRule}
/>
)}
{/* View Usage Records Dialog */}
{!!viewingUsageRule && (
<QuotaUsageRecordsDialog
open={!!viewingUsageRule}
onOpenChange={(open) => {
if (!open) setViewingUsageRule(null)
}}
teamId={teamId}
rule={viewingUsageRule}
/>
)}
{/* Delete Confirmation Alert Dialog */}
<AlertDialog
open={!!deletingRule}
onOpenChange={(open) => {
if (!open) setDeletingRule(null)
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.delete_quota()}</AlertDialogTitle>
<AlertDialogDescription>{m.delete_quota_confirm()}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteMutation.isPending}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault()
if (deletingRule) {
deleteMutation.mutate(deletingRule.id)
}
}}
disabled={deleteMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.delete()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</ScrollArea>
)
}