feat(quota): move usage monitoring to team dashboard (#327)

This commit is contained in:
Yiling-J
2026-08-18 15:57:36 +08:00
committed by GitHub
parent 4d100bf542
commit ffef67be8f
47 changed files with 1578 additions and 522 deletions
+1 -1
View File
@@ -63,7 +63,7 @@ apps/web/e2e/
| Owner invites a member via invite link and the invitee joins | `tests/team/invite-member.spec.ts` |
| Owner removes a member via the members dialog; the membership is deleted from the DB | `tests/team/remove-member.spec.ts` |
| Owner changes a team member role in the members dialog and permissions update | `tests/team/change-member-role.spec.ts` |
| Owner manages resource quotas in settings | `tests/team/quotas-settings.spec.ts` |
| Owner manages resource quotas in settings and resets usage from the dashboard | `tests/team/quotas-settings.spec.ts` |
### project
| Test | File |
+42 -11
View File
@@ -1,7 +1,10 @@
import { expect, test } from '../../fixtures'
test('owner manages resource quotas in settings', async ({ owner, prisma }) => {
const { page, teamId } = owner
test('owner manages resource quotas in settings and resets usage from the dashboard', async ({
owner,
prisma,
}) => {
const { page, teamId, email } = owner
// 1. Navigate to team settings
await page.goto(`/teams/${teamId}/settings`)
@@ -35,14 +38,8 @@ test('owner manages resource quotas in settings', async ({ owner, prisma }) => {
expect(createdRule).not.toBeNull()
expect(createdRule?.enabled).toBe(true)
// 7. Click View Usage button to open usage records dialog
await page.getByRole('button', { name: /View Usage|查看使用量/i }).click()
await expect(page.getByRole('heading', { name: /Usage Records|使用记录/i })).toBeVisible()
await expect(page.getByText(/Quota available|配额可用/i)).toBeVisible()
// Close dialog via Close button
await page.getByRole('button', { name: /Close|关闭/i }).click()
await expect(page.getByRole('heading', { name: /Usage Records|使用记录/i })).not.toBeVisible()
// 7. Usage is now monitored from the dashboard, not the settings rule card.
await expect(page.getByRole('button', { name: /View Usage|查看使用量/i })).not.toBeVisible()
// 8. Toggle quota rule switch
await page.getByRole('switch').click()
@@ -73,7 +70,41 @@ test('owner manages resource quotas in settings', async ({ owner, prisma }) => {
})
expect(updatedRule?.limit).toBe(75000)
// 11. Delete quota rule
// 11. Verify quota usage and reset it from the dashboard
const ownerUser = await prisma.user.findUnique({ where: { email } })
expect(ownerUser).not.toBeNull()
await prisma.quotaRecord.create({
data: {
ruleId: createdRule?.id as string,
teamId,
userId: ownerUser?.id,
periodStart: new Date(),
periodEnd: new Date(Date.now() + 24 * 60 * 60 * 1000),
consumed: 100,
},
})
await page.goto(`/teams/${teamId}/dashboard`)
await page.getByRole('button', { name: /Quotas|配额/i }).click()
await expect(
page.getByText(/Monitor live quota usage|在仪表盘中监控实时配额使用情况/),
).toBeVisible()
const quotaRuleButton = page.getByRole('button', { name: /Expand quota rule|展开配额规则/i })
await quotaRuleButton.click()
await expect(page.getByText(/^100 \/ 75,000 tokens$|^100 \/ 75000 tokens$/i)).toBeVisible()
await page.getByRole('button', { name: /Reset Usage|重置使用量/i }).click()
await expect(page.getByRole('alertdialog')).toBeVisible()
await page.getByRole('button', { name: /Confirm|确认/i }).click()
await expect(page.getByText(/^0 \/ 75,000 tokens$|^0 \/ 75000 tokens$/i)).toBeVisible()
const resetRecord = await prisma.quotaRecord.findFirst({
where: { ruleId: createdRule?.id, userId: ownerUser?.id },
})
expect(resetRecord?.consumed).toBe(0)
// 12. Delete quota rule from settings
await page.goto(`/teams/${teamId}/settings`)
await page.getByRole('button', { name: /Quotas|配额/i }).click()
await page.getByRole('button', { name: 'Quota actions' }).first().click()
await page.getByRole('menuitem', { name: /Delete|删除/i }).click()
await page
+49
View File
@@ -0,0 +1,49 @@
# Code Quality Review: Quota Usage Dashboard
## Context
The change moves quota usage monitoring from the settings rule-card dialog to an owner-only dashboard section, adds collapsible rule/record display, and adds an audited manual record reset operation.
## Review
### Correctness
- The reset service validates team ownership, scope mode, membership, role filters, and selected-member membership.
- Reset and first-use record creation are serialized with a quota-rule row lock.
- Reset starts a new window at the current time and clears consumption.
- API and service tests cover shared records, member records, invalid targets, cross-team access, request validation, and audit logging.
- The application E2E test covers the settings/dashboard flow and verifies the persisted reset.
### Readability and architecture
- Business logic remains in `QuotaService`; the API only validates, authorizes, invokes the service, and maps the audit action.
- The dashboard owns usage presentation, while quota formatting metadata is shared between dashboard and settings.
- The removed usage dialog and obsolete translation messages are not referenced after the refactor.
### Security
- The reset endpoint retains owner-level team authorization.
- Request input is validated with Zod.
- SQL uses Prisma tagged-template parameters and does not interpolate raw user input.
### Performance
- Usage records are queried only after a rule is expanded.
- Expanded rules refresh every ten seconds, matching the previous usage dialog behavior.
- Quota rules retain the existing bounded list endpoint and descending ID ordering.
## Verification
- `bun run lint` passed.
- `bun run format` passed.
- `bun run typecheck` passed.
- `bun run test` passed: 124 files, 1190 tests.
- Quota API/core tests passed: 2 files, 30 tests.
- Quota application E2E passed.
- WebUI harness E2E passed: 9 tests.
- Workflow E2E passed: 14 files, 58 tests.
- `git diff --check` passed.
## Verdict
Approve. No critical or required findings remain.
+38 -12
View File
@@ -1,6 +1,6 @@
---
title: Resource Quotas
description: Control and monitor AI token usage, costs, shell executions, and tool call quotas for your team.
description: Configure team resource quotas, monitor live usage, and reset quota windows from the dashboard.
---
AI workflows and media processing tools can consume significant compute and API credits. Shumai provides a **Resource Quotas** system that allows Team Owners to set granular rate limits, govern budgets, and monitor real-time usage across team members and roles.
@@ -11,7 +11,12 @@ AI workflows and media processing tools can consume significant compute and API
Resource Quotas allow you to define maximum usage limits across specific time windows (e.g., hourly, daily, or weekly). When a member or team reaches their assigned quota, further actions for that resource are safely blocked until the quota period resets.
To manage quotas, open **Team Settings** from your team dashboard and navigate to the **Quotas** tab.
Quota configuration and usage monitoring are separate parts of the team experience:
- To create and manage quota rules, open **Team Settings** and navigate to the **Quotas** tab.
- To monitor live usage, open the **Team Dashboard** and select **Quotas** under the **TEAM** section.
The quota dashboard is available to Team Owners.
---
@@ -77,19 +82,40 @@ Shumai tracks usage windows automatically. When a period window expires, the sys
## Monitoring Live Usage
Team Owners can inspect live consumption at any time:
Team Owners can inspect live consumption from the team dashboard:
1. In the **Quotas** settings tab, click **View Usage** on any quota rule card.
2. The **Usage Records** modal displays:
- **Consumption Status**: Progress bar showing consumed units vs. total limit.
- **Remaining Allowance**: Percentage and numerical amount remaining.
- **Refresh Countdown**: Exact remaining time until the active window resets (e.g., _"Refreshes in 45m"_).
- **Member Search**: Quickly filter through members to view individual usage.
1. Open the **Team Dashboard**.
2. Select **Quotas** under the **TEAM** section.
3. Quota rules are shown as first-level collapsible entries.
4. Expand a rule to view its usage records.
Each usage record displays:
- **Consumption Status**: Progress bar showing consumed units versus the total limit.
- **Remaining Allowance**: Percentage and numerical amount remaining.
- **Refresh Countdown**: Remaining time until the active window resets (e.g., _"Refreshes in 45m"_).
- **Target**: The team shared pool, role pool, or individual member associated with the record.
- **Member Search**: For member-scoped rules, search the usage records by member name or email.
Usage records are loaded when a rule is expanded and refresh automatically while the rule is open.
### Manually Resetting a Usage Record
Each usage record includes a **Reset Usage** action. After confirming the action:
- Consumption is set to zero.
- The quota period starts immediately.
- The period ends after the configured quota duration.
- For example, resetting a one-day quota at 10:00 starts a new window from 10:00 until 10:00 the following day.
A reset can also initialize a zero-consumption record for a member or shared pool that has not received usage yet. Resets are recorded in the team audit log.
---
## Managing Quota Rules
- **Enable / Disable**: Toggle the switch on any quota card to temporarily pause or resume enforcement without deleting the rule.
- **Edit Rules**: Click any quota card to update limits, change reset periods, or adjust member selections.
- **Delete Rules**: Open the card action menu (`⋮`) and select **Delete** to remove the quota rule.
- **Enable / Disable**: Toggle the switch on any quota card in Team Settings to temporarily pause or resume enforcement without deleting the rule.
- **Edit Rules**: Click any quota card in Team Settings to update limits, change reset periods, or adjust member selections.
- **Delete Rules**: Open the card action menu (`⋮`) in Team Settings and select **Delete** to remove the quota rule.
Quota usage is monitored and reset from the Team Dashboard rather than from the settings rule cards.
+53
View File
@@ -19,6 +19,7 @@ vi.mock('@shumai/core/src/quota/quota-service', () => ({
createRule: vi.fn(),
getRule: vi.fn(),
listRuleRecords: vi.fn(),
resetRecord: vi.fn(),
updateRule: vi.fn(),
deleteRule: vi.fn(),
},
@@ -198,6 +199,58 @@ describe('Quota API', () => {
})
})
describe('POST /teams/:teamId/quotas/:id/records/reset', () => {
test('Rejects a reset request without a userId', async () => {
const res = await app.request('/teams/team1/quotas/rule1/records/reset', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer test',
},
body: JSON.stringify({}),
})
expect(res.status).toBe(400)
expect(quotaService.resetRecord).not.toHaveBeenCalled()
})
test('Success resetting a quota record with audit log', async () => {
const mockRecord = {
id: 'record1',
ruleId: 'rule1',
teamId: 'team1',
userId: 'user2',
user: null,
periodStart: new Date().toISOString(),
periodEnd: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
consumed: 0,
remaining: 100,
percent: 0,
isWindowActive: true,
}
vi.spyOn(quotaService, 'resetRecord').mockResolvedValue(mockRecord)
const res = await app.request('/teams/team1/quotas/rule1/records/reset', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer test',
},
body: JSON.stringify({ userId: 'user2' }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual(mockRecord)
expect(quotaService.resetRecord).toHaveBeenCalledWith('team1', 'rule1', 'user2')
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.quota_record_reset,
teamId: 'team1',
userId: 'user1',
itemId: 'record1',
})
})
})
describe('PUT /teams/:teamId/quotas/:id', () => {
test('Success updating rule with audit log', async () => {
const updatedRule = {
+27
View File
@@ -4,6 +4,7 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
import { quotaService } from '@shumai/core/src/quota/quota-service'
import {
createQuotaRuleRequestSchema,
resetQuotaRecordRequestSchema,
updateQuotaRuleRequestSchema,
AuditAction,
} from '@shumai/dtos'
@@ -78,6 +79,32 @@ const route = new Hono<{ Variables: { user: User } }>()
const data = await quotaService.listRuleRecords(teamId, id)
return c.json(data)
})
.post(
'/teams/:teamId/quotas/:id/records/reset',
zValidator('json', resetQuotaRecordRequestSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const id = c.req.param('id')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const record = await quotaService.resetRecord(teamId, id, req.userId)
await auditLogService.logAction({
action: AuditAction.quota_record_reset,
teamId,
userId: user?.id,
itemId: record.id ?? id,
})
return c.json(record)
},
)
.put('/teams/:teamId/quotas/:id', zValidator('json', updateQuotaRuleRequestSchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
@@ -554,6 +554,126 @@ describe('QuotaService', () => {
expect(activeRecords.records[0].isWindowActive).toBe(true)
})
it('resets a shared quota record and starts a fresh window', async () => {
const team = await prisma.team.create({
data: { name: 'Reset Shared Quota Team' },
})
const rule = await quotaService.createRule(team.id, {
scopeMode: 'all_members',
resource: 'agent_total_tokens',
limit: 1000,
period: '1hour',
})
await quotaService.consumeQuota({ teamId: team.id, resource: 'agent_total_tokens' }, 500)
const beforeReset = await prisma.quotaRecord.findFirst({ where: { ruleId: rule.id } })
expect(beforeReset?.consumed).toBe(500)
const reset = await quotaService.resetRecord(team.id, rule.id, null)
expect(reset.userId).toBeNull()
expect(reset.consumed).toBe(0)
expect(reset.remaining).toBe(1000)
expect(reset.percent).toBe(0)
expect(reset.isWindowActive).toBe(true)
expect(reset.periodStart).toBeDefined()
expect(reset.periodEnd).toBeDefined()
const afterReset = await prisma.quotaRecord.findFirst({ where: { ruleId: rule.id } })
expect(afterReset?.consumed).toBe(0)
expect(afterReset?.periodStart?.getTime()).toBeGreaterThanOrEqual(
beforeReset?.periodStart?.getTime() ?? 0,
)
})
it('creates and resets a member quota record before any usage exists', async () => {
const team = await prisma.team.create({
data: { name: 'Reset Member Quota Team' },
})
const user = await prisma.user.create({
data: { name: 'Reset Member', email: 'reset-member@example.com', password: 'pw' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'editor' },
})
const rule = await quotaService.createRule(team.id, {
scopeMode: 'each_member',
resource: 'agent_total_tokens',
limit: 1000,
period: '1day',
})
const reset = await quotaService.resetRecord(team.id, rule.id, user.id)
expect(reset.userId).toBe(user.id)
expect(reset.consumed).toBe(0)
expect(reset.isWindowActive).toBe(true)
const records = await prisma.quotaRecord.findMany({ where: { ruleId: rule.id } })
expect(records).toHaveLength(1)
expect(records[0]?.userId).toBe(user.id)
expect(records[0]?.consumed).toBe(0)
})
it('rejects reset targets that do not match the quota rule', async () => {
const team = await prisma.team.create({
data: { name: 'Invalid Reset Target Team' },
})
const editor = await prisma.user.create({
data: { name: 'Editor', email: 'invalid-reset-editor@example.com', password: 'pw' },
})
const reviewer = await prisma.user.create({
data: { name: 'Reviewer', email: 'invalid-reset-reviewer@example.com', password: 'pw' },
})
await prisma.teamMember.createMany({
data: [
{ teamId: team.id, userId: editor.id, role: 'editor' },
{ teamId: team.id, userId: reviewer.id, role: 'reviewer' },
],
})
const roleRule = await quotaService.createRule(team.id, {
scopeMode: 'each_member',
role: 'editor',
resource: 'agent_total_tokens',
limit: 1000,
period: '1hour',
})
await expect(quotaService.resetRecord(team.id, roleRule.id, reviewer.id)).rejects.toThrow(
'does not match the rule role',
)
await expect(quotaService.resetRecord(team.id, roleRule.id, null)).rejects.toThrow(
'require a userId',
)
const selectedRule = await quotaService.createRule(team.id, {
scopeMode: 'selected_members',
userIds: [editor.id],
resource: 'agent_total_tokens',
limit: 1000,
period: '1hour',
})
await expect(quotaService.resetRecord(team.id, selectedRule.id, reviewer.id)).rejects.toThrow(
'not selected by this rule',
)
})
it('does not allow resetting a quota rule from another team', async () => {
const team = await prisma.team.create({ data: { name: 'Reset Owner Team' } })
const otherTeam = await prisma.team.create({ data: { name: 'Reset Other Team' } })
const rule = await quotaService.createRule(team.id, {
scopeMode: 'all_members',
resource: 'agent_total_tokens',
limit: 1000,
period: '1hour',
})
await expect(quotaService.resetRecord(otherTeam.id, rule.id, null)).rejects.toThrow(
'Quota rule not found',
)
})
it('enforces multiple matching rules simultaneously', async () => {
const team = await prisma.team.create({
data: { name: 'Multi Rule Team' },
+119
View File
@@ -548,6 +548,125 @@ export class QuotaService {
}
}
async resetRecord(
teamId: string,
ruleId: string,
userId: string | null,
): Promise<QuotaRecordResponse> {
const rule = await this.prismaClient.quotaRule.findUnique({
where: { id: ruleId },
})
if (!rule || rule.teamId !== teamId) {
throw new HTTPException(404, { message: 'Quota rule not found' })
}
if (rule.scopeMode === 'all_members' && userId !== null) {
throw new HTTPException(400, {
message: 'All-members quota records must use a null userId',
})
}
if (rule.scopeMode !== 'all_members' && userId === null) {
throw new HTTPException(400, {
message: 'Member quota records require a userId',
})
}
if (userId !== null) {
const member = await this.prismaClient.teamMember.findUnique({
where: {
teamIdUserId: {
teamId,
userId,
},
},
select: {
role: true,
user: {
select: { type: true },
},
},
})
if (!member || member.user.type !== 'human') {
throw new HTTPException(400, {
message: 'Quota record user must be a human team member',
})
}
if (rule.scopeMode === 'each_member' && rule.role && member.role !== rule.role) {
throw new HTTPException(400, {
message: 'Quota record user does not match the rule role',
})
}
if (rule.scopeMode === 'selected_members') {
const userIds = Array.isArray(rule.userIds) ? (rule.userIds as string[]) : []
if (!userIds.includes(userId)) {
throw new HTTPException(400, {
message: 'Quota record user is not selected by this rule',
})
}
}
}
await this.prismaClient.$transaction(async (tx) => {
// Lock the rule row so reset and first-use record creation are serialized.
await tx.$queryRaw`SELECT id FROM quota_rules WHERE id = ${rule.id} FOR UPDATE`
const periodStart = new Date()
const periodEnd = new Date(periodStart.getTime() + periodToDurationMs(rule.period))
const existingRecord = userId
? (
await tx.$queryRaw<RawQuotaRecord[]>`
SELECT * FROM quota_records
WHERE rule_id = ${rule.id} AND user_id = ${userId}
FOR UPDATE
`
)[0]
: (
await tx.$queryRaw<RawQuotaRecord[]>`
SELECT * FROM quota_records
WHERE rule_id = ${rule.id} AND user_id IS NULL
FOR UPDATE
`
)[0]
if (existingRecord) {
await tx.quotaRecord.update({
where: { id: existingRecord.id },
data: {
periodStart,
periodEnd,
consumed: 0,
},
})
} else {
await tx.quotaRecord.create({
data: {
ruleId: rule.id,
teamId: rule.teamId,
userId,
periodStart,
periodEnd,
consumed: 0,
},
})
}
})
const records = await this.listRuleRecords(teamId, ruleId)
const mappedRecord = records.records.find((record) => record.userId === userId)
if (!mappedRecord) {
throw new HTTPException(404, { message: 'Quota record not found' })
}
return mappedRecord
}
private async findMatchingRules(event: QuotaEvent): Promise<QuotaRule[]> {
const rules = await this.prismaClient.quotaRule.findMany({
where: {
+1
View File
@@ -49,6 +49,7 @@ export enum AuditAction {
quota_rule_create = 'quota_rule_create',
quota_rule_update = 'quota_rule_update',
quota_rule_delete = 'quota_rule_delete',
quota_record_reset = 'quota_record_reset',
quota_policy_create = 'quota_policy_create',
quota_policy_update = 'quota_policy_update',
quota_policy_delete = 'quota_policy_delete',
+5
View File
@@ -182,6 +182,11 @@ export const createQuotaRuleRequestSchema = z
})
export type CreateQuotaRuleRequest = z.input<typeof createQuotaRuleRequestSchema>
export const resetQuotaRecordRequestSchema = z.object({
userId: z.string().nullable(),
})
export type ResetQuotaRecordRequest = z.infer<typeof resetQuotaRecordRequestSchema>
export const updateQuotaRuleRequestSchema = z
.object({
scopeMode: quotaScopeModeSchema.optional(),
@@ -0,0 +1,458 @@
import { useEffect, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { formatRemainingTime } from '@/ui/lib/time'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Progress } from '@/ui/components/ui/progress'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/ui/components/ui/collapsible'
import {
Activity,
CheckCircle2,
ChevronDown,
Clock,
Gauge,
Loader2,
Search,
Users,
User,
UserCheck,
} from 'lucide-react'
import type { QuotaRecordResponse, QuotaRuleResponse } from '@shumai/dtos'
import { toast } from 'sonner'
import {
QUOTA_RESOURCE_META,
formatQuotaResourceValue,
getQuotaPeriodLabel,
} from '@/ui/components/quota/quota-display'
interface QuotaUsageDashboardProps {
teamId: string
}
function getRoleLabel(role: string): string {
switch (role.toLowerCase()) {
case 'owner':
return m.owner()
case 'editor':
return m.editor()
case 'reviewer':
return m.reviewer()
default:
return role
}
}
function getErrorMessage(body: unknown, fallback: string): string {
if (typeof body === 'object' && body !== null && 'message' in body) {
const message = body.message
if (typeof message === 'string') return message
}
return fallback
}
function RuleTarget({ rule }: { rule: QuotaRuleResponse }) {
const resourceData = rule.resourceData ?? {}
if (rule.resource === 'agent_mcp_call_count') {
return <span>{m.quota_target_server({ value: String(resourceData.id ?? '') })}</span>
}
if (rule.resource === 'agent_bash_call_count') {
return <span>{m.quota_target_match({ value: String(resourceData.match ?? '*') })}</span>
}
if (rule.resource === 'agent_tool_call_count') {
return (
<span>
{m.quota_target_tool({ value: String(resourceData.name ?? resourceData.toolName ?? '*') })}
</span>
)
}
return null
}
function ScopeBadge({ rule }: { rule: QuotaRuleResponse }) {
if (rule.scopeMode === 'all_members') {
return (
<Badge variant="secondary" className="gap-1 text-xs">
<Users className="h-3 w-3" />
<span>
{m.quota_scope_mode_all_members()}
{rule.role ? ` (${getRoleLabel(rule.role)})` : ` (${m.quota_scope_team()})`}
</span>
</Badge>
)
}
if (rule.scopeMode === 'each_member') {
return (
<Badge variant="secondary" className="gap-1 text-xs">
<User className="h-3 w-3" />
<span>
{m.quota_scope_mode_each_member()}
{rule.role ? ` (${getRoleLabel(rule.role)})` : ` (${m.quota_scope_team()})`}
</span>
</Badge>
)
}
return (
<Badge variant="secondary" className="gap-1 text-xs">
<UserCheck className="h-3 w-3" />
<span>
{m.quota_scope_mode_selected_members()} ({rule.userIds?.length || 0})
</span>
</Badge>
)
}
function QuotaUsageRecordCard({
teamId,
rule,
record,
}: {
teamId: string
rule: QuotaRuleResponse
record: QuotaRecordResponse
}) {
const queryClient = useQueryClient()
const [isResetDialogOpen, setIsResetDialogOpen] = useState(false)
const [now, setNow] = useState(() => new Date())
const meta = QUOTA_RESOURCE_META[rule.resource]
const isSharedPool = rule.scopeMode === 'all_members'
const isOverLimit = record.percent >= 100
const target = isSharedPool
? rule.role
? `${m.quota_role_shared_pool()}: ${getRoleLabel(rule.role)}`
: m.quota_team_shared_pool()
: record.user?.name || record.userId || m.unknown()
useEffect(() => {
if (!record.isWindowActive || !record.periodEnd) return
const interval = window.setInterval(() => setNow(new Date()), 60000)
return () => window.clearInterval(interval)
}, [record.isWindowActive, record.periodEnd])
const resetMutation = useMutation({
mutationFn: async () => {
const response = await client.api.teams[':teamId'].quotas[':id'].records.reset.$post({
param: { teamId, id: rule.id },
json: { userId: record.userId ?? null },
})
if (!response.ok) {
const body: unknown = await response.json().catch(() => null)
throw new Error(getErrorMessage(body, m.failed_to_reset_quota()))
}
return await response.json()
},
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'quotas', rule.id, 'records'],
})
void queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'quotas'] })
setIsResetDialogOpen(false)
toast.success(m.quota_reset_successfully())
},
onError: (error) => {
const message = error instanceof Error ? error.message : m.failed_to_reset_quota()
setIsResetDialogOpen(false)
toast.error(message)
},
})
return (
<>
<div className="space-y-3 rounded-xl border border-border/70 bg-card p-4 text-card-foreground shadow-2xs">
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-3">
{isSharedPool ? (
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
<Users className="h-5 w-5" />
</div>
) : (
<Avatar className="h-9 w-9 shrink-0 border border-border/50">
<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="truncate text-sm font-semibold text-foreground">{target}</div>
{!isSharedPool && record.user?.email && (
<div className="truncate text-xs text-muted-foreground">{record.user.email}</div>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
{record.isWindowActive && record.periodEnd ? (
<Badge
variant="outline"
className="hidden gap-1 border-primary/30 bg-primary/5 text-xs text-primary sm:flex"
>
<Clock className="h-3 w-3" />
<span>
{m.quota_refreshes_in({ time: formatRemainingTime(record.periodEnd, now) })}
</span>
</Badge>
) : (
<Badge
variant="secondary"
className="hidden gap-1 text-xs text-muted-foreground sm:flex"
>
<CheckCircle2 className="h-3 w-3 text-primary" />
<span>{m.quota_available()}</span>
</Badge>
)}
<Button
type="button"
variant="outline"
size="sm"
className="gap-1.5"
onClick={() => setIsResetDialogOpen(true)}
disabled={resetMutation.isPending}
>
{resetMutation.isPending ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Activity className="h-3.5 w-3.5" />
)}
{m.quota_reset_usage()}
</Button>
</div>
</div>
<div className="space-y-1.5 pt-1">
<Progress value={Math.min(100, Math.max(0, record.percent))} className="h-2" />
<div className="flex items-center justify-between gap-2 text-xs font-medium">
<span className={isOverLimit ? 'font-bold text-destructive' : 'text-foreground'}>
{formatQuotaResourceValue(rule.resource, record.consumed)} /{' '}
{formatQuotaResourceValue(rule.resource, rule.limit)} {meta?.unit}
</span>
<span className={isOverLimit ? 'font-bold text-destructive' : 'text-muted-foreground'}>
{record.percent}%
</span>
</div>
</div>
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground sm:hidden">
{record.isWindowActive && record.periodEnd ? (
<span className="flex items-center gap-1 text-primary">
<Clock className="h-3 w-3" />
{m.quota_refreshes_in({ time: formatRemainingTime(record.periodEnd, now) })}
</span>
) : (
<span className="flex items-center gap-1">
<CheckCircle2 className="h-3 w-3 text-primary" />
{m.quota_available()}
</span>
)}
<span>
{m.quota_remaining()}: {formatQuotaResourceValue(rule.resource, record.remaining)}{' '}
{meta?.unit}
</span>
</div>
</div>
<AlertDialog open={isResetDialogOpen} onOpenChange={setIsResetDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.quota_reset_usage()}</AlertDialogTitle>
<AlertDialogDescription>
{m.quota_reset_usage_confirm({ target })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={resetMutation.isPending}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
onClick={(event) => {
event.preventDefault()
resetMutation.mutate()
}}
disabled={resetMutation.isPending}
>
{resetMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{m.confirm()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
function QuotaRuleUsageItem({ teamId, rule }: { teamId: string; rule: QuotaRuleResponse }) {
const [isOpen, setIsOpen] = useState(false)
const [search, setSearch] = useState('')
const meta = QUOTA_RESOURCE_META[rule.resource]
const Icon = meta?.icon || Gauge
const { data, isLoading, isError } = useQuery({
queryKey: ['teams', teamId, 'quotas', rule.id, 'records'],
queryFn: async () => {
const response = await client.api.teams[':teamId'].quotas[':id'].records.$get({
param: { teamId, id: rule.id },
})
if (!response.ok) throw new Error(m.failed_to_load_quota_usage())
return await response.json()
},
enabled: isOpen,
refetchInterval: isOpen ? 10000 : false,
})
const records = data?.records ?? []
const filteredRecords = records.filter((record) => {
if (!search.trim()) return true
const query = search.toLowerCase()
return (
record.user?.name.toLowerCase().includes(query) ||
record.user?.email.toLowerCase().includes(query)
)
})
return (
<Collapsible
open={isOpen}
onOpenChange={setIsOpen}
className="rounded-xl border border-border/70"
>
<CollapsibleTrigger asChild>
<button
type="button"
aria-label={isOpen ? m.quota_collapse_rule() : m.quota_expand_rule()}
className="flex w-full items-center justify-between gap-4 p-4 text-left transition-colors hover:bg-muted/40"
>
<div className="flex min-w-0 items-start gap-3">
<div className="mt-0.5 rounded-lg bg-primary/10 p-2 text-primary">
<Icon className="h-5 w-5" />
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold text-foreground">
{meta?.label() || rule.resource}
</span>
{!rule.enabled && <Badge variant="secondary">{m.quota_disabled()}</Badge>}
</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
<ScopeBadge rule={rule} />
<Badge variant="outline" className="gap-1 text-xs">
<Clock className="h-3 w-3" />
{formatQuotaResourceValue(rule.resource, rule.limit)} {meta?.unit} /{' '}
{getQuotaPeriodLabel(rule.period)}
</Badge>
<RuleTarget rule={rule} />
</div>
</div>
</div>
<ChevronDown
className={`h-5 w-5 shrink-0 text-muted-foreground transition-transform ${isOpen ? 'rotate-180' : ''}`}
/>
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-3 border-t border-border/60 bg-muted/10 p-4">
{rule.scopeMode !== 'all_members' && records.length > 3 && (
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder={m.quota_search_members()}
className="h-9 pl-9 text-sm"
/>
</div>
)}
{isLoading ? (
<div className="flex justify-center py-10">
<Loader2 className="h-7 w-7 animate-spin text-primary" />
</div>
) : isError ? (
<div className="py-8 text-center text-sm text-destructive">
{m.failed_to_load_quota_usage()}
</div>
) : filteredRecords.length === 0 ? (
<div className="py-8 text-center text-sm text-muted-foreground">
{m.quota_no_usage_records()}
</div>
) : (
filteredRecords.map((record, index) => (
<QuotaUsageRecordCard
key={record.id || record.userId || `record-${index}`}
teamId={teamId}
rule={rule}
record={record}
/>
))
)}
</div>
</CollapsibleContent>
</Collapsible>
)
}
export function QuotaUsageDashboard({ teamId }: QuotaUsageDashboardProps) {
const { data, isLoading, isError } = useQuery({
queryKey: ['teams', teamId, 'quotas'],
queryFn: async () => {
const response = await client.api.teams[':teamId'].quotas.$get({ param: { teamId } })
if (!response.ok) throw new Error(m.failed_load_settings())
return await response.json()
},
enabled: !!teamId,
})
const rules = data?.rules ?? []
return (
<Card className="border-border/60 shadow-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-xl font-semibold tracking-tight">
<Gauge className="h-5 w-5 text-primary" />
{m.quotas()}
</CardTitle>
<CardDescription>{m.quota_dashboard_description()}</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="h-7 w-7 animate-spin text-muted-foreground" />
</div>
) : isError ? (
<div className="py-10 text-center text-sm text-destructive">
{m.failed_load_settings()}
</div>
) : rules.length === 0 ? (
<div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-border py-12 text-center">
<Gauge className="mb-3 h-10 w-10 text-muted-foreground/50" />
<p className="text-base font-medium text-foreground">{m.no_quotas_title()}</p>
<p className="mt-1 max-w-md text-sm text-muted-foreground">
{m.no_quotas_description()}
</p>
</div>
) : (
<div className="space-y-3">
{rules.map((rule) => (
<QuotaRuleUsageItem key={rule.id} teamId={teamId} rule={rule} />
))}
</div>
)}
</CardContent>
</Card>
)
}
@@ -0,0 +1,60 @@
import type { ElementType } from 'react'
import type { QuotaResourceTypeEnum } from '@shumai/dtos'
import { formatQuotaPeriod } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import { Cpu, DollarSign, Server, Terminal, Wrench } from 'lucide-react'
/* eslint-disable @typescript-eslint/naming-convention */
export const QUOTA_RESOURCE_META: Record<
QuotaResourceTypeEnum,
{ label: () => string; icon: 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_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 */
export function formatQuotaResourceValue(resource: QuotaResourceTypeEnum, value: number): string {
if (resource === 'agent_cost') {
return `$${value.toFixed(2)}`
}
return value.toLocaleString()
}
export function getQuotaPeriodLabel(period: string): string {
switch (formatQuotaPeriod(period)) {
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 period
}
}
@@ -1,274 +0,0 @@
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,
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_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>
)
}
@@ -28,89 +28,29 @@ import {
Loader2,
MoreVertical,
Trash2,
Cpu,
DollarSign,
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 type { QuotaRuleResponse } from '@shumai/dtos'
import {
QUOTA_RESOURCE_META,
formatQuotaResourceValue,
getQuotaPeriodLabel,
} from '../quota/quota-display'
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_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
@@ -204,7 +144,7 @@ export const QuotasSettings: React.FC<QuotasSettingsProps> = ({ teamId }) => {
) : (
<div className="flex flex-col gap-4">
{rules.map((rule) => {
const meta = RESOURCE_META[rule.resource]
const meta = QUOTA_RESOURCE_META[rule.resource]
const resData = (rule.resourceData as Record<string, unknown> | null) || {}
return (
@@ -272,8 +212,8 @@ export const QuotasSettings: React.FC<QuotasSettingsProps> = ({ teamId }) => {
</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">
{/* Badges Row */}
<div className="flex flex-wrap items-center 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' && (
@@ -308,25 +248,11 @@ export const QuotasSettings: React.FC<QuotasSettingsProps> = ({ teamId }) => {
<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)}
{formatQuotaResourceValue(rule.resource, rule.limit)} {meta?.unit} /{' '}
{getQuotaPeriodLabel(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>
@@ -353,18 +279,6 @@ export const QuotasSettings: React.FC<QuotasSettingsProps> = ({ teamId }) => {
/>
)}
{/* 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}
+12 -3
View File
@@ -1106,9 +1106,18 @@
"quota_scope_mode_all_members_desc": "Shared pooled limit across all matching members",
"quota_scope_mode_selected_members": "Selected Members",
"quota_scope_mode_selected_members_desc": "Individual limit for selected users",
"quota_view_usage": "View Usage",
"quota_usage_records": "Usage Records",
"quota_usage_records_description": "Real-time usage breakdown for this quota rule.",
"quota_dashboard_description": "Monitor live quota usage and reset individual usage windows.",
"quota_reset_usage": "Reset Usage",
"quota_reset_usage_confirm": "Reset usage for {target}? Consumption will be cleared and a new quota window will start now.",
"quota_reset_successfully": "Quota usage reset successfully",
"failed_to_reset_quota": "Failed to reset quota usage",
"failed_to_load_quota_usage": "Failed to load quota usage",
"quota_no_usage_records": "No usage records found",
"quota_expand_rule": "Expand quota rule",
"quota_collapse_rule": "Collapse quota rule",
"quota_target_server": "Server: {value}",
"quota_target_match": "Match: {value}",
"quota_target_tool": "Tool: {value}",
"quota_team_shared_pool": "Team Shared Pool",
"quota_role_shared_pool": "Role Shared Pool",
"quota_available": "Quota available",
+12 -3
View File
@@ -1106,9 +1106,18 @@
"quota_scope_mode_all_members_desc": "所有符合条件的成员共同享有总配额上限",
"quota_scope_mode_selected_members": "指定成员",
"quota_scope_mode_selected_members_desc": "为选定的成员分别设定独立的配额上限",
"quota_view_usage": "查看使用量",
"quota_usage_records": "使用记录",
"quota_usage_records_description": "该配额规则的实时使用明细与生效状态。",
"quota_dashboard_description": "在仪表盘中监控实时配额使用情况,并重置单个使用窗口。",
"quota_reset_usage": "重置使用量",
"quota_reset_usage_confirm": "确定要重置 {target} 的使用量吗?当前消耗将被清零,并立即开始新的配额周期。",
"quota_reset_successfully": "配额使用量重置成功",
"failed_to_reset_quota": "重置配额使用量失败",
"failed_to_load_quota_usage": "加载配额使用量失败",
"quota_no_usage_records": "暂无使用记录",
"quota_expand_rule": "展开配额规则",
"quota_collapse_rule": "收起配额规则",
"quota_target_server": "服务:{value}",
"quota_target_match": "匹配:{value}",
"quota_target_tool": "工具:{value}",
"quota_team_shared_pool": "团队共享配额池",
"quota_role_shared_pool": "角色共享配额池",
"quota_available": "配额可用",
+12 -3
View File
@@ -1050,9 +1050,18 @@ export * from "./quota_scope_mode_all_members.js";
export * from "./quota_scope_mode_all_members_desc.js";
export * from "./quota_scope_mode_selected_members.js";
export * from "./quota_scope_mode_selected_members_desc.js";
export * from "./quota_view_usage.js";
export * from "./quota_usage_records.js";
export * from "./quota_usage_records_description.js";
export * from "./quota_dashboard_description.js";
export * from "./quota_reset_usage.js";
export * from "./quota_reset_usage_confirm.js";
export * from "./quota_reset_successfully.js";
export * from "./failed_to_reset_quota.js";
export * from "./failed_to_load_quota_usage.js";
export * from "./quota_no_usage_records.js";
export * from "./quota_expand_rule.js";
export * from "./quota_collapse_rule.js";
export * from "./quota_target_server.js";
export * from "./quota_target_match.js";
export * from "./quota_target_tool.js";
export * from "./quota_team_shared_pool.js";
export * from "./quota_role_shared_pool.js";
export * from "./quota_available.js";
+12 -3
View File
@@ -1052,9 +1052,18 @@ export * from './quota_scope_mode_all_members.js'
export * from './quota_scope_mode_all_members_desc.js'
export * from './quota_scope_mode_selected_members.js'
export * from './quota_scope_mode_selected_members_desc.js'
export * from './quota_view_usage.js'
export * from './quota_usage_records.js'
export * from './quota_usage_records_description.js'
export * from './quota_dashboard_description.js'
export * from './quota_reset_usage.js'
export * from './quota_reset_usage_confirm.js'
export * from './quota_reset_successfully.js'
export * from './failed_to_reset_quota.js'
export * from './failed_to_load_quota_usage.js'
export * from './quota_no_usage_records.js'
export * from './quota_expand_rule.js'
export * from './quota_collapse_rule.js'
export * from './quota_target_server.js'
export * from './quota_target_match.js'
export * from './quota_target_tool.js'
export * from './quota_team_shared_pool.js'
export * from './quota_role_shared_pool.js'
export * from './quota_available.js'
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Failed to load quota usage" |
*
* @param {Failed_To_Load_Quota_UsageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const failed_to_load_quota_usage: ((inputs?: Failed_To_Load_Quota_UsageInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Failed_To_Load_Quota_UsageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Failed_To_Load_Quota_UsageInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Failed_To_Load_Quota_UsageInputs */
const en_failed_to_load_quota_usage = /** @type {(inputs: Failed_To_Load_Quota_UsageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Failed to load quota usage`)
};
const zh_failed_to_load_quota_usage = /** @type {(inputs: Failed_To_Load_Quota_UsageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`加载配额使用量失败`)
};
/**
* | output |
* | --- |
* | "Failed to load quota usage" |
*
* @param {Failed_To_Load_Quota_UsageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const failed_to_load_quota_usage = /** @type {((inputs?: Failed_To_Load_Quota_UsageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Failed_To_Load_Quota_UsageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_failed_to_load_quota_usage(inputs)
return zh_failed_to_load_quota_usage(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Failed to reset quota usage" |
*
* @param {Failed_To_Reset_QuotaInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const failed_to_reset_quota: ((inputs?: Failed_To_Reset_QuotaInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Failed_To_Reset_QuotaInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Failed_To_Reset_QuotaInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Failed_To_Reset_QuotaInputs */
const en_failed_to_reset_quota = /** @type {(inputs: Failed_To_Reset_QuotaInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Failed to reset quota usage`)
};
const zh_failed_to_reset_quota = /** @type {(inputs: Failed_To_Reset_QuotaInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`重置配额使用量失败`)
};
/**
* | output |
* | --- |
* | "Failed to reset quota usage" |
*
* @param {Failed_To_Reset_QuotaInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const failed_to_reset_quota = /** @type {((inputs?: Failed_To_Reset_QuotaInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Failed_To_Reset_QuotaInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_failed_to_reset_quota(inputs)
return zh_failed_to_reset_quota(inputs)
});
@@ -1,16 +1,16 @@
/**
* | output |
* | --- |
* | "Usage Records" |
* | "Collapse quota rule" |
*
* @param {Quota_Usage_RecordsInputs} inputs
* @param {Quota_Collapse_RuleInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_usage_records: ((inputs?: Quota_Usage_RecordsInputs, options?: {
export const quota_collapse_rule: ((inputs?: Quota_Collapse_RuleInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Usage_RecordsInputs, {
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Collapse_RuleInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Usage_RecordsInputs = {};
export type Quota_Collapse_RuleInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Collapse_RuleInputs */
const en_quota_collapse_rule = /** @type {(inputs: Quota_Collapse_RuleInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Collapse quota rule`)
};
const zh_quota_collapse_rule = /** @type {(inputs: Quota_Collapse_RuleInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`收起配额规则`)
};
/**
* | output |
* | --- |
* | "Collapse quota rule" |
*
* @param {Quota_Collapse_RuleInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_collapse_rule = /** @type {((inputs?: Quota_Collapse_RuleInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Collapse_RuleInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_collapse_rule(inputs)
return zh_quota_collapse_rule(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Monitor live quota usage and reset individual usage windows." |
*
* @param {Quota_Dashboard_DescriptionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_dashboard_description: ((inputs?: Quota_Dashboard_DescriptionInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Dashboard_DescriptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Dashboard_DescriptionInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Dashboard_DescriptionInputs */
const en_quota_dashboard_description = /** @type {(inputs: Quota_Dashboard_DescriptionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Monitor live quota usage and reset individual usage windows.`)
};
const zh_quota_dashboard_description = /** @type {(inputs: Quota_Dashboard_DescriptionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`在仪表盘中监控实时配额使用情况,并重置单个使用窗口。`)
};
/**
* | output |
* | --- |
* | "Monitor live quota usage and reset individual usage windows." |
*
* @param {Quota_Dashboard_DescriptionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_dashboard_description = /** @type {((inputs?: Quota_Dashboard_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Dashboard_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_dashboard_description(inputs)
return zh_quota_dashboard_description(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Expand quota rule" |
*
* @param {Quota_Expand_RuleInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_expand_rule: ((inputs?: Quota_Expand_RuleInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Expand_RuleInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Expand_RuleInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Expand_RuleInputs */
const en_quota_expand_rule = /** @type {(inputs: Quota_Expand_RuleInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Expand quota rule`)
};
const zh_quota_expand_rule = /** @type {(inputs: Quota_Expand_RuleInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`展开配额规则`)
};
/**
* | output |
* | --- |
* | "Expand quota rule" |
*
* @param {Quota_Expand_RuleInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_expand_rule = /** @type {((inputs?: Quota_Expand_RuleInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Expand_RuleInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_expand_rule(inputs)
return zh_quota_expand_rule(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "No usage records found" |
*
* @param {Quota_No_Usage_RecordsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_no_usage_records: ((inputs?: Quota_No_Usage_RecordsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_No_Usage_RecordsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_No_Usage_RecordsInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_No_Usage_RecordsInputs */
const en_quota_no_usage_records = /** @type {(inputs: Quota_No_Usage_RecordsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`No usage records found`)
};
const zh_quota_no_usage_records = /** @type {(inputs: Quota_No_Usage_RecordsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`暂无使用记录`)
};
/**
* | output |
* | --- |
* | "No usage records found" |
*
* @param {Quota_No_Usage_RecordsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_no_usage_records = /** @type {((inputs?: Quota_No_Usage_RecordsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_No_Usage_RecordsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_no_usage_records(inputs)
return zh_quota_no_usage_records(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Quota usage reset successfully" |
*
* @param {Quota_Reset_SuccessfullyInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_reset_successfully: ((inputs?: Quota_Reset_SuccessfullyInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Reset_SuccessfullyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Reset_SuccessfullyInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Reset_SuccessfullyInputs */
const en_quota_reset_successfully = /** @type {(inputs: Quota_Reset_SuccessfullyInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Quota usage reset successfully`)
};
const zh_quota_reset_successfully = /** @type {(inputs: Quota_Reset_SuccessfullyInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`配额使用量重置成功`)
};
/**
* | output |
* | --- |
* | "Quota usage reset successfully" |
*
* @param {Quota_Reset_SuccessfullyInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_reset_successfully = /** @type {((inputs?: Quota_Reset_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Reset_SuccessfullyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_reset_successfully(inputs)
return zh_quota_reset_successfully(inputs)
});
@@ -1,16 +1,16 @@
/**
* | output |
* | --- |
* | "View Usage" |
* | "Reset Usage" |
*
* @param {Quota_View_UsageInputs} inputs
* @param {Quota_Reset_UsageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_view_usage: ((inputs?: Quota_View_UsageInputs, options?: {
export const quota_reset_usage: ((inputs?: Quota_Reset_UsageInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_View_UsageInputs, {
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Reset_UsageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_View_UsageInputs = {};
export type Quota_Reset_UsageInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Reset_UsageInputs */
const en_quota_reset_usage = /** @type {(inputs: Quota_Reset_UsageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Reset Usage`)
};
const zh_quota_reset_usage = /** @type {(inputs: Quota_Reset_UsageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`重置使用量`)
};
/**
* | output |
* | --- |
* | "Reset Usage" |
*
* @param {Quota_Reset_UsageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_reset_usage = /** @type {((inputs?: Quota_Reset_UsageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Reset_UsageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_reset_usage(inputs)
return zh_quota_reset_usage(inputs)
});
+18
View File
@@ -0,0 +1,18 @@
/**
* | output |
* | --- |
* | "Reset usage for {target}? Consumption will be cleared and a new quota window will start now." |
*
* @param {Quota_Reset_Usage_ConfirmInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_reset_usage_confirm: ((inputs: Quota_Reset_Usage_ConfirmInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Reset_Usage_ConfirmInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Reset_Usage_ConfirmInputs = {
target: NonNullable<unknown>;
};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ target: NonNullable<unknown> }} Quota_Reset_Usage_ConfirmInputs */
const en_quota_reset_usage_confirm = /** @type {(inputs: Quota_Reset_Usage_ConfirmInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`Reset usage for ${i?.target}? Consumption will be cleared and a new quota window will start now.`)
};
const zh_quota_reset_usage_confirm = /** @type {(inputs: Quota_Reset_Usage_ConfirmInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`确定要重置 ${i?.target} 的使用量吗?当前消耗将被清零,并立即开始新的配额周期。`)
};
/**
* | output |
* | --- |
* | "Reset usage for {target}? Consumption will be cleared and a new quota window will start now." |
*
* @param {Quota_Reset_Usage_ConfirmInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_reset_usage_confirm = /** @type {((inputs: Quota_Reset_Usage_ConfirmInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Reset_Usage_ConfirmInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_reset_usage_confirm(inputs)
return zh_quota_reset_usage_confirm(inputs)
});
+18
View File
@@ -0,0 +1,18 @@
/**
* | output |
* | --- |
* | "Match: {value}" |
*
* @param {Quota_Target_MatchInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_target_match: ((inputs: Quota_Target_MatchInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Target_MatchInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Target_MatchInputs = {
value: NonNullable<unknown>;
};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ value: NonNullable<unknown> }} Quota_Target_MatchInputs */
const en_quota_target_match = /** @type {(inputs: Quota_Target_MatchInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`Match: ${i?.value}`)
};
const zh_quota_target_match = /** @type {(inputs: Quota_Target_MatchInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`匹配:${i?.value}`)
};
/**
* | output |
* | --- |
* | "Match: {value}" |
*
* @param {Quota_Target_MatchInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_target_match = /** @type {((inputs: Quota_Target_MatchInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Target_MatchInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_target_match(inputs)
return zh_quota_target_match(inputs)
});
+18
View File
@@ -0,0 +1,18 @@
/**
* | output |
* | --- |
* | "Server: {value}" |
*
* @param {Quota_Target_ServerInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_target_server: ((inputs: Quota_Target_ServerInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Target_ServerInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Target_ServerInputs = {
value: NonNullable<unknown>;
};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ value: NonNullable<unknown> }} Quota_Target_ServerInputs */
const en_quota_target_server = /** @type {(inputs: Quota_Target_ServerInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`Server: ${i?.value}`)
};
const zh_quota_target_server = /** @type {(inputs: Quota_Target_ServerInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`服务:${i?.value}`)
};
/**
* | output |
* | --- |
* | "Server: {value}" |
*
* @param {Quota_Target_ServerInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_target_server = /** @type {((inputs: Quota_Target_ServerInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Target_ServerInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_target_server(inputs)
return zh_quota_target_server(inputs)
});
+18
View File
@@ -0,0 +1,18 @@
/**
* | output |
* | --- |
* | "Tool: {value}" |
*
* @param {Quota_Target_ToolInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_target_tool: ((inputs: Quota_Target_ToolInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Target_ToolInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Target_ToolInputs = {
value: NonNullable<unknown>;
};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ value: NonNullable<unknown> }} Quota_Target_ToolInputs */
const en_quota_target_tool = /** @type {(inputs: Quota_Target_ToolInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`Tool: ${i?.value}`)
};
const zh_quota_target_tool = /** @type {(inputs: Quota_Target_ToolInputs) => LocalizedString} */ (i) => {
return /** @type {LocalizedString} */ (`工具:${i?.value}`)
};
/**
* | output |
* | --- |
* | "Tool: {value}" |
*
* @param {Quota_Target_ToolInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_target_tool = /** @type {((inputs: Quota_Target_ToolInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Target_ToolInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_target_tool(inputs)
return zh_quota_target_tool(inputs)
});
-29
View File
@@ -1,29 +0,0 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Usage_RecordsInputs */
const en_quota_usage_records = /** @type {(inputs: Quota_Usage_RecordsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Usage Records`)
};
const zh_quota_usage_records = /** @type {(inputs: Quota_Usage_RecordsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`使用记录`)
};
/**
* | output |
* | --- |
* | "Usage Records" |
*
* @param {Quota_Usage_RecordsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_usage_records = /** @type {((inputs?: Quota_Usage_RecordsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Usage_RecordsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_usage_records(inputs)
return zh_quota_usage_records(inputs)
});
-16
View File
@@ -1,16 +0,0 @@
/**
* | output |
* | --- |
* | "Real-time usage breakdown for this quota rule." |
*
* @param {Quota_Usage_Records_DescriptionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_usage_records_description: ((inputs?: Quota_Usage_Records_DescriptionInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Quota_Usage_Records_DescriptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Quota_Usage_Records_DescriptionInputs = {};
@@ -1,29 +0,0 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_Usage_Records_DescriptionInputs */
const en_quota_usage_records_description = /** @type {(inputs: Quota_Usage_Records_DescriptionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Real-time usage breakdown for this quota rule.`)
};
const zh_quota_usage_records_description = /** @type {(inputs: Quota_Usage_Records_DescriptionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`该配额规则的实时使用明细与生效状态。`)
};
/**
* | output |
* | --- |
* | "Real-time usage breakdown for this quota rule." |
*
* @param {Quota_Usage_Records_DescriptionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_usage_records_description = /** @type {((inputs?: Quota_Usage_Records_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_Usage_Records_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_usage_records_description(inputs)
return zh_quota_usage_records_description(inputs)
});
-29
View File
@@ -1,29 +0,0 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Quota_View_UsageInputs */
const en_quota_view_usage = /** @type {(inputs: Quota_View_UsageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`View Usage`)
};
const zh_quota_view_usage = /** @type {(inputs: Quota_View_UsageInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`查看使用量`)
};
/**
* | output |
* | --- |
* | "View Usage" |
*
* @param {Quota_View_UsageInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const quota_view_usage = /** @type {((inputs?: Quota_View_UsageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Quota_View_UsageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_quota_view_usage(inputs)
return zh_quota_view_usage(inputs)
});
@@ -6,10 +6,11 @@ import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { AiUsageDashboard } from '@/ui/components/dashboard/AiUsageDashboard'
import { AgentSessionsDashboard } from '@/ui/components/dashboard/AgentSessionsDashboard'
import { QuotaUsageDashboard } from '@/ui/components/dashboard/QuotaUsageDashboard'
import { AuditLogsDashboard } from '@/ui/components/dashboard/AuditLogsDashboard'
import { Activity, BarChart2, Loader2, MessagesSquare, ShieldAlert } from 'lucide-react'
import { Activity, BarChart2, Gauge, Loader2, MessagesSquare, ShieldAlert } from 'lucide-react'
type DashboardTab = 'audit-logs' | 'ai-usage' | 'ai-sessions'
type DashboardTab = 'audit-logs' | 'ai-usage' | 'ai-sessions' | 'quotas'
function TeamDashboardPage() {
const { teamId } = Route.useParams()
@@ -76,6 +77,22 @@ function TeamDashboardPage() {
)}
</button>
<button
onClick={() => setActiveTab('quotas')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'quotas'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Gauge className="w-5 h-5" />
{m.quotas()}
{activeTab === 'quotas' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
{/* AI Category */}
<div className="mt-4 mb-2 px-4 text-xs font-semibold text-sidebar-foreground/60 uppercase tracking-wider pt-4 border-t border-sidebar-border">
{m.ai()}
@@ -121,6 +138,7 @@ function TeamDashboardPage() {
{activeTab === 'audit-logs' && <AuditLogsDashboard teamId={teamId} />}
{activeTab === 'ai-usage' && <AiUsageDashboard teamId={teamId} />}
{activeTab === 'ai-sessions' && <AgentSessionsDashboard teamId={teamId} />}
{activeTab === 'quotas' && <QuotaUsageDashboard teamId={teamId} />}
</div>
</div>
</div>