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:
Yiling-J
2026-08-16 11:16:14 +08:00
committed by GitHub
parent 6d4f62d6f6
commit cb1c1c502b
26 changed files with 1066 additions and 122 deletions
+109
View File
@@ -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' },
+4
View File
@@ -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 },
},
},
],