mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 02:19:26 +00:00
feat(agent): support dynamic newOption in select and selectMulti metadata fields (#306)
* feat(webui): redesign select and multi-select metadata fields with search box and dynamic option creation * fix(webui): stabilize select popover placement and preserve field visibility in store * refactor(webui): enforce 2-row collapsed height and whitespace-pre-wrap on LongTextField * feat(agent): support dynamic newOption in select and selectMulti metadata fields * fix(metadata): address code review feedback on selectMulti item validation and WebUI option deduplication
This commit is contained in:
@@ -259,4 +259,294 @@ describe('MetadataService', () => {
|
||||
const multiVal = values.find((v) => v.fieldKey === userMultiField.key)
|
||||
expect(multiVal?.jsonValue).toEqual(multiUserIds)
|
||||
})
|
||||
|
||||
it('should dynamically create new options for select fields and store option id', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'test-team' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'test-project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
project: { connect: { id: project.id } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'ai_provider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'AI Provider',
|
||||
type: 'select',
|
||||
select: {
|
||||
options: [
|
||||
{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' },
|
||||
{ id: 'google', displayName: 'Google', color: '#3b82f6' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 1. Add new option 'Kling AI'
|
||||
await metadataService.updateAssetMetadata(asset.id, [
|
||||
{ key: selectField.key, value: { newOption: { value: 'Kling AI' } } },
|
||||
])
|
||||
|
||||
// Verify option added to field config
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const options = (updatedField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(options).toHaveLength(3)
|
||||
const klingOpt = options.find((o) => o.displayName === 'Kling AI')
|
||||
expect(klingOpt).toBeDefined()
|
||||
expect(klingOpt?.id).toBe('kling-ai')
|
||||
expect(klingOpt?.color).toBeDefined()
|
||||
|
||||
// Verify asset metadata value stores the option ID
|
||||
const val = await prisma.assetMetadataValue.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_fieldKey: {
|
||||
assetId: asset.id,
|
||||
fieldKey: selectField.key,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(val?.stringValue).toBe('kling-ai')
|
||||
|
||||
// 2. Deduplication: passing 'kling ai' case-insensitively should reuse existing 'kling-ai'
|
||||
await metadataService.updateAssetMetadata(asset.id, [
|
||||
{ key: selectField.key, value: { newOption: { value: 'kling ai' } } },
|
||||
])
|
||||
const updatedField2 = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const options2 = (updatedField2?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(options2).toHaveLength(3) // Not 4!
|
||||
})
|
||||
|
||||
it('should dynamically create new options for selectMulti fields and store array of option ids', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'test-team' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'test-project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
project: { connect: { id: project.id } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const selectMultiField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'tags',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: {
|
||||
options: [{ id: 'tag1', displayName: 'Tag 1', color: '#f43f5e' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Pass mixed existing and new option
|
||||
await metadataService.updateAssetMetadata(asset.id, [
|
||||
{
|
||||
key: selectMultiField.key,
|
||||
value: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
])
|
||||
|
||||
// Verify option added to field config
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectMultiField.key },
|
||||
})
|
||||
const options = (updatedField?.config as PrismaJson.FieldConfig)?.selectMulti?.options || []
|
||||
expect(options).toHaveLength(2)
|
||||
const tag2Opt = options.find((o) => o.displayName === 'Tag 2')
|
||||
expect(tag2Opt).toBeDefined()
|
||||
expect(tag2Opt?.id).toBe('tag-2')
|
||||
|
||||
// Verify asset metadata value stores array of IDs
|
||||
const val = await prisma.assetMetadataValue.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_fieldKey: {
|
||||
assetId: asset.id,
|
||||
fieldKey: selectMultiField.key,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(val?.jsonValue).toEqual(['tag1', 'tag-2'])
|
||||
})
|
||||
|
||||
it('should reject invalid newOption value format', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'test-team' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'test-project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
project: { connect: { id: project.id } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'field_opt',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: { name: 'Field Opt', type: 'select' },
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
metadataService.updateAssetMetadata(asset.id, [
|
||||
{ key: selectField.key, value: { newOption: { value: ' ' } } },
|
||||
]),
|
||||
).rejects.toThrow('value must be a non-empty string')
|
||||
})
|
||||
|
||||
it('should handle ID collisions by appending numeric suffix', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'test-team' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'test-project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
project: { connect: { id: project.id } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'collision_test',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Collision Test',
|
||||
type: 'select',
|
||||
select: {
|
||||
options: [
|
||||
{ id: 'kling-ai', displayName: 'Old Kling AI', color: '#f43f5e' },
|
||||
{ id: 'kling-ai-1', displayName: 'Old Kling AI Suffix 1', color: '#3b82f6' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Now adding a new option with different displayName whose slug collides with 'kling-ai'
|
||||
await metadataService.updateAssetMetadata(asset.id, [
|
||||
{ key: selectField.key, value: { newOption: { value: 'Kling AI Unique' } } },
|
||||
])
|
||||
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const options = (updatedField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
const newOpt = options.find((o) => o.displayName === 'Kling AI Unique')
|
||||
expect(newOpt).toBeDefined()
|
||||
expect(newOpt?.id).toBe('kling-ai-unique')
|
||||
|
||||
// Test when baseId and candidateId-1 exist, next should be candidateId-2
|
||||
const collisionField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'collision_base',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Collision Base',
|
||||
type: 'select',
|
||||
select: {
|
||||
options: [
|
||||
{ id: 'custom-tool', displayName: 'First Tool', color: '#f43f5e' },
|
||||
{ id: 'custom-tool-1', displayName: 'Second Tool', color: '#3b82f6' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// displayName is 'Custom Tool' which has baseId 'custom-tool' (not matching display names 'First Tool' / 'Second Tool')
|
||||
await metadataService.updateAssetMetadata(asset.id, [
|
||||
{ key: collisionField.key, value: { newOption: { value: 'Custom Tool' } } },
|
||||
])
|
||||
|
||||
const updatedCollisionField = await prisma.metadataField.findUnique({
|
||||
where: { key: collisionField.key },
|
||||
})
|
||||
const collisionOpts =
|
||||
(updatedCollisionField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
const resolvedNewOpt = collisionOpts.find((o) => o.displayName === 'Custom Tool')
|
||||
expect(resolvedNewOpt).toBeDefined()
|
||||
expect(resolvedNewOpt?.id).toBe('custom-tool-2')
|
||||
})
|
||||
|
||||
it('should reject non-string and non-newOption items in selectMulti array', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'test-team' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'test-project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
project: { connect: { id: project.id } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const selectMultiField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'tags_invalid_items',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Passing invalid items like number or null
|
||||
await expect(
|
||||
metadataService.updateAssetMetadata(asset.id, [
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
{ key: selectMultiField.key, value: ['tag1', 123 as any] },
|
||||
]),
|
||||
).rejects.toThrow('expected string or {newOption}')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,6 +10,36 @@ import { ulid } from 'ulid'
|
||||
import { assetService } from '../asset/asset'
|
||||
import { systemFields } from './system_fields'
|
||||
|
||||
export const FIELD_COLORS = [
|
||||
'#f43f5e', // rose
|
||||
'#ec4899', // pink
|
||||
'#d946ef', // fuchsia
|
||||
'#a855f7', // purple
|
||||
'#8b5cf6', // violet
|
||||
'#6366f1', // indigo
|
||||
'#3b82f6', // blue
|
||||
'#0ea5e9', // sky
|
||||
'#06b6d4', // cyan
|
||||
'#14b8a6', // teal
|
||||
'#10b981', // emerald
|
||||
'#22c55e', // green
|
||||
'#84cc16', // lime
|
||||
'#eab308', // yellow
|
||||
'#f59e0b', // amber
|
||||
'#f97316', // orange
|
||||
'#71717a', // zinc
|
||||
'#64748b', // slate
|
||||
]
|
||||
|
||||
export function getNextOptionColor(existingOptions: PrismaJson.SelectOption[] = []): string {
|
||||
const usedColors = new Set(existingOptions.map((o) => o.color))
|
||||
const available = FIELD_COLORS.filter((c) => !usedColors.has(c))
|
||||
if (available.length > 0) {
|
||||
return available[0]
|
||||
}
|
||||
return FIELD_COLORS[existingOptions.length % FIELD_COLORS.length]
|
||||
}
|
||||
|
||||
export class MetadataService {
|
||||
constructor(private client: typeof prisma = prisma) {}
|
||||
async syncSystemFields(): Promise<void> {
|
||||
@@ -277,6 +307,84 @@ export class MetadataService {
|
||||
await this.updateAssetMetadataInternal(tx, assetId, reqs, allowReadOnly)
|
||||
}
|
||||
|
||||
private async resolveOrCreateOption(
|
||||
client: Prisma.TransactionClient | typeof prisma,
|
||||
field: Prisma.MetadataFieldGetPayload<Record<string, never>>,
|
||||
rawOption: unknown,
|
||||
): Promise<string> {
|
||||
if (
|
||||
typeof rawOption !== 'object' ||
|
||||
rawOption === null ||
|
||||
!('newOption' in rawOption) ||
|
||||
typeof (rawOption as { newOption?: unknown }).newOption !== 'object' ||
|
||||
(rawOption as { newOption?: unknown }).newOption === null
|
||||
) {
|
||||
throw new Error(`Invalid newOption object for field ${field.key}`)
|
||||
}
|
||||
|
||||
const value = (rawOption as { newOption: { value?: unknown } }).newOption.value
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
throw new Error(
|
||||
`Invalid newOption value for field ${field.key}: value must be a non-empty string`,
|
||||
)
|
||||
}
|
||||
|
||||
const trimmedValue = value.trim()
|
||||
const config = (field.config ?? {}) as PrismaJson.FieldConfig
|
||||
const isMulti = config.type === 'selectMulti'
|
||||
const existingOptions: PrismaJson.SelectOption[] =
|
||||
(isMulti ? config.selectMulti?.options : config.select?.options) ?? []
|
||||
|
||||
// 1. Check for case-insensitive match against existing options (id or displayName)
|
||||
const existing = existingOptions.find(
|
||||
(opt) =>
|
||||
opt.id.toLowerCase() === trimmedValue.toLowerCase() ||
|
||||
opt.displayName.toLowerCase() === trimmedValue.toLowerCase(),
|
||||
)
|
||||
if (existing) {
|
||||
return existing.id
|
||||
}
|
||||
|
||||
// 2. Generate slug id
|
||||
let baseId = trimmedValue.toLowerCase().replace(/\s+/g, '-')
|
||||
if (!baseId) {
|
||||
baseId = ulid().toLowerCase()
|
||||
}
|
||||
|
||||
let candidateId = baseId
|
||||
let suffix = 1
|
||||
while (existingOptions.some((opt) => opt.id === candidateId)) {
|
||||
candidateId = `${baseId}-${suffix}`
|
||||
suffix++
|
||||
}
|
||||
|
||||
const newOption: PrismaJson.SelectOption = {
|
||||
id: candidateId,
|
||||
displayName: trimmedValue,
|
||||
color: getNextOptionColor(existingOptions),
|
||||
}
|
||||
|
||||
const updatedOptions = [...existingOptions, newOption]
|
||||
const updatedConfig: PrismaJson.FieldConfig = {
|
||||
...config,
|
||||
name: config.name ?? field.key,
|
||||
type: config.type ?? (isMulti ? 'selectMulti' : 'select'),
|
||||
...(isMulti
|
||||
? { selectMulti: { ...(config.selectMulti ?? {}), options: updatedOptions } }
|
||||
: { select: { ...(config.select ?? {}), options: updatedOptions } }),
|
||||
}
|
||||
|
||||
await client.metadataField.update({
|
||||
where: { key: field.key },
|
||||
data: { config: updatedConfig },
|
||||
})
|
||||
|
||||
// Update in-memory field.config for subsequent iterations in the same transaction
|
||||
field.config = updatedConfig
|
||||
|
||||
return candidateId
|
||||
}
|
||||
|
||||
private async updateAssetMetadataInternal(
|
||||
client: Prisma.TransactionClient | typeof prisma,
|
||||
assetId: string,
|
||||
@@ -293,7 +401,34 @@ export class MetadataService {
|
||||
throw new Error(`Field ${field.key} is read-only`)
|
||||
}
|
||||
|
||||
const value = req.value
|
||||
let value = req.value
|
||||
const config = field?.config as PrismaJson.FieldConfig | null
|
||||
|
||||
if (
|
||||
field &&
|
||||
config?.type === 'select' &&
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'newOption' in value
|
||||
) {
|
||||
value = await this.resolveOrCreateOption(client, field, value)
|
||||
} else if (field && config?.type === 'selectMulti' && Array.isArray(value)) {
|
||||
const resolvedList: string[] = []
|
||||
for (const item of value) {
|
||||
if (typeof item === 'object' && item !== null && 'newOption' in item) {
|
||||
const resolvedId = await this.resolveOrCreateOption(client, field, item)
|
||||
resolvedList.push(resolvedId)
|
||||
} else if (typeof item === 'string') {
|
||||
resolvedList.push(item)
|
||||
} else {
|
||||
throw new Error(
|
||||
`Invalid option value for field ${field.key}: expected string or {newOption}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
value = resolvedList
|
||||
}
|
||||
|
||||
let stringValue: string | null = null
|
||||
let numberValue: number | null = null
|
||||
let booleanValue: boolean | null = null
|
||||
|
||||
Reference in New Issue
Block a user