feat(webui): use project members for asset comment mentions (#315)

* feat(webui): use project members for asset comment mentions

* refactor(project): remove legacy unused bots endpoint and props
This commit is contained in:
Yiling-J
2026-08-16 16:44:50 +08:00
committed by GitHub
parent 55d9596835
commit dd82daf65c
17 changed files with 170 additions and 109 deletions
+69
View File
@@ -264,6 +264,75 @@ describe('project api', () => {
expect(assetService.emptyTrash).toHaveBeenCalledWith('p1')
})
it('GET /projects/:projectId/members', async () => {
vi.mocked(projectService.listProjectMembers).mockResolvedValue([
{
id: 'user1',
name: 'Test User',
role: 'editor',
type: 'human',
},
])
const res = await app.request('/projects/p1/members')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual([
{
id: 'user1',
name: 'Test User',
role: 'editor',
type: 'human',
},
])
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(projectService.listProjectMembers).toHaveBeenCalledWith({
projectId: 'p1',
includeAgents: false,
requesterUserId: 'user1',
})
})
it('GET /projects/:projectId/members?includeAgents=true', async () => {
vi.mocked(projectService.listProjectMembers).mockResolvedValue([
{
id: 'user1',
name: 'Test User',
role: 'editor',
type: 'human',
},
{
id: 'agent1',
name: 'Agent Bot',
role: 'bot',
type: 'agent',
},
])
const res = await app.request('/projects/p1/members?includeAgents=true')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toHaveLength(2)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(projectService.listProjectMembers).toHaveBeenCalledWith({
projectId: 'p1',
includeAgents: true,
requesterUserId: 'user1',
})
})
it('POST /projects/:projectId/members', async () => {
vi.mocked(projectService.addProjectMember).mockResolvedValue(undefined)
-15
View File
@@ -245,21 +245,6 @@ const route = new Hono<{ Variables: { user: User } }>()
})
return c.json(members)
})
.get('/projects/:projectId/bots', async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Project,
id: projectId,
})
// STUB: AgentService is not migrated yet.
return c.json([])
})
.post(
'/projects/:projectId/reparent',
zValidator('json', reparentAssetsRequestSchema),
@@ -194,6 +194,10 @@ describe('ProjectService', () => {
includeAgents: true,
})
expect(allMembers).toHaveLength(2)
const agentMember = allMembers.find((m) => m.id === bot.id)
const humanMember = allMembers.find((m) => m.id === human.id)
expect(agentMember?.type).toBe('agent')
expect(humanMember?.type).toBe('human')
})
it('filters agent bots by the requester effective project role', async () => {
+1
View File
@@ -321,6 +321,7 @@ export class ProjectService {
id: m.user.id,
name: m.user.name,
role: m.role as ProjectUserInfo['role'],
type: m.user.type || undefined,
image: await getAvatarUrl(m.user.image),
scope: m.scope,
hasCustomRole: m.hasCustomRole,
+2 -6
View File
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { UserType } from '@shumai/db/enums'
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
export const createProjectRequestSchema = z.object({
@@ -48,18 +49,13 @@ export const projectUserInfoSchema = z.object({
id: z.string(),
name: z.string(),
role: z.enum(['owner', 'editor', 'reviewer', 'bot', 'unknown']),
type: z.nativeEnum(UserType).optional(),
image: z.string().optional(),
scope: z.enum(['team', 'project']).optional(),
hasCustomRole: z.boolean().optional(),
})
export type ProjectUserInfo = z.infer<typeof projectUserInfoSchema>
export const botInfoSchema = z.object({
id: z.string(),
name: z.string(),
})
export type BotInfo = z.infer<typeof botInfoSchema>
export const recentlyDeletedRequestSchema = z
.object({
assetType: z.string(),
@@ -17,6 +17,7 @@ import {
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import type { AttachmentInfo, CommentInfo, UserInfo } from '@shumai/dtos'
import type { MemberInfo } from '@/ui/stores/members'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Download, File, MoreHorizontal, Trash2 } from 'lucide-react'
import React from 'react'
@@ -36,7 +37,7 @@ interface MessageCardProps {
isReply?: boolean
hasReplies?: boolean
isLastReply?: boolean
getUser: (id: string) => UserInfo
getUser: (id: string) => MemberInfo | UserInfo
onReply: (message: CommentInfo) => void
onViewAttachment: (attachment: AttachmentInfo) => void
isSelected?: boolean
@@ -1,14 +1,12 @@
import type { CommentInfo, PostAttachmentRequest, PostAttachmentResponse } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import type { BotInfo } from '@shumai/dtos'
import type { UserInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { Annotation } from '@/ui/types'
import { useMutation } from '@tanstack/react-query'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
import { Skeleton } from '../ui/skeleton'
import { useMemberStore } from '@/ui/stores/members'
import { useMemberStore, type MemberInfo } from '@/ui/stores/members'
import { useTeamContextStore } from '@/ui/stores/team-context'
import {
ArrowLeft,
@@ -51,7 +49,6 @@ interface ChatInputProps {
) => void
replyingTo?: CommentInfo | null
onCancelReply?: () => void
bots?: BotInfo[]
initialText?: string
hideAnnotationControl?: boolean
disableMentions?: boolean
@@ -74,7 +71,7 @@ const PREDEFINED_COLORS = [
'#ffffff', // White
]
type MentionEntity = { type: 'user'; data: UserInfo } | { type: 'bot'; data: BotInfo }
type MentionEntity = { type: 'user'; data: MemberInfo }
export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
(
@@ -83,7 +80,6 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
onSendMessage,
replyingTo,
onCancelReply,
bots = [],
initialText = '',
hideAnnotationControl = false,
disableMentions = false,
@@ -111,7 +107,12 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
}, [currentTime, frameRate, videoTimeDisplayMode, startTimecode, formatTimestamp])
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const { members: storeMembers, loading: membersLoading, fetchMembers } = useMemberStore()
const {
members: storeMembers,
loading: membersLoading,
fetchMembers,
fetchProjectMembers,
} = useMemberStore()
useEffect(() => {
if (projectId && !teamId) {
@@ -214,16 +215,11 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
}
}, [setIsDrawing])
const filteredAgents = [
...storeMembers
.filter(
(u) => u.type === 'agent' && u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()),
)
.map((u) => ({ type: 'user' as const, data: u })),
...bots
.filter((b) => b.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()))
.map((b) => ({ type: 'bot' as const, data: b })),
]
const filteredAgents = storeMembers
.filter(
(u) => u.type === 'agent' && u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()),
)
.map((u) => ({ type: 'user' as const, data: u }))
const filteredHumans = storeMembers
.filter(
@@ -290,7 +286,9 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
setMentionQuery(query)
setShowMentionList(true)
if (teamId) {
if (projectId) {
fetchProjectMembers(projectId, true, true)
} else if (teamId) {
fetchMembers(teamId, true, true)
}
@@ -1,6 +1,6 @@
import type { AssetInfo, AttachmentInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { UserInfo } from '@shumai/dtos'
import type { MemberInfo } from '@/ui/stores/members'
import { client } from '@/ui/api/client'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
@@ -23,7 +23,7 @@ interface FileViewerRightSidebarProps {
projectId: string
file: AssetInfo | null
onSaveField: (fieldId: string, value: unknown) => void
members: UserInfo[]
members: MemberInfo[]
onCommentSelect?: (comment: CommentInfo) => void
hideAnnotationControl?: boolean
readOnly?: boolean
@@ -78,23 +78,7 @@ export function FileViewerRightSidebar({
enabled: !!projectId && !publicFields,
})
const { data: bots } = useQuery({
queryKey: ['projects', projectId, 'bots'],
queryFn: async () => {
const res = await client.api.projects[':projectId'].bots.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch bots')
return await res.json()
},
enabled: !!projectId && !readOnly,
})
const viewerDef = getViewerForFile(file)
const isAiEnabled = !!viewerDef?.commentsConfig?.hasAiBots
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const enabledBots = isAiEnabled ? (bots as any[]) || [] : []
useEffect(() => {
if (publicFields) {
@@ -280,20 +264,12 @@ export function FileViewerRightSidebar({
}
}
const getUser = (id: string): UserInfo => {
const getUser = (id: string): MemberInfo => {
const member = members.find((m) => m.id === id)
if (member) {
return member
}
if (bots) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bot = (bots as any[]).find((b) => b.id === id)
if (bot) {
return { id: bot.id, name: bot.name, role: 'bot' }
}
}
return {
id: 'unknown',
name: 'Unknown',
@@ -417,7 +393,6 @@ export function FileViewerRightSidebar({
onSendMessage={handleSendMessage}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
bots={enabledBots}
hideAnnotationControl={hideAnnotationControl}
disableMentions={isPublic}
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
@@ -1,29 +1,29 @@
import { client } from '@/ui/api/client'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
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,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Switch } from '@/ui/components/ui/switch'
import { usePermissions } from '@/ui/hooks/use-permissions'
@@ -32,16 +32,16 @@ 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,
Bot,
ChevronDown,
Cpu,
Loader2,
MessageSquare,
MoreVertical,
Plus,
Puzzle,
Trash2,
Zap,
} from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
@@ -9,6 +9,5 @@ export const defaultTypeDefinition: FileTypeDefinition = {
commentsConfig: {
hasTimestamp: false,
hasAnnotations: false,
hasAiBots: false,
},
}
@@ -11,6 +11,5 @@ export const imageTypeDefinition: FileTypeDefinition = {
commentsConfig: {
hasTimestamp: false,
hasAnnotations: true,
hasAiBots: true,
},
}
@@ -9,7 +9,6 @@ export const pdfTypeDefinition: FileTypeDefinition = {
commentsConfig: {
hasTimestamp: true,
hasAnnotations: true,
hasAiBots: true,
formatTimestamp: (second: number) => `P${Math.round(second)}`,
},
}
@@ -50,7 +50,6 @@ export interface FileTypeDefinition {
commentsConfig?: {
hasTimestamp?: boolean
hasAnnotations?: boolean
hasAiBots?: boolean
formatTimestamp?: (second: number) => string
}
}
@@ -11,6 +11,5 @@ export const videoTypeDefinition: FileTypeDefinition = {
commentsConfig: {
hasTimestamp: true,
hasAnnotations: true,
hasAiBots: true,
},
}
@@ -78,7 +78,6 @@ export interface FileTypeDefinition {
commentsConfig?: {
hasTimestamp?: boolean; // Enables timestamped comments
hasAnnotations?: boolean; // Enables annotation drawing canvas
hasAiBots?: boolean; // Enables metadata/autofill AI bots
};
}
```
@@ -179,7 +178,6 @@ export const audioTypeDefinition: FileTypeDefinition = {
commentsConfig: {
hasTimestamp: true,
hasAnnotations: false,
hasAiBots: false,
},
}
```
@@ -88,17 +88,17 @@ function FileViewPage() {
},
})
const queryClient = useQueryClient()
const { members, fetchMembers } = useMemberStore()
const { members, fetchProjectMembers } = useMemberStore()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
useEffect(() => {
if (teamId) {
fetchMembers(teamId, true)
if (projectId) {
fetchProjectMembers(projectId, true)
}
}, [teamId, fetchMembers])
}, [projectId, fetchProjectMembers])
const {
data: stackData,
+42 -3
View File
@@ -2,14 +2,22 @@ import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
import { client } from '@/ui/api/client'
import type { UserInfo } from '@shumai/dtos'
import type { UserInfo, ProjectUserInfo } from '@shumai/dtos'
export type MemberInfo = UserInfo | ProjectUserInfo
interface MemberState {
members: UserInfo[]
members: MemberInfo[]
loadedTeamId?: string
loadedProjectId?: string
loadedWithAgents?: boolean
loading: boolean
fetchMembers: (teamId: string, includeAgents?: boolean, force?: boolean) => Promise<void>
fetchProjectMembers: (
projectId: string,
includeAgents?: boolean,
force?: boolean,
) => Promise<void>
}
export const useMemberStore = create<MemberState>()(
@@ -31,8 +39,39 @@ export const useMemberStore = create<MemberState>()(
if (!res.ok) throw new Error('failed to fetch members')
const members = await res.json()
set({
members: (members as UserInfo[]) || [],
members: (members as MemberInfo[]) || [],
loadedTeamId: teamId,
loadedProjectId: undefined,
loadedWithAgents: includeAgents,
loading: false,
})
} catch {
set({
loading: false,
})
}
},
fetchProjectMembers: async (projectId, includeAgents, force) => {
if (
!force &&
get().loadedProjectId === projectId &&
get().loadedWithAgents === includeAgents
) {
return
}
set({ loading: true })
try {
const res = await client.api.projects[':projectId'].members.$get({
param: { projectId: projectId },
query: { includeAgents: includeAgents ? 'true' : 'false' },
})
if (!res.ok) throw new Error('failed to fetch project members')
const members = await res.json()
set({
members: (members as MemberInfo[]) || [],
loadedProjectId: projectId,
loadedTeamId: undefined,
loadedWithAgents: includeAgents,
loading: false,
})