mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 20:34:28 +00:00
feat(agent): add permission controls for chat agents (#313)
* feat(agent): add permission controls for chat agents * refactor(agent): extract shared agent permission helpers Consolidate the duplicated role-hierarchy logic into packages/core/src/agent/permissions.ts: - getRoleLevel(): numeric level for a team role (fail closed at 0) - getAgentRequiredLevel(): required level for an agent permission (defaults to reviewer/1) - getAllowedAgentRoles(): inclusive role set for filtering The typed Record over TeamMemberRole makes the mapping exhaustive, so adding a new role fails compilation until all sites are updated. Used by ChatService.startOrContinueChat, AssetService comment mentions, getAgentChatContextActivity, AgentService.listAgents, and TeamService.getTeamMembers, replacing four inline copies of the hierarchy and the allowed-roles conditionals. Also fix the API permission-denial test to mock HTTPException(403) and assert a 403 response instead of a generic Error/500, matching real authzService behavior. * test(agent): fix flaky comment DAG tests by spacing ULID id generation ULID ids have 1ms timestamp granularity; back-to-back comment creates frequently land in the same millisecond, in which case Prisma ULIDs sort by their random suffix instead of creation order. The DAG spine in initializeAgentSessionActivity chains top-level comments by id, so a shuffled order produces paths that omit preceding comments, making the path-to-root assertions flaky (~80% of full-file runs locally). Add a 2ms sleep between consecutive comment creates in the affected tests, guaranteeing strictly increasing ULID timestamps. A 2ms delay is sufficient because the next create always fires at least 2ms after the previous ULID was generated. Production is unaffected: real comments arrive seconds apart via separate requests.
This commit is contained in:
@@ -86,6 +86,8 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
||||
if (!exists) {
|
||||
setSelectedAgentId(chatAgents[0].id)
|
||||
}
|
||||
} else if (selectedAgentId !== null) {
|
||||
setSelectedAgentId(null)
|
||||
}
|
||||
}, [chatAgents, selectedAgentId, setSelectedAgentId])
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ interface AgentFormDialogProps {
|
||||
const agentFormSchema = z.object({
|
||||
name: z.string().min(1, m.name_is_required()),
|
||||
type: z.enum(['chat', 'autofill', 'embedding']),
|
||||
permission: z.enum(['owner', 'editor', 'reviewer']),
|
||||
avatar: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
@@ -186,6 +187,7 @@ export function AgentFormDialog({
|
||||
defaultValues: {
|
||||
name: initialValues?.name || '',
|
||||
type: initialValues?.type || type || 'chat',
|
||||
permission: initialValues?.permission || 'reviewer',
|
||||
avatar: initialValues?.avatar || AVAILABLE_AVATARS[0],
|
||||
providerId: initialValues?.providerId || '',
|
||||
modelId: initialValues?.modelId || '',
|
||||
@@ -272,6 +274,7 @@ export function AgentFormDialog({
|
||||
|
||||
const agentType = useStore(form.store, (s) => s.values.type)
|
||||
const isAiType = agentType === 'chat' || agentType === 'autofill'
|
||||
const isChatType = agentType === 'chat'
|
||||
|
||||
const mapErrors = (errors: unknown[]) => {
|
||||
return errors.map((e) => {
|
||||
@@ -345,6 +348,35 @@ export function AgentFormDialog({
|
||||
)}
|
||||
/>
|
||||
|
||||
{isChatType && (
|
||||
<form.Field
|
||||
name="permission"
|
||||
children={(field) => (
|
||||
<Field>
|
||||
<FieldLabel>{m.skill_permission()}</FieldLabel>
|
||||
<Select
|
||||
value={field.state.value || 'reviewer'}
|
||||
onValueChange={(val) =>
|
||||
field.handleChange(val as 'owner' | 'editor' | 'reviewer')
|
||||
}
|
||||
disabled={!canAdmin}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="reviewer">{m.permission_all_users()}</SelectItem>
|
||||
<SelectItem value="editor">
|
||||
{m.permission_owner_and_editor()}
|
||||
</SelectItem>
|
||||
<SelectItem value="owner">{m.permission_owner_only()}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<form.Field
|
||||
name="avatar"
|
||||
children={(field) => (
|
||||
|
||||
@@ -1,43 +1,51 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Card, CardContent } from '@/ui/components/ui/card'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Loader2,
|
||||
Plus,
|
||||
Trash2,
|
||||
Bot,
|
||||
MoreVertical,
|
||||
MessageSquare,
|
||||
Zap,
|
||||
Cpu,
|
||||
Puzzle,
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Card, CardContent } from '@/ui/components/ui/card'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { AgentInfo, AgentPermission, AgentType, ThinkingLevel } from '@shumai/dtos'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Bot,
|
||||
ChevronDown,
|
||||
Cpu,
|
||||
Loader2,
|
||||
MessageSquare,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
Puzzle,
|
||||
Trash2,
|
||||
Zap,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { AgentInfo, AgentType, ThinkingLevel } from '@shumai/dtos'
|
||||
import { AgentFormDialog } from './AgentFormDialog'
|
||||
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 { cn } from '@/ui/lib/utils'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface AgentsSettingsProps {
|
||||
teamId: string
|
||||
@@ -55,6 +63,7 @@ const AGENT_TYPES: {
|
||||
|
||||
export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { canAdmin } = usePermissions()
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [createType, setCreateType] = useState<AgentType>('chat')
|
||||
const [editingAgent, setAgentToEdit] = useState<AgentInfo | null>(null)
|
||||
@@ -101,6 +110,29 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
},
|
||||
})
|
||||
|
||||
const updateAgentPermissionMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
agentId,
|
||||
permission,
|
||||
}: {
|
||||
agentId: string
|
||||
permission: AgentPermission
|
||||
}) => {
|
||||
const res = await client.api.agents[':agentId'].permission.$patch({
|
||||
param: { agentId },
|
||||
json: { permission },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_update_permission())
|
||||
return res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || m.failed_to_update_permission())
|
||||
},
|
||||
})
|
||||
|
||||
const updateAgentMutation = useMutation({
|
||||
mutationFn: async (params: {
|
||||
teamId: string
|
||||
@@ -279,56 +311,34 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
{typeAgents.map((agent) => (
|
||||
<Card
|
||||
key={agent.id}
|
||||
className="group relative overflow-hidden border-border hover:border-primary/50 transition-all duration-200 cursor-pointer"
|
||||
className="group relative overflow-hidden border-border hover:border-primary/50 transition-all duration-200 cursor-pointer pb-1 pt-1"
|
||||
onClick={() => setAgentToEdit(agent)}
|
||||
>
|
||||
<CardContent className="p-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||
<div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center overflow-hidden">
|
||||
{agent.avatar ? (
|
||||
<img
|
||||
src={agent.avatar}
|
||||
className="w-full h-full object-cover"
|
||||
alt=""
|
||||
/>
|
||||
) : (
|
||||
<Bot className="w-6 h-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-bold text-foreground block truncate">
|
||||
{agent.name}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
|
||||
<span className="flex items-center gap-1">
|
||||
<Puzzle className="w-3 h-3" />
|
||||
{m.skills_count_value({ count: agent.skills?.length || 0 })}
|
||||
<CardContent className="p-4 flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||
<div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center overflow-hidden">
|
||||
{agent.avatar ? (
|
||||
<img
|
||||
src={agent.avatar}
|
||||
className="w-full h-full object-cover"
|
||||
alt=""
|
||||
/>
|
||||
) : (
|
||||
<Bot className="w-6 h-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-bold text-foreground block truncate">
|
||||
{agent.name}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
|
||||
<span className="flex items-center gap-1">
|
||||
<Puzzle className="w-3 h-3" />
|
||||
{m.skills_count_value({ count: agent.skills?.length || 0 })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="mr-2" onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={agent.enabled}
|
||||
onCheckedChange={(enabled) => {
|
||||
updateAgentMutation.mutate({
|
||||
teamId,
|
||||
agentId: agent.id,
|
||||
name: agent.name,
|
||||
type: agent.type,
|
||||
enabled,
|
||||
avatar: agent.avatar,
|
||||
providerId: agent.providerId,
|
||||
modelId: agent.modelId,
|
||||
thinkingLevel: agent.thinkingLevel,
|
||||
systemPrompt: agent.systemPrompt,
|
||||
soul: agent.soul,
|
||||
skills: agent.skills?.map((s) => s.skillId),
|
||||
deniedTools: agent.deniedTools,
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
@@ -352,7 +362,71 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
<Trash2 className="w-4 h-4" /> {m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>{' '}
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 pt-2 border-t border-border/50">
|
||||
<div>
|
||||
{agent.type === 'chat' ? (
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<Select
|
||||
value={agent.permission || 'reviewer'}
|
||||
onValueChange={(permission) => {
|
||||
updateAgentPermissionMutation.mutate({
|
||||
agentId: agent.id,
|
||||
permission: permission as AgentPermission,
|
||||
})
|
||||
}}
|
||||
disabled={!canAdmin}
|
||||
>
|
||||
<SelectTrigger className="h-7 text-xs px-2 bg-background border-border w-[140px]">
|
||||
<SelectValue>
|
||||
{agent.permission === 'reviewer'
|
||||
? m.permission_all_users()
|
||||
: agent.permission === 'editor'
|
||||
? m.permission_owner_and_editor()
|
||||
: m.permission_owner_only()}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent align="start">
|
||||
<SelectItem value="reviewer">
|
||||
{m.permission_all_users()}
|
||||
</SelectItem>
|
||||
<SelectItem value="editor">
|
||||
{m.permission_owner_and_editor()}
|
||||
</SelectItem>
|
||||
<SelectItem value="owner">
|
||||
{m.permission_owner_only()}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
</div>
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={agent.enabled}
|
||||
onCheckedChange={(enabled) => {
|
||||
updateAgentMutation.mutate({
|
||||
teamId,
|
||||
agentId: agent.id,
|
||||
name: agent.name,
|
||||
type: agent.type,
|
||||
enabled,
|
||||
avatar: agent.avatar,
|
||||
providerId: agent.providerId,
|
||||
modelId: agent.modelId,
|
||||
thinkingLevel: agent.thinkingLevel,
|
||||
systemPrompt: agent.systemPrompt,
|
||||
soul: agent.soul,
|
||||
skills: agent.skills?.map((s) => s.skillId),
|
||||
deniedTools: agent.deniedTools,
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
Reference in New Issue
Block a user