mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 10:06:56 +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:
@@ -514,6 +514,11 @@ describe('Agent Activities', () => {
|
||||
describe('Agent Database Activities Integration', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// Space out comment creations: ULID ids have 1ms timestamp granularity, so
|
||||
// back-to-back creates landing in the same millisecond sort by random suffix
|
||||
// and can break the id-ordered DAG spine in initializeAgentSessionActivity.
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
let team: Team
|
||||
let user: User
|
||||
let project: Project
|
||||
@@ -571,6 +576,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
},
|
||||
})
|
||||
|
||||
await sleep(2)
|
||||
// Create second comment that user responds with, triggering session initialization
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
@@ -618,11 +624,13 @@ describe('Agent Database Activities Integration', () => {
|
||||
const mainComment1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'Main Comment 1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
const mainComment2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'Main Comment 2', creatorId: user.id },
|
||||
})
|
||||
|
||||
// 2. Thread reply under mainComment1
|
||||
await sleep(2)
|
||||
const threadReply1 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -731,10 +739,12 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg2 (top level)
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg3 (top level asking agent)
|
||||
const msg3 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '[ask agent] msg3', creatorId: user.id },
|
||||
@@ -749,6 +759,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// agent response msg4
|
||||
await sleep(2)
|
||||
const msg4 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -760,6 +771,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// msg5 (top level asking agent)
|
||||
await sleep(2)
|
||||
const msg5 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '[ask agent] msg5', creatorId: user.id },
|
||||
})
|
||||
@@ -783,6 +795,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(session3Id).not.toBe(session5Id)
|
||||
|
||||
// msg7 (reply to msg3 asking agent again)
|
||||
await sleep(2)
|
||||
const msg7 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -831,10 +844,12 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg2 (top level)
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg3 (top level asking agent)
|
||||
const msg3 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '<@shumai-x1> what did i say', creatorId: user.id },
|
||||
@@ -869,10 +884,12 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg2 (top level)
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
await sleep(2)
|
||||
// msg3 (top level asking agent)
|
||||
const msg3 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: '<@shumai-x1> what did i say', creatorId: user.id },
|
||||
@@ -1086,6 +1103,55 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(chatCtx.enabledSkillIds).toEqual([enabledSkill.id])
|
||||
expect(chatCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id)
|
||||
|
||||
// Test permission enforcement in getAgentChatContextActivity
|
||||
// Create owner-only agent
|
||||
const ownerAgentUser = await prisma.user.create({
|
||||
data: { name: 'Owner Bot', email: `ownerbot-${Date.now()}@shumai.ai`, type: 'agent' },
|
||||
})
|
||||
const ownerAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: ownerAgentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
|
||||
// Create owner and reviewer members
|
||||
const ownerUser = await prisma.user.create({
|
||||
data: { name: 'Owner User', email: `owner-${Date.now()}@shumai.ai` },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: ownerUser.id, role: 'owner' },
|
||||
})
|
||||
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: { name: 'Reviewer User', email: `reviewer-${Date.now()}@shumai.ai` },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Owner should succeed
|
||||
const ownerCtx = await getAgentChatContextActivity({
|
||||
teamId: team.id,
|
||||
agentId: ownerAgent.id,
|
||||
userId: ownerUser.id,
|
||||
})
|
||||
expect(ownerCtx.agent.id).toBe(ownerAgent.id)
|
||||
|
||||
// Reviewer should fail with non-retryable ApplicationFailure
|
||||
await expect(
|
||||
getAgentChatContextActivity({
|
||||
teamId: team.id,
|
||||
agentId: ownerAgent.id,
|
||||
userId: reviewerUser.id,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
|
||||
// Create User for autofill agent
|
||||
const autofillUser = await prisma.user.create({
|
||||
data: {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { encodeCursor, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
|
||||
import { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, Context } from '@temporalio/activity'
|
||||
@@ -886,6 +887,7 @@ export async function updateCommentActivity(params: {
|
||||
export async function getAgentChatContextActivity(params: {
|
||||
teamId: string
|
||||
agentId: string
|
||||
userId?: string
|
||||
}): Promise<AgentExecutionContext> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
@@ -913,6 +915,26 @@ export async function getAgentChatContextActivity(params: {
|
||||
})
|
||||
}
|
||||
|
||||
if (params.userId) {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
const userLevel = getRoleLevel(member?.role)
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel < requiredLevel) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Permission denied: Insufficient role to use agent "${params.agentId}". Minimum required role is "${agent.permission}".`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no provider configured',
|
||||
|
||||
@@ -114,6 +114,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const context = await executeActivity(agentWorkerQueue, getAgentChatContextActivity, {
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userId: payload.agent?.userId,
|
||||
})
|
||||
|
||||
const pathContext = await executeActivity(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
@@ -183,6 +184,63 @@ describe('Agent API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /agents/:agentId/permission', () => {
|
||||
it('updates agent permission when user is admin', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
teamId: 'team1',
|
||||
user: { name: 'Bot 1', image: 'avatar1' },
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission: 'owner',
|
||||
config: {
|
||||
provider: 'prov1',
|
||||
model: 'model1',
|
||||
},
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgentPermission).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/agents/agent1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'owner' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.permission).toBe('owner')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: undefined,
|
||||
permission: 'Admin',
|
||||
type: 'agent',
|
||||
id: 'agent1',
|
||||
})
|
||||
expect(agentService.updateAgentPermission).toHaveBeenCalledWith('agent1', 'owner')
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith({
|
||||
action: 'agent_update',
|
||||
teamId: 'team1',
|
||||
userId: undefined,
|
||||
itemId: 'agent1',
|
||||
})
|
||||
})
|
||||
|
||||
it('denies access when user is not admin', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new HTTPException(403, { message: 'Forbidden' }),
|
||||
)
|
||||
|
||||
const res = await app.request('/agents/agent1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'owner' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /agent-sessions/:sessionId/entries', () => {
|
||||
it('returns entries of agent session if user is admin', async () => {
|
||||
const mockEntries = [
|
||||
|
||||
@@ -6,6 +6,7 @@ import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
updateAgentPermissionRequestSchema,
|
||||
paginationParamsSchema,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
@@ -29,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
const agents = await agentService.listAgents({ teamId, userId: userReq?.id })
|
||||
|
||||
const res: AgentInfo[] = await Promise.all(
|
||||
agents.map(async (agent) => {
|
||||
@@ -39,6 +40,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
permission: agent.permission,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
@@ -83,6 +85,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
permission: agent.permission,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
@@ -137,6 +140,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
permission: agent.permission,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
@@ -154,6 +158,55 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.patch(
|
||||
'/agents/:agentId/permission',
|
||||
zValidator('json', updateAgentPermissionRequestSchema),
|
||||
async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgentPermission(agentId, req.permission)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.agent_update,
|
||||
teamId: agent.teamId,
|
||||
userId: userReq?.id,
|
||||
itemId: agent.id,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
permission: agent.permission,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
},
|
||||
)
|
||||
.delete('/agents/:agentId', async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
@@ -421,4 +421,123 @@ describe('AgentService', () => {
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('agent permissions', () => {
|
||||
test('createAgent with custom permission and updateAgentPermission', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
const agent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Owner Only Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'owner',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
expect(agent?.permission).toBe('owner')
|
||||
|
||||
const updated = await svc.updateAgentPermission(agent!.id, 'editor')
|
||||
expect(updated.permission).toBe('editor')
|
||||
|
||||
const updatedViaUpdateAgent = await svc.updateAgent({
|
||||
agentId: agent!.id,
|
||||
name: 'Owner Only Agent Updated',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(updatedViaUpdateAgent.permission).toBe('reviewer')
|
||||
})
|
||||
|
||||
test('listAgents filters chat agents by requester role when userId is provided', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
// Create 3 chat agents with different permissions
|
||||
const reviewerAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'All Users Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'reviewer',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
const editorAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Editor Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'editor',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
const ownerAgent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Owner Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
permission: 'owner',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
|
||||
// Create 3 test users with different roles in the team
|
||||
const reviewerUser = await db.user.create({
|
||||
data: { name: 'Reviewer User', email: 'rev@shumai.ai' },
|
||||
})
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const editorUser = await db.user.create({
|
||||
data: { name: 'Editor User', email: 'ed@shumai.ai' },
|
||||
})
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: editorUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const ownerUser = await db.user.create({
|
||||
data: { name: 'Owner User', email: 'own@shumai.ai' },
|
||||
})
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: ownerUser.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// Reviewer should only see reviewerAgent
|
||||
const reviewerList = await svc.listAgents({ teamId: team.id, userId: reviewerUser.id })
|
||||
const reviewerAgentIds = reviewerList.map((a) => a.id)
|
||||
expect(reviewerAgentIds).toContain(reviewerAgent!.id)
|
||||
expect(reviewerAgentIds).not.toContain(editorAgent!.id)
|
||||
expect(reviewerAgentIds).not.toContain(ownerAgent!.id)
|
||||
|
||||
// Editor should see reviewerAgent and editorAgent
|
||||
const editorList = await svc.listAgents({ teamId: team.id, userId: editorUser.id })
|
||||
const editorAgentIds = editorList.map((a) => a.id)
|
||||
expect(editorAgentIds).toContain(reviewerAgent!.id)
|
||||
expect(editorAgentIds).toContain(editorAgent!.id)
|
||||
expect(editorAgentIds).not.toContain(ownerAgent!.id)
|
||||
|
||||
// Owner should see all agents
|
||||
const ownerList = await svc.listAgents({ teamId: team.id, userId: ownerUser.id })
|
||||
const ownerAgentIds = ownerList.map((a) => a.id)
|
||||
expect(ownerAgentIds).toContain(reviewerAgent!.id)
|
||||
expect(ownerAgentIds).toContain(editorAgent!.id)
|
||||
expect(ownerAgentIds).toContain(ownerAgent!.id)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAllowedAgentRoles } from './permissions'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
@@ -114,6 +115,7 @@ export class AgentService {
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
permission,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
@@ -179,6 +181,7 @@ export class AgentService {
|
||||
teamId,
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
permission: permission || 'reviewer',
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
@@ -224,6 +227,7 @@ export class AgentService {
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
permission,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
@@ -300,6 +304,7 @@ export class AgentService {
|
||||
data: {
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
...(permission ? { permission } : {}),
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
@@ -327,6 +332,29 @@ export class AgentService {
|
||||
})
|
||||
}
|
||||
|
||||
async updateAgentPermission(agentId: string, permission: 'owner' | 'editor' | 'reviewer') {
|
||||
const existing = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
})
|
||||
if (!existing) throw new Error('agent not found')
|
||||
|
||||
return this.prismaClient.agent.update({
|
||||
where: { id: agentId },
|
||||
data: { permission },
|
||||
include: {
|
||||
user: true,
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
skills: {
|
||||
include: {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
mcpServers: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async getAgent(params: { agentId: string }) {
|
||||
return this.prismaClient.agent.findUnique({
|
||||
where: { id: params.agentId },
|
||||
@@ -349,9 +377,36 @@ export class AgentService {
|
||||
}
|
||||
|
||||
async listAgents(params: ListAgentsParams) {
|
||||
const allowedRoles = params.userId
|
||||
? getAllowedAgentRoles(
|
||||
(
|
||||
await this.prismaClient.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: params.teamId,
|
||||
userId: params.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
)?.role,
|
||||
)
|
||||
: null
|
||||
|
||||
return this.prismaClient.agent.findMany({
|
||||
where: {
|
||||
teamId: params.teamId,
|
||||
...(allowedRoles
|
||||
? {
|
||||
OR: [
|
||||
{ type: { not: 'chat' } },
|
||||
{
|
||||
type: 'chat',
|
||||
permission: { in: allowedRoles },
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: {
|
||||
id: 'desc',
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getRoleLevel, getAgentRequiredLevel, getAllowedAgentRoles } from './permissions'
|
||||
|
||||
describe('agent permission helpers', () => {
|
||||
describe('getRoleLevel', () => {
|
||||
it('maps each role to its level', () => {
|
||||
expect(getRoleLevel('reviewer')).toBe(1)
|
||||
expect(getRoleLevel('editor')).toBe(2)
|
||||
expect(getRoleLevel('owner')).toBe(3)
|
||||
})
|
||||
|
||||
it('resolves missing roles to 0 (fail closed)', () => {
|
||||
expect(getRoleLevel(null)).toBe(0)
|
||||
expect(getRoleLevel(undefined)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAgentRequiredLevel', () => {
|
||||
it('maps each permission to its required level', () => {
|
||||
expect(getAgentRequiredLevel('reviewer')).toBe(1)
|
||||
expect(getAgentRequiredLevel('editor')).toBe(2)
|
||||
expect(getAgentRequiredLevel('owner')).toBe(3)
|
||||
})
|
||||
|
||||
it('defaults missing permissions to reviewer level (1)', () => {
|
||||
expect(getAgentRequiredLevel(null)).toBe(1)
|
||||
expect(getAgentRequiredLevel(undefined)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAllowedAgentRoles', () => {
|
||||
it('returns inclusive role sets per hierarchy', () => {
|
||||
expect(getAllowedAgentRoles('owner')).toEqual(['reviewer', 'editor', 'owner'])
|
||||
expect(getAllowedAgentRoles('editor')).toEqual(['reviewer', 'editor'])
|
||||
expect(getAllowedAgentRoles('reviewer')).toEqual(['reviewer'])
|
||||
})
|
||||
|
||||
it('defaults missing roles to reviewer only', () => {
|
||||
expect(getAllowedAgentRoles(null)).toEqual(['reviewer'])
|
||||
expect(getAllowedAgentRoles(undefined)).toEqual(['reviewer'])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { TeamMemberRole } from '@shumai/db'
|
||||
|
||||
/**
|
||||
* Numeric levels for the team role hierarchy used by agent permissions.
|
||||
* The record is typed exhaustively over `TeamMemberRole`, so adding a new
|
||||
* role to the enum will fail compilation until it is handled here.
|
||||
*/
|
||||
const ROLE_LEVELS: Record<TeamMemberRole, number> = {
|
||||
reviewer: 1,
|
||||
editor: 2,
|
||||
owner: 3,
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric level of a team role for agent-permission comparisons.
|
||||
* Unknown or missing roles resolve to 0, which is below every agent
|
||||
* permission, so lookups fail closed.
|
||||
*/
|
||||
export function getRoleLevel(role: TeamMemberRole | null | undefined): number {
|
||||
if (!role) return 0
|
||||
return ROLE_LEVELS[role] ?? 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum role level required to use an agent with the given permission.
|
||||
* Unknown or missing permissions resolve to 1 (reviewer), the most
|
||||
* permissive default.
|
||||
*/
|
||||
export function getAgentRequiredLevel(permission: TeamMemberRole | null | undefined): number {
|
||||
if (!permission) return 1
|
||||
return ROLE_LEVELS[permission] ?? 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Roles allowed to use agents, following the inclusive role hierarchy:
|
||||
* owner sees owner+editor+reviewer agents, editor sees editor+reviewer,
|
||||
* reviewer (or any unknown/missing role) sees reviewer agents only.
|
||||
*/
|
||||
export function getAllowedAgentRoles(role: TeamMemberRole | null | undefined): TeamMemberRole[] {
|
||||
const level = getRoleLevel(role)
|
||||
if (level >= 3) return ['reviewer', 'editor', 'owner']
|
||||
if (level === 2) return ['reviewer', 'editor']
|
||||
return ['reviewer']
|
||||
}
|
||||
@@ -41,6 +41,13 @@ describe('AssetService', () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'TestTeam_Asset_' + Date.now() },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'TestProject_Asset', teamId: team.id },
|
||||
})
|
||||
@@ -734,15 +741,6 @@ describe('AssetService', () => {
|
||||
attachmentIds: [],
|
||||
})
|
||||
|
||||
// 2. Add user as a team member with owner role (team owner)
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: project.teamId,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
// Create another user
|
||||
const otherUser = await prisma.user.create({
|
||||
data: {
|
||||
@@ -813,16 +811,7 @@ describe('AssetService', () => {
|
||||
it('deleteComment cleans up S3 attachment files and database records', async () => {
|
||||
const { user, project, assets } = await setupBasicAssets()
|
||||
|
||||
// 1. Add user as team owner
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: project.teamId,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Create StorageKey and Asset for attachment
|
||||
// 1. Create StorageKey and Asset for attachment
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'attachments/test-attachment-file.png',
|
||||
@@ -1245,6 +1234,68 @@ describe('AssetService', () => {
|
||||
expect(p3b?.agent?.userId).toBe(user.id)
|
||||
})
|
||||
|
||||
it('silently skips triggering agent workflow when comment creator lacks permission', async () => {
|
||||
const { project } = await setupBasicAssets()
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'perm-file',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
// Create owner-only bot agent
|
||||
const ownerBotUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Owner Bot Agent',
|
||||
type: 'agent',
|
||||
email: `owner-bot-${Date.now()}@shumai.ai`,
|
||||
},
|
||||
})
|
||||
const ownerAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: ownerBotUser.id,
|
||||
teamId: project.teamId,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
})
|
||||
|
||||
// Create a reviewer user
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Reviewer Member',
|
||||
email: `rev-comment-${Date.now()}@shumai.ai`,
|
||||
password: 'pw',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: project.teamId, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Reviewer mentions owner-only agent
|
||||
const comment = await assetService.createComment({
|
||||
assetId: file.id,
|
||||
userId: reviewerUser.id,
|
||||
message: `Hello <@${ownerAgent.id}>`,
|
||||
attachmentIds: [],
|
||||
})
|
||||
|
||||
// Comment was saved successfully
|
||||
expect(comment.id).toBeDefined()
|
||||
|
||||
// But no workflow task was created for ownerAgent
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: file.id,
|
||||
payload: { path: ['agent', 'userCommentId'], equals: comment.id },
|
||||
},
|
||||
})
|
||||
expect(tasks.length).toBe(0)
|
||||
})
|
||||
|
||||
it('updates asset order correctly', async () => {
|
||||
const { user, project } = await setupBasicAssets()
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import { dedupeSymlinksToTarget } from './symlink'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
|
||||
type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: {
|
||||
@@ -1377,30 +1378,49 @@ export class AssetService {
|
||||
const mentionedAgentIds = new Set(botMentionMatches.map((match) => match[1]))
|
||||
const handledAgentIds = new Set<string>()
|
||||
|
||||
const member = a.project?.team
|
||||
? await tx.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: a.project.team.id,
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
: null
|
||||
|
||||
const userLevel = getRoleLevel(member?.role)
|
||||
|
||||
if (parentComment && a.project) {
|
||||
const rootSessionId = parentComment.sessionId
|
||||
const isRootAgent = !!rootSessionId || parentComment.creator?.type === 'agent'
|
||||
const rootAgentId = parentComment.creatorId
|
||||
|
||||
if (isRootAgent && rootAgentId && mentionedAgentIds.has(rootAgentId)) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId: a.project.team.id,
|
||||
projectId: a.project.id,
|
||||
payload: {
|
||||
const rootAgent = await tx.agent.findUnique({ where: { id: rootAgentId } })
|
||||
const requiredLevel = getAgentRequiredLevel(rootAgent?.permission)
|
||||
|
||||
if (userLevel >= requiredLevel) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId: a.project.team.id,
|
||||
projectId: a.project.id,
|
||||
agent: {
|
||||
userCommentId: comment.id,
|
||||
agentId: rootAgentId,
|
||||
sessionId: rootSessionId || undefined,
|
||||
userId: req.userId,
|
||||
payload: {
|
||||
projectId: a.project.id,
|
||||
agent: {
|
||||
userCommentId: comment.id,
|
||||
agentId: rootAgentId,
|
||||
sessionId: rootSessionId || undefined,
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
handledAgentIds.add(rootAgentId)
|
||||
}
|
||||
}
|
||||
@@ -1414,7 +1434,12 @@ export class AssetService {
|
||||
foundAgent = true
|
||||
} else {
|
||||
const agent = await tx.agent.findUnique({ where: { id: agentId } })
|
||||
if (agent) foundAgent = true
|
||||
if (agent) {
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel >= requiredLevel) {
|
||||
foundAgent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundAgent && a.project) {
|
||||
|
||||
@@ -255,6 +255,61 @@ describe('ChatService', () => {
|
||||
expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key')
|
||||
})
|
||||
|
||||
it('should enforce agent permissions in startOrContinueChat', async () => {
|
||||
const { team, project } = await setupBasicData()
|
||||
|
||||
// Create an owner-only agent
|
||||
const ownerAgentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Owner Agent User',
|
||||
email: `owner-agent-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
const ownerAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: ownerAgentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
})
|
||||
|
||||
// Create an editor user and a reviewer user
|
||||
const editorUser = await prisma.user.create({
|
||||
data: { name: 'Editor User', email: `ed-${Date.now()}@shumai.ai`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: editorUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const reviewerUser = await prisma.user.create({
|
||||
data: { name: 'Reviewer User', email: `rev-${Date.now()}@shumai.ai`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Editor trying to chat with owner-only agent should fail
|
||||
await expect(
|
||||
chatService.startOrContinueChat(editorUser, team.id, {
|
||||
agentId: ownerAgent.id,
|
||||
textPrompt: 'test',
|
||||
projectId: project.id,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
|
||||
// Reviewer trying to chat with owner-only agent should fail
|
||||
await expect(
|
||||
chatService.startOrContinueChat(reviewerUser, team.id, {
|
||||
agentId: ownerAgent.id,
|
||||
textPrompt: 'test',
|
||||
projectId: project.id,
|
||||
}),
|
||||
).rejects.toThrow('Permission denied')
|
||||
})
|
||||
|
||||
it('should list sessions of a user and only return chat type sessions', async () => {
|
||||
const { user, team, project } = await setupBasicData()
|
||||
|
||||
@@ -688,6 +743,9 @@ describe('ChatService', () => {
|
||||
const otherUser = await prisma.user.create({
|
||||
data: { name: 'Other User', email: `other-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: otherUser.id, role: 'reviewer' },
|
||||
})
|
||||
const { sessionId } = await chatService.startOrContinueChat(otherUser, team.id, {
|
||||
agentId: 'test-agent-id',
|
||||
textPrompt: 'hello',
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
@@ -281,7 +282,10 @@ export class ChatService {
|
||||
let activeSessionId = passedSessionId
|
||||
|
||||
// Ensure AI agent configuration exists
|
||||
const agent = await tx.agent.findUnique({ where: { id: agentId } })
|
||||
const agent = await tx.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
include: { user: true },
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error(`Agent with ID "${agentId}" not found`)
|
||||
}
|
||||
@@ -289,6 +293,27 @@ export class ChatService {
|
||||
throw new Error(`Agent does not belong to the specified team`)
|
||||
}
|
||||
|
||||
// Check user's permission to use this agent
|
||||
const member = await tx.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId: user.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!member) {
|
||||
throw new Error('User is not a member of the team')
|
||||
}
|
||||
|
||||
const userLevel = getRoleLevel(member.role)
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel < requiredLevel) {
|
||||
throw new Error(
|
||||
`Permission denied: Insufficient role to use agent "${agent.user.name}". Minimum required role is "${agent.permission}".`,
|
||||
)
|
||||
}
|
||||
|
||||
if (activeSessionId) {
|
||||
const sessionExists = await tx.agentSession.findUnique({
|
||||
where: { id: activeSessionId },
|
||||
|
||||
@@ -184,6 +184,115 @@ describe('TeamService', () => {
|
||||
expect(allMembers).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('should filter included agents by agent permission and requester role', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: `owner-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'Permission Team' })
|
||||
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Editor', email: `editor-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: editor.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: `reviewer-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: reviewer.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Create 3 agents with different permissions
|
||||
const botReviewer = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot All Users',
|
||||
email: `bot-rev-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'reviewer',
|
||||
enabled: true,
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: botReviewer.id })
|
||||
|
||||
const botEditor = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot Editor Only',
|
||||
email: `bot-ed-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'editor',
|
||||
enabled: true,
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: botEditor.id })
|
||||
|
||||
const botOwner = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bot Owner Only',
|
||||
email: `bot-own-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
permission: 'owner',
|
||||
enabled: true,
|
||||
config: { provider: 'p', model: 'm' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: botOwner.id })
|
||||
|
||||
// Reviewer should only see botReviewer among agents
|
||||
const reviewerMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: reviewer.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
const reviewerAgentIds = reviewerMembers.filter((m) => m.type === 'agent').map((m) => m.id)
|
||||
expect(reviewerAgentIds).toEqual([botReviewer.id])
|
||||
|
||||
// Editor should see botReviewer and botEditor
|
||||
const editorMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: editor.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
const editorAgentIds = editorMembers.filter((m) => m.type === 'agent').map((m) => m.id)
|
||||
expect(editorAgentIds).toHaveLength(2)
|
||||
expect(editorAgentIds).toContain(botReviewer.id)
|
||||
expect(editorAgentIds).toContain(botEditor.id)
|
||||
expect(editorAgentIds).not.toContain(botOwner.id)
|
||||
|
||||
// Owner should see all 3 agents
|
||||
const ownerMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: owner.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
const ownerAgentIds = ownerMembers.filter((m) => m.type === 'agent').map((m) => m.id)
|
||||
expect(ownerAgentIds).toHaveLength(3)
|
||||
expect(ownerAgentIds).toContain(botReviewer.id)
|
||||
expect(ownerAgentIds).toContain(botEditor.id)
|
||||
expect(ownerAgentIds).toContain(botOwner.id)
|
||||
})
|
||||
|
||||
it('should filter members for project-scoped members', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: `owner-${Date.now()}@example.com`, password: 'pw' },
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ProviderService, providerService } from '@shumai/core/src/provider/prov
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
@@ -188,6 +189,8 @@ export class TeamService {
|
||||
throw new HTTPException(403, { message: 'Requester is not a team member' })
|
||||
}
|
||||
|
||||
const allowedAgentRoles = getAllowedAgentRoles(requester.role)
|
||||
|
||||
const members = await prisma.teamMember.findMany({
|
||||
where: {
|
||||
teamId: req.teamId,
|
||||
@@ -201,6 +204,7 @@ export class TeamService {
|
||||
agent: {
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
permission: { in: allowedAgentRoles },
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "agents" ADD COLUMN "permission" "TeamMemberRole" NOT NULL DEFAULT 'reviewer';
|
||||
@@ -751,6 +751,7 @@ model Agent {
|
||||
user User @relation(fields: [id], references: [id], onDelete: Cascade)
|
||||
type AgentType
|
||||
enabled Boolean @default(true)
|
||||
permission TeamMemberRole @default(reviewer)
|
||||
soul String? @db.Text
|
||||
providerId String? @map("provider_id")
|
||||
provider Provider? @relation("ProviderToAgent", fields: [providerId], references: [id], onDelete: SetNull)
|
||||
|
||||
+3
-3
File diff suppressed because one or more lines are too long
@@ -4003,6 +4003,7 @@ export const AgentScalarFieldEnum = {
|
||||
id: 'id',
|
||||
type: 'type',
|
||||
enabled: 'enabled',
|
||||
permission: 'permission',
|
||||
soul: 'soul',
|
||||
providerId: 'providerId',
|
||||
modelId: 'modelId',
|
||||
|
||||
@@ -522,6 +522,7 @@ export const AgentScalarFieldEnum = {
|
||||
id: 'id',
|
||||
type: 'type',
|
||||
enabled: 'enabled',
|
||||
permission: 'permission',
|
||||
soul: 'soul',
|
||||
providerId: 'providerId',
|
||||
modelId: 'modelId',
|
||||
|
||||
+64
-1
@@ -30,6 +30,7 @@ export type AgentMinAggregateOutputType = {
|
||||
id: string | null
|
||||
type: $Enums.AgentType | null
|
||||
enabled: boolean | null
|
||||
permission: $Enums.TeamMemberRole | null
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
@@ -42,6 +43,7 @@ export type AgentMaxAggregateOutputType = {
|
||||
id: string | null
|
||||
type: $Enums.AgentType | null
|
||||
enabled: boolean | null
|
||||
permission: $Enums.TeamMemberRole | null
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
@@ -54,6 +56,7 @@ export type AgentCountAggregateOutputType = {
|
||||
id: number
|
||||
type: number
|
||||
enabled: number
|
||||
permission: number
|
||||
soul: number
|
||||
providerId: number
|
||||
modelId: number
|
||||
@@ -69,6 +72,7 @@ export type AgentMinAggregateInputType = {
|
||||
id?: true
|
||||
type?: true
|
||||
enabled?: true
|
||||
permission?: true
|
||||
soul?: true
|
||||
providerId?: true
|
||||
modelId?: true
|
||||
@@ -81,6 +85,7 @@ export type AgentMaxAggregateInputType = {
|
||||
id?: true
|
||||
type?: true
|
||||
enabled?: true
|
||||
permission?: true
|
||||
soul?: true
|
||||
providerId?: true
|
||||
modelId?: true
|
||||
@@ -93,6 +98,7 @@ export type AgentCountAggregateInputType = {
|
||||
id?: true
|
||||
type?: true
|
||||
enabled?: true
|
||||
permission?: true
|
||||
soul?: true
|
||||
providerId?: true
|
||||
modelId?: true
|
||||
@@ -179,6 +185,7 @@ export type AgentGroupByOutputType = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled: boolean
|
||||
permission: $Enums.TeamMemberRole
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
@@ -213,6 +220,7 @@ export type AgentWhereInput = {
|
||||
id?: Prisma.StringFilter<"Agent"> | string
|
||||
type?: Prisma.EnumAgentTypeFilter<"Agent"> | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFilter<"Agent"> | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFilter<"Agent"> | $Enums.TeamMemberRole
|
||||
soul?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
@@ -233,6 +241,7 @@ export type AgentOrderByWithRelationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
enabled?: Prisma.SortOrder
|
||||
permission?: Prisma.SortOrder
|
||||
soul?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
@@ -256,6 +265,7 @@ export type AgentWhereUniqueInput = Prisma.AtLeast<{
|
||||
NOT?: Prisma.AgentWhereInput | Prisma.AgentWhereInput[]
|
||||
type?: Prisma.EnumAgentTypeFilter<"Agent"> | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFilter<"Agent"> | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFilter<"Agent"> | $Enums.TeamMemberRole
|
||||
soul?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
@@ -276,6 +286,7 @@ export type AgentOrderByWithAggregationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
enabled?: Prisma.SortOrder
|
||||
permission?: Prisma.SortOrder
|
||||
soul?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
@@ -295,6 +306,7 @@ export type AgentScalarWhereWithAggregatesInput = {
|
||||
id?: Prisma.StringWithAggregatesFilter<"Agent"> | string
|
||||
type?: Prisma.EnumAgentTypeWithAggregatesFilter<"Agent"> | $Enums.AgentType
|
||||
enabled?: Prisma.BoolWithAggregatesFilter<"Agent"> | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleWithAggregatesFilter<"Agent"> | $Enums.TeamMemberRole
|
||||
soul?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
@@ -307,6 +319,7 @@ export type AgentScalarWhereWithAggregatesInput = {
|
||||
export type AgentCreateInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -324,6 +337,7 @@ export type AgentUncheckedCreateInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -339,6 +353,7 @@ export type AgentUncheckedCreateInput = {
|
||||
export type AgentUpdateInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -356,6 +371,7 @@ export type AgentUncheckedUpdateInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -372,6 +388,7 @@ export type AgentCreateManyInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -384,6 +401,7 @@ export type AgentCreateManyInput = {
|
||||
export type AgentUpdateManyMutationInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -394,6 +412,7 @@ export type AgentUncheckedUpdateManyInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -422,6 +441,7 @@ export type AgentCountOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
enabled?: Prisma.SortOrder
|
||||
permission?: Prisma.SortOrder
|
||||
soul?: Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrder
|
||||
@@ -435,6 +455,7 @@ export type AgentMaxOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
enabled?: Prisma.SortOrder
|
||||
permission?: Prisma.SortOrder
|
||||
soul?: Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrder
|
||||
@@ -447,6 +468,7 @@ export type AgentMinOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
type?: Prisma.SortOrder
|
||||
enabled?: Prisma.SortOrder
|
||||
permission?: Prisma.SortOrder
|
||||
soul?: Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrder
|
||||
@@ -667,6 +689,7 @@ export type AgentUncheckedUpdateManyWithoutProviderNestedInput = {
|
||||
export type AgentCreateWithoutUserInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -682,6 +705,7 @@ export type AgentCreateWithoutUserInput = {
|
||||
export type AgentUncheckedCreateWithoutUserInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -713,6 +737,7 @@ export type AgentUpdateToOneWithWhereWithoutUserInput = {
|
||||
export type AgentUpdateWithoutUserInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -728,6 +753,7 @@ export type AgentUpdateWithoutUserInput = {
|
||||
export type AgentUncheckedUpdateWithoutUserInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -743,6 +769,7 @@ export type AgentUncheckedUpdateWithoutUserInput = {
|
||||
export type AgentCreateWithoutTeamInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -759,6 +786,7 @@ export type AgentUncheckedCreateWithoutTeamInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -803,6 +831,7 @@ export type AgentScalarWhereInput = {
|
||||
id?: Prisma.StringFilter<"Agent"> | string
|
||||
type?: Prisma.EnumAgentTypeFilter<"Agent"> | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFilter<"Agent"> | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFilter<"Agent"> | $Enums.TeamMemberRole
|
||||
soul?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
@@ -815,6 +844,7 @@ export type AgentScalarWhereInput = {
|
||||
export type AgentCreateWithoutSkillsInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -831,6 +861,7 @@ export type AgentUncheckedCreateWithoutSkillsInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -861,6 +892,7 @@ export type AgentUpdateToOneWithWhereWithoutSkillsInput = {
|
||||
export type AgentUpdateWithoutSkillsInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -877,6 +909,7 @@ export type AgentUncheckedUpdateWithoutSkillsInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -891,6 +924,7 @@ export type AgentUncheckedUpdateWithoutSkillsInput = {
|
||||
export type AgentCreateWithoutMcpServersInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -907,6 +941,7 @@ export type AgentUncheckedCreateWithoutMcpServersInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -937,6 +972,7 @@ export type AgentUpdateToOneWithWhereWithoutMcpServersInput = {
|
||||
export type AgentUpdateWithoutMcpServersInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -953,6 +989,7 @@ export type AgentUncheckedUpdateWithoutMcpServersInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -967,6 +1004,7 @@ export type AgentUncheckedUpdateWithoutMcpServersInput = {
|
||||
export type AgentCreateWithoutAgentSessionsInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -983,6 +1021,7 @@ export type AgentUncheckedCreateWithoutAgentSessionsInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -1013,6 +1052,7 @@ export type AgentUpdateToOneWithWhereWithoutAgentSessionsInput = {
|
||||
export type AgentUpdateWithoutAgentSessionsInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1029,6 +1069,7 @@ export type AgentUncheckedUpdateWithoutAgentSessionsInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -1043,6 +1084,7 @@ export type AgentUncheckedUpdateWithoutAgentSessionsInput = {
|
||||
export type AgentCreateWithoutModelRefInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1059,6 +1101,7 @@ export type AgentUncheckedCreateWithoutModelRefInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
teamId: string
|
||||
@@ -1099,6 +1142,7 @@ export type AgentUpdateManyWithWhereWithoutModelRefInput = {
|
||||
export type AgentCreateWithoutProviderInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1115,6 +1159,7 @@ export type AgentUncheckedCreateWithoutProviderInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
modelId?: string | null
|
||||
teamId: string
|
||||
@@ -1156,6 +1201,7 @@ export type AgentCreateManyTeamInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
@@ -1167,6 +1213,7 @@ export type AgentCreateManyTeamInput = {
|
||||
export type AgentUpdateWithoutTeamInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1183,6 +1230,7 @@ export type AgentUncheckedUpdateWithoutTeamInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -1198,6 +1246,7 @@ export type AgentUncheckedUpdateManyWithoutTeamInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
@@ -1210,6 +1259,7 @@ export type AgentCreateManyModelRefInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
teamId: string
|
||||
@@ -1221,6 +1271,7 @@ export type AgentCreateManyModelRefInput = {
|
||||
export type AgentUpdateWithoutModelRefInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1237,6 +1288,7 @@ export type AgentUncheckedUpdateWithoutModelRefInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -1252,6 +1304,7 @@ export type AgentUncheckedUpdateManyWithoutModelRefInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -1264,6 +1317,7 @@ export type AgentCreateManyProviderInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
modelId?: string | null
|
||||
teamId: string
|
||||
@@ -1275,6 +1329,7 @@ export type AgentCreateManyProviderInput = {
|
||||
export type AgentUpdateWithoutProviderInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1291,6 +1346,7 @@ export type AgentUncheckedUpdateWithoutProviderInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -1306,6 +1362,7 @@ export type AgentUncheckedUpdateManyWithoutProviderInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -1367,6 +1424,7 @@ export type AgentSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
id?: boolean
|
||||
type?: boolean
|
||||
enabled?: boolean
|
||||
permission?: boolean
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
@@ -1388,6 +1446,7 @@ export type AgentSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensi
|
||||
id?: boolean
|
||||
type?: boolean
|
||||
enabled?: boolean
|
||||
permission?: boolean
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
@@ -1405,6 +1464,7 @@ export type AgentSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensi
|
||||
id?: boolean
|
||||
type?: boolean
|
||||
enabled?: boolean
|
||||
permission?: boolean
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
@@ -1422,6 +1482,7 @@ export type AgentSelectScalar = {
|
||||
id?: boolean
|
||||
type?: boolean
|
||||
enabled?: boolean
|
||||
permission?: boolean
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
@@ -1431,7 +1492,7 @@ export type AgentSelectScalar = {
|
||||
updatedAt?: boolean
|
||||
}
|
||||
|
||||
export type AgentOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "enabled" | "soul" | "providerId" | "modelId" | "teamId" | "config" | "createdAt" | "updatedAt", ExtArgs["result"]["agent"]>
|
||||
export type AgentOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "enabled" | "permission" | "soul" | "providerId" | "modelId" | "teamId" | "config" | "createdAt" | "updatedAt", ExtArgs["result"]["agent"]>
|
||||
export type AgentInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
@@ -1470,6 +1531,7 @@ export type $AgentPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled: boolean
|
||||
permission: $Enums.TeamMemberRole
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
@@ -1913,6 +1975,7 @@ export interface AgentFieldRefs {
|
||||
readonly id: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly type: Prisma.FieldRef<"Agent", 'AgentType'>
|
||||
readonly enabled: Prisma.FieldRef<"Agent", 'Boolean'>
|
||||
readonly permission: Prisma.FieldRef<"Agent", 'TeamMemberRole'>
|
||||
readonly soul: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly providerId: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly modelId: Prisma.FieldRef<"Agent", 'String'>
|
||||
|
||||
@@ -7,6 +7,9 @@ export const agentTypeSchema = z.nativeEnum(AgentType)
|
||||
export const thinkingLevelSchema = z.enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh'])
|
||||
export type ThinkingLevel = z.infer<typeof thinkingLevelSchema>
|
||||
|
||||
export const agentPermissionSchema = z.enum(['owner', 'editor', 'reviewer'])
|
||||
export type AgentPermission = z.infer<typeof agentPermissionSchema>
|
||||
|
||||
export const agentSkillSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
skillId: z.string(),
|
||||
@@ -24,6 +27,7 @@ export const agentInfoSchema = z.object({
|
||||
name: z.string(),
|
||||
type: agentTypeSchema,
|
||||
enabled: z.boolean(),
|
||||
permission: agentPermissionSchema.optional().default('reviewer'),
|
||||
avatar: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
@@ -40,6 +44,7 @@ const baseAgentRequest = z.object({
|
||||
name: z.string().min(1),
|
||||
type: agentTypeSchema,
|
||||
enabled: z.boolean().optional().default(true),
|
||||
permission: agentPermissionSchema.optional(),
|
||||
avatar: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
@@ -91,6 +96,11 @@ export const updateAgentRequestSchema = baseAgentRequest.superRefine((data, ctx)
|
||||
})
|
||||
export type UpdateAgentRequest = z.infer<typeof updateAgentRequestSchema>
|
||||
|
||||
export const updateAgentPermissionRequestSchema = z.object({
|
||||
permission: agentPermissionSchema,
|
||||
})
|
||||
export type UpdateAgentPermissionRequest = z.infer<typeof updateAgentPermissionRequestSchema>
|
||||
|
||||
export interface CreateAgentParams extends CreateAgentRequest {
|
||||
teamId: string
|
||||
}
|
||||
@@ -105,6 +115,7 @@ export interface DeleteAgentParams {
|
||||
|
||||
export interface ListAgentsParams {
|
||||
teamId: string
|
||||
userId?: string
|
||||
}
|
||||
|
||||
export const agentSessionEntrySchema = z.object({
|
||||
|
||||
@@ -140,6 +140,14 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentChat (executo
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: regularUser.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
// Create AgentSession first
|
||||
await prisma.agentSession.create({
|
||||
data: {
|
||||
@@ -284,6 +292,14 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentChat (executo
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: regularUser.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
// Create AgentSession first
|
||||
await prisma.agentSession.create({
|
||||
data: {
|
||||
@@ -418,6 +434,14 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - agentChat (executo
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: regularUser.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.agentSession.create({
|
||||
data: {
|
||||
id: 'vs-session-789',
|
||||
|
||||
@@ -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