mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 22:09:24 +00:00
feat(agent): store preset avatars as real files in s3 storage (#381)
* feat(agent): store preset avatars as real files in s3 storage * fix(agent): use inline base64 previews in dialog and remove static avatar files * feat(agent): add 4 avatar presets and track avatarPreset in agent config * refactor(agent): consolidate preset avatar base64 data in dtos
This commit is contained in:
@@ -11,6 +11,7 @@ import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { migrateLegacyAgentAvatars } from '@shumai/core/src/agent/migration'
|
||||
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
import { authService } from '@shumai/core/src/auth/auth'
|
||||
@@ -51,6 +52,7 @@ async function run() {
|
||||
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
await migrateLegacyAgentAvatars().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
|
||||
@@ -257,6 +257,107 @@ describe('AgentService', () => {
|
||||
expect(updated.user.image).toBe('files/01JK23456789ABCDEF01234567')
|
||||
})
|
||||
|
||||
test('Create and Update Agent with Preset Avatars', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
// 1. Create with specific preset avatar
|
||||
const agent2 = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Agent Preset 2',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
avatar: 'avatar-2',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(agent2!.user.image).toMatch(/^files\/[A-Z0-9]{26}\.webp$/)
|
||||
expect((agent2!.config as unknown as PrismaJson.AgentConfig).avatarPreset).toBe('avatar-2')
|
||||
const initialKey = agent2!.user.image
|
||||
|
||||
// 2. Create without avatar (should default to avatar-1)
|
||||
const agentDefault = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Agent Default',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(agentDefault!.user.image).toMatch(/^files\/[A-Z0-9]{26}\.webp$/)
|
||||
expect((agentDefault!.config as unknown as PrismaJson.AgentConfig).avatarPreset).toBe(
|
||||
'avatar-1',
|
||||
)
|
||||
|
||||
const agentInfo = await svc.toAgentInfo(agentDefault!)
|
||||
expect(agentInfo.avatarPreset).toBe('avatar-1')
|
||||
|
||||
// 3. Update agent with a different preset avatar
|
||||
const updatedPreset = await svc.updateAgent({
|
||||
agentId: agent2!.id,
|
||||
name: 'Agent Preset 3',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
avatar: 'avatar-3',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(updatedPreset.user.image).toMatch(/^files\/[A-Z0-9]{26}\.webp$/)
|
||||
expect(updatedPreset.user.image).not.toBe(initialKey)
|
||||
expect((updatedPreset.config as unknown as PrismaJson.AgentConfig).avatarPreset).toBe(
|
||||
'avatar-3',
|
||||
)
|
||||
|
||||
// 3b. Update agent with the SAME preset avatar (should preserve image key without re-upload)
|
||||
const keyBeforeSameUpdate = updatedPreset.user.image
|
||||
const updatedSamePreset = await svc.updateAgent({
|
||||
agentId: agent2!.id,
|
||||
name: 'Agent Same Preset 3',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
avatar: 'avatar-3',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(updatedSamePreset.user.image).toBe(keyBeforeSameUpdate)
|
||||
expect((updatedSamePreset.config as unknown as PrismaJson.AgentConfig).avatarPreset).toBe(
|
||||
'avatar-3',
|
||||
)
|
||||
|
||||
// 4. Update with presigned URL containing .webp extension
|
||||
const updatedPresigned = await svc.updateAgent({
|
||||
agentId: agent2!.id,
|
||||
name: 'Agent Presigned',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
avatar: 'https://shumai.s3.amazonaws.com/files/01JK23456789ABCDEF01234567.webp?foo=bar',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(updatedPresigned.user.image).toBe('files/01JK23456789ABCDEF01234567.webp')
|
||||
expect(
|
||||
(updatedPresigned.config as unknown as PrismaJson.AgentConfig).avatarPreset,
|
||||
).toBeUndefined()
|
||||
|
||||
// 5. Update without avatar specified (avatar undefined) - preserves image
|
||||
const updatedWithoutAvatar = await svc.updateAgent({
|
||||
agentId: agent2!.id,
|
||||
name: 'Agent Without Avatar Change',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
thinkingLevel: 'off',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
})
|
||||
expect(updatedWithoutAvatar.user.image).toBe('files/01JK23456789ABCDEF01234567.webp')
|
||||
})
|
||||
|
||||
test('Delete Agent', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
@@ -18,6 +18,8 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { getAllowedAgentRoles } from './permissions'
|
||||
import { ulid } from 'ulid'
|
||||
import { isPresetAvatarId, getPresetAvatarBuffer } from './presets'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
@@ -47,7 +49,7 @@ interface AgentInfoSource {
|
||||
|
||||
function extractS3Key(urlOrKey?: string | null): string | null | undefined {
|
||||
if (!urlOrKey) return urlOrKey
|
||||
const match = urlOrKey.match(/files\/[A-Z0-9]{26}/)
|
||||
const match = urlOrKey.match(/files\/[A-Z0-9]{26}(\.[a-zA-Z0-9]+)?/)
|
||||
return match ? match[0] : urlOrKey
|
||||
}
|
||||
|
||||
@@ -178,6 +180,23 @@ export class AgentService {
|
||||
}
|
||||
}
|
||||
|
||||
const targetAvatar = avatar || 'avatar-1'
|
||||
let avatarPreset: string | undefined
|
||||
let imageKey: string | null | undefined
|
||||
|
||||
if (isPresetAvatarId(targetAvatar)) {
|
||||
avatarPreset = targetAvatar
|
||||
const buffer = getPresetAvatarBuffer(targetAvatar)
|
||||
if (buffer) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = `files/${ulid()}.webp`
|
||||
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
|
||||
imageKey = key
|
||||
}
|
||||
} else {
|
||||
imageKey = extractS3Key(avatar)
|
||||
}
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
const team = await tx.team.findUnique({
|
||||
where: { id: teamId },
|
||||
@@ -190,6 +209,7 @@ export class AgentService {
|
||||
thinkingLevel,
|
||||
systemPrompt,
|
||||
deniedTools: deniedTools || [],
|
||||
avatarPreset,
|
||||
}
|
||||
|
||||
const user = await tx.user.create({
|
||||
@@ -197,7 +217,7 @@ export class AgentService {
|
||||
name,
|
||||
email: `agent-${Date.now()}-${Math.random().toString(36).substring(7)}@shumai.ai`,
|
||||
type: 'agent',
|
||||
image: extractS3Key(avatar),
|
||||
image: imageKey,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -298,12 +318,41 @@ export class AgentService {
|
||||
}
|
||||
}
|
||||
|
||||
const currentConfig = (agent.config as unknown as PrismaJson.AgentConfig) || {}
|
||||
let newAvatarPreset: string | undefined = currentConfig.avatarPreset
|
||||
let imageKey: string | null | undefined
|
||||
|
||||
if (avatar !== undefined) {
|
||||
if (!avatar) {
|
||||
imageKey = null
|
||||
newAvatarPreset = undefined
|
||||
} else if (isPresetAvatarId(avatar)) {
|
||||
if (avatar === currentConfig.avatarPreset && agent.user.image) {
|
||||
imageKey = agent.user.image
|
||||
newAvatarPreset = avatar
|
||||
} else {
|
||||
const buffer = getPresetAvatarBuffer(avatar)
|
||||
if (buffer) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const key = `files/${ulid()}.webp`
|
||||
await s3Service.putObject(bucket, key, buffer, buffer.length, 'image/webp')
|
||||
imageKey = key
|
||||
newAvatarPreset = avatar
|
||||
}
|
||||
}
|
||||
} else {
|
||||
imageKey = extractS3Key(avatar)
|
||||
newAvatarPreset = undefined
|
||||
}
|
||||
}
|
||||
|
||||
const agentConfig: PrismaJson.AgentConfig = {
|
||||
provider: providerId || '',
|
||||
model: modelId || '',
|
||||
thinkingLevel,
|
||||
systemPrompt,
|
||||
deniedTools: deniedTools || [],
|
||||
avatarPreset: newAvatarPreset,
|
||||
}
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
@@ -311,7 +360,7 @@ export class AgentService {
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
name,
|
||||
image: extractS3Key(avatar),
|
||||
...(imageKey !== undefined ? { image: imageKey } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -415,6 +464,7 @@ export class AgentService {
|
||||
enabled: agent.enabled,
|
||||
permission: agent.permission,
|
||||
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
|
||||
avatarPreset: config.avatarPreset,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { migrateLegacyAgentAvatars } from './migration'
|
||||
import { getPresetAvatarBuffer } from './presets'
|
||||
|
||||
describe('migrateLegacyAgentAvatars', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('returns 0 when no legacy agents exist', async () => {
|
||||
const result = await migrateLegacyAgentAvatars(prisma)
|
||||
expect(result).toEqual({ migrated: 0, errors: 0 })
|
||||
})
|
||||
|
||||
it('migrates legacy agent base64 avatars to S3', async () => {
|
||||
const presetBase64 =
|
||||
'data:image/webp;base64,' + getPresetAvatarBuffer('avatar-1')!.toString('base64')
|
||||
const customBase64 =
|
||||
'data:image/webp;base64,UklGRtInAABXRUJQVlA4IMYnAACwmACdASosASwBPm0ylUekIyIhp1L7UIANiWVu3P6nGjxxkZZTIvmXwJRUeg/Jf+ndPZ0L4H6mVI3YJ/D/tH5j9vT9C/6f3AP1d/Xz+79l/zDfsj6yP+59R39j/y/sAf3r/VdZ36EXly+0Z+6/peaqTMC4q/u/7z45+fr5VuB3l+xvUg7u/5f+G9tH9D3q/Lv/a9Qj25/vvGH2lFyP2J9gX3F+8f9H1AfzfM/+G/0nsBfrb/0PZDvp/yf/H9gP+nf4j9lPeL/2PKX+yf8H2F/6D1Of3o9pv9uzXj2UCILxSqTJtnLrjF0IFB27Vo5QPaRJKEf73CFDiYb46kQh9ZimTAfOlbMytbJDx1VHoVO115vAHuMthHxJoOL/D/OOWk7DrZTEtbvTiXzvmXoZSFox8u7pVGZ4TmovMKAMAZtbdgS8p6MNEYUl2x4pPMe0bPqCNISczDauiMeOe/Bgos4oXilTgIe/4FB/KBRUIV0FiVRnmPndzO7QLVRnyoYI+oKPA/heN/n2wfElNcnOExdS6iaO/IIjkYWljnuIe8akKIWAkomDcGMr2fPIiNFXCNFxgRCTPFdGc+T/b2dMMLNdN3KjGjeGMzQe4UURLfl5oiFEw5Pu5y0fFhDnYhvS7Ezpsb54rvwP+ycBblMc5VRkMxpWgi7zlkUUOIzcsp8rJvOWHryMg36mIXa1xMNyp2rhlY3Vgul9+8VfT412zRHaz12VW/qh9l67/CDtCsnUBGO/e8J1mT9RAmfZTCKX+ecvAjhxyIeUEAg5olYzZSkgLNrAf+HFBHtihqoNZNUgRB+NKEfWCXPqAmsILE+/Ap/wD2FlHj0Q1Qk8PrAN9C/fyX/qgkJyQGu9cAmoYwicMlikN4oRxsA6WckScktHrWfdZYT6WV2xwpPXzy/IJL7TEXpY+W9Lwn/I3P8+q9N+d895Qu4TZMfUfou353e8Wn2UzcHQsKMI7fIZiW7QHhpYTgN41QTiY3CdoGpCOjBJ7cGZrYCpm3XGz2+FBkc1si2VAiuYI/4iWRjeO/MM28I+Qr93kQ+fpnyeMMsvk845A7+37z9M5b/IfOo2z+AywfCalW3nlFXyjVqphG4zq1Xe+FQmMjC8S8JNRMUDEfQnkEcCL/+cd6RkDsj4HAwG6VD3D23XacpKJf4/D1B/f+0v/cJrVvKEknKLNw1nz2gX7HKcAWB0Z+QZDp7Y2FkMAG17AnNVYSAqW7/xgalH6qTLexWRu6LYJVIdLLlriLzZOZlqvIXvawsT1GexNoi/OPUEgSlmUbNHEFe+NtoSuKzV0DgE0k3NXU8Fjjc/oeJL0J+XplQFqXhYg+r4yDOGN7h7xxyUm7IeUiDRLK9MkyQ7b+tRIUVg6pxhKRwj0r34SPFDlMWxhsfO/fYmq/5FbsACkYPysdQAjJzNqbbmX5A7OyZ0Y85gjBVDNHWMZswj7HJVofro0VpmGWUdzLSs/aBF0o2xNxcUdxqeqUFURISYHaX8Jx0ONcwIGQH3EperfP7ZiOxEKrot1BjTcWvYQ4LD4XkTAa+16dp5x4svp1Pp8/U5IGXD+WZAhpxIA+JaP16povKRq9O4hiZQyExaNml6lrO0G/olTvRSc9nq/PybXAw5uYhRIvclmBM27AAA='
|
||||
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Legacy Agent Preset',
|
||||
email: `legacy-preset-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
image: presetBase64,
|
||||
},
|
||||
})
|
||||
|
||||
const customAgentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Legacy Agent Custom',
|
||||
email: `legacy-custom-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
image: customBase64,
|
||||
},
|
||||
})
|
||||
|
||||
const humanUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Human User',
|
||||
email: `human-${Date.now()}@shumai.ai`,
|
||||
type: 'human',
|
||||
image: customBase64,
|
||||
},
|
||||
})
|
||||
|
||||
const modernAgentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Modern Agent',
|
||||
email: `modern-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
image: 'files/existing-key.webp',
|
||||
},
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Test Team' },
|
||||
})
|
||||
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: {
|
||||
provider: 'p',
|
||||
model: 'm',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: customAgentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: {
|
||||
provider: 'p',
|
||||
model: 'm',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const result = await migrateLegacyAgentAvatars(prisma)
|
||||
expect(result).toEqual({ migrated: 2, errors: 0 })
|
||||
|
||||
const updatedAgent = await prisma.user.findUnique({
|
||||
where: { id: agentUser.id },
|
||||
})
|
||||
expect(updatedAgent?.image).toMatch(/^files\/[A-Z0-9]{26}\.webp$/)
|
||||
|
||||
const updatedAgentRecord = await prisma.agent.findUnique({
|
||||
where: { id: agentUser.id },
|
||||
})
|
||||
expect((updatedAgentRecord?.config as unknown as PrismaJson.AgentConfig)?.avatarPreset).toBe(
|
||||
'avatar-1',
|
||||
)
|
||||
|
||||
const updatedCustomAgent = await prisma.user.findUnique({
|
||||
where: { id: customAgentUser.id },
|
||||
})
|
||||
expect(updatedCustomAgent?.image).toMatch(/^files\/[A-Z0-9]{26}\.webp$/)
|
||||
|
||||
const updatedCustomAgentRecord = await prisma.agent.findUnique({
|
||||
where: { id: customAgentUser.id },
|
||||
})
|
||||
expect(
|
||||
(updatedCustomAgentRecord?.config as unknown as PrismaJson.AgentConfig)?.avatarPreset,
|
||||
).toBeUndefined()
|
||||
|
||||
const updatedHuman = await prisma.user.findUnique({
|
||||
where: { id: humanUser.id },
|
||||
})
|
||||
expect(updatedHuman?.image).toBe(customBase64)
|
||||
|
||||
const updatedModern = await prisma.user.findUnique({
|
||||
where: { id: modernAgentUser.id },
|
||||
})
|
||||
expect(updatedModern?.image).toBe('files/existing-key.webp')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { ulid } from 'ulid'
|
||||
import { PRESET_AVATAR_IDS, getPresetAvatarBuffer } from './presets'
|
||||
|
||||
export async function migrateLegacyAgentAvatars(
|
||||
client: typeof prisma = prisma,
|
||||
): Promise<{ migrated: number; errors: number }> {
|
||||
const legacyUsers = await client.user.findMany({
|
||||
where: {
|
||||
type: 'agent',
|
||||
image: {
|
||||
startsWith: 'data:',
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
image: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (legacyUsers.length === 0) {
|
||||
return { migrated: 0, errors: 0 }
|
||||
}
|
||||
|
||||
logger.info({ count: legacyUsers.length }, 'Starting migration of legacy agent avatars to S3')
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
let migrated = 0
|
||||
let errors = 0
|
||||
|
||||
for (const user of legacyUsers) {
|
||||
try {
|
||||
if (!user.image) continue
|
||||
|
||||
const match = user.image.match(/^data:([^;]+);base64,(.+)$/)
|
||||
let buffer: Buffer
|
||||
let contentType = 'image/webp'
|
||||
let ext = 'webp'
|
||||
|
||||
if (match) {
|
||||
contentType = match[1]
|
||||
buffer = Buffer.from(match[2], 'base64')
|
||||
const subtype = contentType.split('/')[1]
|
||||
if (subtype) ext = subtype
|
||||
} else {
|
||||
const commaIdx = user.image.indexOf(',')
|
||||
const rawBase64 = commaIdx !== -1 ? user.image.slice(commaIdx + 1) : user.image
|
||||
buffer = Buffer.from(rawBase64, 'base64')
|
||||
}
|
||||
|
||||
let matchedPresetId: string | undefined
|
||||
for (const id of PRESET_AVATAR_IDS) {
|
||||
const presetBuf = getPresetAvatarBuffer(id)
|
||||
if (presetBuf && buffer.equals(presetBuf)) {
|
||||
matchedPresetId = id
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const key = `files/${ulid()}.${ext}`
|
||||
await s3Service.putObject(bucket, key, buffer, buffer.length, contentType)
|
||||
|
||||
await client.user.update({
|
||||
where: { id: user.id },
|
||||
data: { image: key },
|
||||
})
|
||||
|
||||
if (matchedPresetId) {
|
||||
const agent = await client.agent.findUnique({
|
||||
where: { id: user.id },
|
||||
select: { config: true },
|
||||
})
|
||||
if (agent) {
|
||||
const currentConfig = (agent.config as unknown as PrismaJson.AgentConfig) || {}
|
||||
await client.agent.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
config: {
|
||||
...currentConfig,
|
||||
avatarPreset: matchedPresetId,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
migrated++
|
||||
logger.info(
|
||||
{ userId: user.id, key, avatarPreset: matchedPresetId },
|
||||
'Successfully migrated agent avatar to S3',
|
||||
)
|
||||
} catch (err: unknown) {
|
||||
errors++
|
||||
logger.error({ userId: user.id, err }, 'Failed to migrate legacy agent avatar')
|
||||
}
|
||||
}
|
||||
|
||||
logger.info({ migrated, errors }, 'Completed migration of legacy agent avatars')
|
||||
return { migrated, errors }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
getPresetAvatarBuffer,
|
||||
isPresetAvatarId,
|
||||
PRESET_AVATAR_IDS,
|
||||
type PresetAvatarId,
|
||||
} from './presets'
|
||||
|
||||
describe('agent presets', () => {
|
||||
it('identifies preset avatar IDs correctly', () => {
|
||||
expect(PRESET_AVATAR_IDS).toHaveLength(8)
|
||||
for (const id of PRESET_AVATAR_IDS) {
|
||||
expect(isPresetAvatarId(id)).toBe(true)
|
||||
}
|
||||
expect(isPresetAvatarId('avatar-999')).toBe(false)
|
||||
expect(isPresetAvatarId('')).toBe(false)
|
||||
expect(isPresetAvatarId(null)).toBe(false)
|
||||
expect(isPresetAvatarId(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns valid buffer for all preset avatars', () => {
|
||||
for (const id of PRESET_AVATAR_IDS) {
|
||||
const buf = getPresetAvatarBuffer(id)
|
||||
expect(buf).toBeInstanceOf(Buffer)
|
||||
expect(buf?.length).toBeGreaterThan(5000)
|
||||
}
|
||||
expect(getPresetAvatarBuffer('unknown' as PresetAvatarId)).toBeNull()
|
||||
})
|
||||
|
||||
it('provides AVAILABLE_AVATARS with 8 previews via dtos', async () => {
|
||||
const { AVAILABLE_AVATARS } = await import('@shumai/dtos')
|
||||
expect(AVAILABLE_AVATARS).toHaveLength(8)
|
||||
for (const avatar of AVAILABLE_AVATARS) {
|
||||
expect(avatar.id).toMatch(/^avatar-[1-8]$/)
|
||||
expect(avatar.preview).toMatch(/^data:image\/webp;base64,/)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import {
|
||||
PRESET_AVATAR_IDS,
|
||||
type PresetAvatarId,
|
||||
isPresetAvatarId,
|
||||
PRESET_AVATAR_BASE64,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
export { PRESET_AVATAR_IDS, type PresetAvatarId, isPresetAvatarId }
|
||||
|
||||
const bufferCache = new Map<PresetAvatarId, Buffer>()
|
||||
|
||||
export function getPresetAvatarBuffer(id: PresetAvatarId): Buffer | null {
|
||||
const cached = bufferCache.get(id)
|
||||
if (cached) return cached
|
||||
|
||||
const b64 = PRESET_AVATAR_BASE64[id]
|
||||
if (!b64) return null
|
||||
|
||||
const buf = Buffer.from(b64, 'base64')
|
||||
bufferCache.set(id, buf)
|
||||
return buf
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { getAvatarUrl } from './avatar'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
|
||||
describe('getAvatarUrl', () => {
|
||||
it('returns undefined when imageKeyOrUrl is falsy', async () => {
|
||||
expect(await getAvatarUrl(null)).toBeUndefined()
|
||||
expect(await getAvatarUrl(undefined)).toBeUndefined()
|
||||
expect(await getAvatarUrl('')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns http/https URLs directly', async () => {
|
||||
expect(await getAvatarUrl('http://example.com/avatar.png')).toBe(
|
||||
'http://example.com/avatar.png',
|
||||
)
|
||||
expect(await getAvatarUrl('https://example.com/avatar.png')).toBe(
|
||||
'https://example.com/avatar.png',
|
||||
)
|
||||
})
|
||||
|
||||
it('presigns S3 keys', async () => {
|
||||
const presignSpy = vi
|
||||
.spyOn(s3Service, 'presign')
|
||||
.mockResolvedValue('http://s3.local/presigned-url')
|
||||
const url = await getAvatarUrl('files/01JXYZ1234567890ABCDEFGHJK.webp')
|
||||
expect(url).toBe('http://s3.local/presigned-url')
|
||||
expect(presignSpy).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/01JXYZ1234567890ABCDEFGHJK.webp',
|
||||
'GET',
|
||||
)
|
||||
presignSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -8,11 +8,7 @@ export async function getAvatarUrl(
|
||||
imageKeyOrUrl: string | null | undefined,
|
||||
): Promise<string | undefined> {
|
||||
if (!imageKeyOrUrl) return undefined
|
||||
if (
|
||||
imageKeyOrUrl.startsWith('data:') ||
|
||||
imageKeyOrUrl.startsWith('http://') ||
|
||||
imageKeyOrUrl.startsWith('https://')
|
||||
) {
|
||||
if (imageKeyOrUrl.startsWith('http://') || imageKeyOrUrl.startsWith('https://')) {
|
||||
return imageKeyOrUrl
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -31,6 +31,7 @@ declare global {
|
||||
systemPrompt?: string
|
||||
appendSystemPrompt?: string[]
|
||||
deniedTools?: string[]
|
||||
avatarPreset?: string
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,8 @@
|
||||
import { z } from 'zod'
|
||||
import { AgentType } from '@shumai/db/enums'
|
||||
|
||||
export * from './agent-avatar'
|
||||
|
||||
export { AgentType }
|
||||
export const agentTypeSchema = z.nativeEnum(AgentType)
|
||||
|
||||
@@ -29,6 +31,7 @@ export const agentInfoSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
permission: agentPermissionSchema.optional().default('reviewer'),
|
||||
avatar: z.string().optional(),
|
||||
avatarPreset: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
thinkingLevel: thinkingLevelSchema.optional().default('off'),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from './agent'
|
||||
export * from './agent-avatar'
|
||||
export * from './ai'
|
||||
export * from './asset'
|
||||
export * from './auth'
|
||||
|
||||
@@ -179,7 +179,7 @@ export function AgentFormDialog({
|
||||
name: initialValues?.name || '',
|
||||
type: initialValues?.type || type || 'chat',
|
||||
permission: initialValues?.permission || 'reviewer',
|
||||
avatar: initialValues?.avatar || AVAILABLE_AVATARS[0],
|
||||
avatar: initialValues?.avatarPreset || initialValues?.avatar || AVAILABLE_AVATARS[0].id,
|
||||
providerId: initialValues?.providerId || '',
|
||||
modelId: initialValues?.modelId || '',
|
||||
soul: initialValues?.soul || '',
|
||||
@@ -415,14 +415,14 @@ export function AgentFormDialog({
|
||||
children={(field) => (
|
||||
<Field className="md:col-span-2">
|
||||
<FieldLabel>{m.agent_avatar()}</FieldLabel>
|
||||
<div className="flex gap-4 mt-2">
|
||||
{AVAILABLE_AVATARS.map((avatarPath) => {
|
||||
const isSelected = field.state.value === avatarPath
|
||||
<div className="flex flex-wrap gap-4 mt-2">
|
||||
{AVAILABLE_AVATARS.map((preset) => {
|
||||
const isSelected = field.state.value === preset.id
|
||||
return (
|
||||
<button
|
||||
key={avatarPath}
|
||||
key={preset.id}
|
||||
type="button"
|
||||
onClick={() => field.handleChange(avatarPath)}
|
||||
onClick={() => field.handleChange(preset.id)}
|
||||
className={cn(
|
||||
'relative w-14 h-14 rounded-full overflow-hidden border-2 transition-all hover:scale-105',
|
||||
isSelected
|
||||
@@ -431,25 +431,26 @@ export function AgentFormDialog({
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={avatarPath}
|
||||
src={preset.preview}
|
||||
className="w-full h-full object-cover"
|
||||
alt={m.preset_avatar_option()}
|
||||
/>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{field.state.value && !AVAILABLE_AVATARS.includes(field.state.value) && (
|
||||
<button
|
||||
type="button"
|
||||
className="relative w-14 h-14 rounded-full overflow-hidden border-2 border-primary ring-2 ring-primary ring-offset-2 scale-105"
|
||||
>
|
||||
<img
|
||||
src={field.state.value}
|
||||
className="w-full h-full object-cover"
|
||||
alt={m.current_custom_avatar()}
|
||||
/>
|
||||
</button>
|
||||
)}
|
||||
{field.state.value &&
|
||||
!AVAILABLE_AVATARS.some((p) => p.id === field.state.value) && (
|
||||
<button
|
||||
type="button"
|
||||
className="relative w-14 h-14 rounded-full overflow-hidden border-2 border-primary ring-2 ring-primary ring-offset-2 scale-105"
|
||||
>
|
||||
<img
|
||||
src={field.state.value}
|
||||
className="w-full h-full object-cover"
|
||||
alt={m.current_custom_avatar()}
|
||||
/>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user