mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 23:17:37 +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:
@@ -1512,6 +1512,92 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(val?.stringValue).toBe('Generated using gemini')
|
||||
})
|
||||
|
||||
it('should persist select and selectMulti metadata with dynamic newOption', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'provider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const multiField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'tags',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/new_opt.txt',
|
||||
name: 'new_opt.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
// Verify select field
|
||||
const providerVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(providerVal?.stringValue).toBe('kling')
|
||||
|
||||
// Verify select field config was updated with new option
|
||||
const updatedSelectField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const selectOpts =
|
||||
(updatedSelectField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(selectOpts.some((o) => o.displayName === 'Kling' && o.id === 'kling')).toBe(true)
|
||||
|
||||
// Verify selectMulti field
|
||||
const tagsVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: multiField.key },
|
||||
})
|
||||
expect(tagsVal?.jsonValue).toEqual(['tag1', 'tag-2'])
|
||||
|
||||
// Verify selectMulti field config was updated with new option
|
||||
const updatedMultiField = await prisma.metadataField.findUnique({
|
||||
where: { key: multiField.key },
|
||||
})
|
||||
const multiOpts =
|
||||
(updatedMultiField?.config as PrismaJson.FieldConfig)?.selectMulti?.options || []
|
||||
expect(multiOpts.some((o) => o.displayName === 'Tag 2' && o.id === 'tag-2')).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject metadata with keys that are not valid in this project', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
@@ -1707,6 +1793,71 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using seedance')
|
||||
})
|
||||
|
||||
it('should persist select and selectMulti newOption metadata in create_version', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'versionProvider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Version Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const fileAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: fileAsset.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
metadata: {
|
||||
versionProvider: { newOption: { value: 'Midjourney' } },
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(val?.stringValue).toBe('midjourney')
|
||||
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const opts = (updatedField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(opts.some((o) => o.displayName === 'Midjourney' && o.id === 'midjourney')).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+46
-14
@@ -415,6 +415,22 @@ export interface AutofillField {
|
||||
}
|
||||
|
||||
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
||||
const newOptionSchema = Type.Object(
|
||||
{
|
||||
newOption: Type.Object(
|
||||
{
|
||||
value: Type.String({
|
||||
minLength: 1,
|
||||
description:
|
||||
'The new option display name/value to create and select if none of the existing options match.',
|
||||
}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
const properties: Record<string, TSchema> = {}
|
||||
for (const f of fields) {
|
||||
let schema: TSchema
|
||||
@@ -437,26 +453,42 @@ export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
||||
const options = f.config.select?.options || []
|
||||
const description =
|
||||
options.length > 0
|
||||
? `${baseDescription}\nSelect one option and return the option ID as the value.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
|
||||
: baseDescription
|
||||
schema = Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
description,
|
||||
})
|
||||
? `${baseDescription}\nSelect one existing option ID or provide {"newOption": {"value": "..."}} to create a new option.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
|
||||
: `${baseDescription}\nProvide {"newOption": {"value": "..."}} with the desired option name.`
|
||||
if (options.length > 0) {
|
||||
schema = Type.Union(
|
||||
[
|
||||
Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
}),
|
||||
newOptionSchema,
|
||||
],
|
||||
{ description },
|
||||
)
|
||||
} else {
|
||||
schema = Type.Object(newOptionSchema.properties, {
|
||||
additionalProperties: false,
|
||||
description,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'selectMulti': {
|
||||
const options = f.config.selectMulti?.options || []
|
||||
const description =
|
||||
options.length > 0
|
||||
? `${baseDescription}\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
|
||||
: baseDescription
|
||||
schema = Type.Array(
|
||||
Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
}),
|
||||
{ description },
|
||||
)
|
||||
? `${baseDescription}\nSelect applicable option IDs or provide {"newOption": {"value": "..."}} objects for new options (e.g. ["opt1", {"newOption": {"value": "new_name"}}]).\n\nAvailable options:\n${options.map((o) => `- ${o.displayName} => ${o.id}`).join('\n')}`
|
||||
: `${baseDescription}\nProvide an array of {"newOption": {"value": "..."}} objects for new options.`
|
||||
const itemSchema =
|
||||
options.length > 0
|
||||
? Type.Union([
|
||||
Type.String({
|
||||
enum: options.map((o) => o.id),
|
||||
}),
|
||||
newOptionSchema,
|
||||
])
|
||||
: newOptionSchema
|
||||
schema = Type.Array(itemSchema, { description })
|
||||
break
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
expect(propsOf(schema).f1.anyOf![0].type).toBe('boolean')
|
||||
})
|
||||
|
||||
it('converts select fields with enums and option descriptions', () => {
|
||||
it('converts select fields with enums, newOption support and option descriptions', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
@@ -68,18 +68,40 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
const selectSchema = propsOf(schema).f1.anyOf![0]
|
||||
expect(selectSchema.type).toBe('string')
|
||||
expect(selectSchema.enum).toEqual(['opt1', 'opt2'])
|
||||
expect(selectSchema.anyOf![0].type).toBe('string')
|
||||
expect(selectSchema.anyOf![0].enum).toEqual(['opt1', 'opt2'])
|
||||
expect(selectSchema.anyOf![1].type).toBe('object')
|
||||
expect(selectSchema.description).toBe(
|
||||
"The field 'Species' represents Species of animal.\nSelect one option and return the option ID as the value.\n\nAvailable options:\n- Option 1 => opt1\n- Option 2 => opt2",
|
||||
'The field \'Species\' represents Species of animal.\nSelect one existing option ID or provide {"newOption": {"value": "..."}} to create a new option.\n\nAvailable options:\n- Option 1 => opt1\n- Option 2 => opt2',
|
||||
)
|
||||
// Only the declared option IDs are valid (enforced by the typebox validator)
|
||||
// Declared option IDs, newOption objects, and null are valid
|
||||
expect(Value.Check(schema, { f1: 'opt1' })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: 'opt2' })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: { newOption: { value: 'kling' } } })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
// Arbitrary strings or invalid objects are rejected
|
||||
expect(Value.Check(schema, { f1: 'not-an-option' })).toBe(false)
|
||||
expect(Value.Check(schema, { f1: { newOption: { foo: 'bar' } } })).toBe(false)
|
||||
})
|
||||
|
||||
it('converts selectMulti fields with array enums and option descriptions', () => {
|
||||
it('converts select fields with empty options to newOption schema only', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [] },
|
||||
},
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(Value.Check(schema, { f1: { newOption: { value: 'kling' } } })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: 'any-string' })).toBe(false)
|
||||
})
|
||||
|
||||
it('converts selectMulti fields with array enums, newOption support and option descriptions', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
@@ -98,13 +120,33 @@ describe('fieldsToTypeBoxSchema', () => {
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
const selectMultiSchema = propsOf(schema).f1.anyOf![0]
|
||||
expect(selectMultiSchema.type).toBe('array')
|
||||
expect(selectMultiSchema.items!.enum).toEqual(['opt1', 'opt2'])
|
||||
expect(selectMultiSchema.description).toBe(
|
||||
"The field 'Tags' represents Tags.\nSelect applicable options and return the option IDs as the value.\n\nAvailable options:\n- Tag 1 => opt1\n- Tag 2 => opt2",
|
||||
'The field \'Tags\' represents Tags.\nSelect applicable option IDs or provide {"newOption": {"value": "..."}} objects for new options (e.g. ["opt1", {"newOption": {"value": "new_name"}}]).\n\nAvailable options:\n- Tag 1 => opt1\n- Tag 2 => opt2',
|
||||
)
|
||||
expect(Value.Check(schema, { f1: ['opt1', 'opt2'] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: [{ newOption: { value: 'Tag 3' } }] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: ['opt1', { newOption: { value: 'Tag 3' } }] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: ['opt1', 'bad'] })).toBe(false)
|
||||
expect(Value.Check(schema, { f1: ['opt1', { newOption: { bad: 'value' } }] })).toBe(false)
|
||||
})
|
||||
|
||||
it('converts selectMulti fields with empty options to array of newOption schema', () => {
|
||||
const fields: AutofillField[] = [
|
||||
{
|
||||
id: 'f1',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [] },
|
||||
},
|
||||
},
|
||||
]
|
||||
const schema = fieldsToTypeBoxSchema(fields)
|
||||
expect(Value.Check(schema, { f1: [{ newOption: { value: 'Tag 1' } }] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: [] })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: null })).toBe(true)
|
||||
expect(Value.Check(schema, { f1: ['tag1'] })).toBe(false)
|
||||
})
|
||||
|
||||
it('defaults to string for unknown types', () => {
|
||||
|
||||
@@ -93,6 +93,50 @@ describe('createCreateFileTool', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should forward select and selectMulti newOption metadata', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-new-option.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{
|
||||
id: 'provider',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const tool = createCreateFileTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
data: null,
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
@@ -244,11 +288,18 @@ describe('createCreateFileTool', () => {
|
||||
expect(metaObject.additionalProperties).toBe(false)
|
||||
expect(metaObject.properties.prompt.anyOf[0].type).toBe('string')
|
||||
expect(metaObject.properties.prompt.anyOf[1].type).toBe('null')
|
||||
expect(metaObject.properties.source.anyOf[0].enum).toEqual(['gemini'])
|
||||
expect(metaObject.properties.source.anyOf[0].anyOf[0].enum).toEqual(['gemini'])
|
||||
expect(metaObject.properties.rating.anyOf[0].type).toBe('number')
|
||||
|
||||
// Every field must be present (use null when unknown); unknown keys and bad enums are rejected
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: 'gemini', rating: 5 })).toBe(true)
|
||||
expect(
|
||||
Value.Check(meta, {
|
||||
prompt: 'hello',
|
||||
source: { newOption: { value: 'kling' } },
|
||||
rating: 5,
|
||||
}),
|
||||
).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: null, source: null, rating: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello', source: null, rating: null })).toBe(true)
|
||||
expect(Value.Check(meta, { prompt: 'hello' })).toBe(false)
|
||||
|
||||
@@ -89,6 +89,49 @@ describe('createCreateVersionTool', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should forward select and selectMulti newOption metadata', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-new-option.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{
|
||||
id: 'provider',
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import SelectField from './select-field'
|
||||
@@ -83,5 +83,39 @@ describe('SelectField Component', () => {
|
||||
expect(screen.getByText('abc')).toBeTruthy()
|
||||
// "Add options: abc" button should be hidden
|
||||
expect(screen.queryByText('Add options: abc')).toBeNull()
|
||||
// Type "foo" -> exact match with option id "foo" / displayName "Foo"
|
||||
fireEvent.change(searchInput, { target: { value: 'foo' } })
|
||||
expect(screen.queryByText('Add options: foo')).toBeNull()
|
||||
})
|
||||
|
||||
it('calls API and onSave when adding a new option', async () => {
|
||||
const onSave = vi.fn()
|
||||
const { client } = await import('@/ui/api/client')
|
||||
vi.mocked(client.api.fields[':fieldId'].$put).mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
render(<SelectField value="" config={sampleConfig} fieldId="field_123" onSave={onSave} />)
|
||||
|
||||
const trigger = screen.getByText('Select an option')
|
||||
fireEvent.click(trigger)
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search options...')
|
||||
fireEvent.change(searchInput, { target: { value: 'New Custom Option' } })
|
||||
|
||||
const addBtn = screen.getByText('Add options: New Custom Option')
|
||||
expect(addBtn).toBeTruthy()
|
||||
fireEvent.click(addBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(client.api.fields[':fieldId'].$put).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { fieldId: 'field_123' },
|
||||
}),
|
||||
)
|
||||
expect(onSave).toHaveBeenCalledWith('new-custom-option')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -28,7 +28,9 @@ const SelectField: React.FC<FieldProps<string>> = ({
|
||||
opt.displayName.toLowerCase().includes(trimmedSearch.toLowerCase()),
|
||||
)
|
||||
const hasExactMatch = options.some(
|
||||
(opt: SelectOption) => opt.displayName.trim().toLowerCase() === trimmedSearch.toLowerCase(),
|
||||
(opt: SelectOption) =>
|
||||
opt.displayName.trim().toLowerCase() === trimmedSearch.toLowerCase() ||
|
||||
opt.id.toLowerCase() === trimmedSearch.toLowerCase(),
|
||||
)
|
||||
|
||||
const handleStartEdit = () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import SelectMultiField from './select-multi-field'
|
||||
@@ -79,5 +79,46 @@ describe('SelectMultiField Component', () => {
|
||||
fireEvent.change(searchInput, { target: { value: 'abc' } })
|
||||
expect(screen.getByText('abc')).toBeTruthy()
|
||||
expect(screen.queryByText('Add options: abc')).toBeNull()
|
||||
// Type "foo" -> exact match with option id "foo" / displayName "Foo"
|
||||
fireEvent.change(searchInput, { target: { value: 'foo' } })
|
||||
expect(screen.queryByText('Add options: foo')).toBeNull()
|
||||
})
|
||||
|
||||
it('calls API and onSave when adding a new option in MultiSelect', async () => {
|
||||
const onSave = vi.fn()
|
||||
const { client } = await import('@/ui/api/client')
|
||||
vi.mocked(client.api.fields[':fieldId'].$put).mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
render(
|
||||
<SelectMultiField
|
||||
value={['foo']}
|
||||
config={sampleConfig}
|
||||
fieldId="field_multi_123"
|
||||
onSave={onSave}
|
||||
/>,
|
||||
)
|
||||
|
||||
const trigger = screen.getByText('Foo')
|
||||
fireEvent.click(trigger)
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search options...')
|
||||
fireEvent.change(searchInput, { target: { value: 'New Multi Option' } })
|
||||
|
||||
const addBtn = screen.getByText('Add options: New Multi Option')
|
||||
expect(addBtn).toBeTruthy()
|
||||
fireEvent.click(addBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(client.api.fields[':fieldId'].$put).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { fieldId: 'field_multi_123' },
|
||||
}),
|
||||
)
|
||||
expect(onSave).toHaveBeenCalledWith(['foo', 'new-multi-option'])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -32,7 +32,9 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
opt.displayName.toLowerCase().includes(trimmedSearch.toLowerCase()),
|
||||
)
|
||||
const hasExactMatch = options.some(
|
||||
(opt: SelectOption) => opt.displayName.trim().toLowerCase() === trimmedSearch.toLowerCase(),
|
||||
(opt: SelectOption) =>
|
||||
opt.displayName.trim().toLowerCase() === trimmedSearch.toLowerCase() ||
|
||||
opt.id.toLowerCase() === trimmedSearch.toLowerCase(),
|
||||
)
|
||||
|
||||
// Dynamic calculation for how many items fit in one line
|
||||
|
||||
Reference in New Issue
Block a user