feat(embedding): add compose tiers, docs, and regenerate-embeddings CLI (#480)

* feat(embedding): update compose tiers, docs, and add regenerate-embeddings CLI

- Add Lite, Embedding, and Full Docker Compose configurations (and Aliyun mirrors)
- Set CONCURRENCY_AGENT to 1 for compose files containing embedding-server
- Update README and README_CN with compose options, recommended RAM, and semantic search links
- Add LiteRT-LM Embedding Server setup guide in docs/using-shumai/embedding-server.mdx
- Add shumai regenerate-embeddings CLI command and EmbeddingService to regenerate embeddings across teams
- Add comprehensive test coverage for EmbeddingService

* fix(docker): remove basic auth for turntable-renderer in full compose

* fix(agent): lock and disable embedding agent when ENABLE_EMBEDDING_AGENT is false

Ensure that when ENABLE_EMBEDDING_AGENT is set to 'false', existing embedding agents are automatically disabled on startup, marked as read-only, and blocked from manual API modifications or creations. Additionally guard background task creation and semantic search when the environment variable disables embedding agents.

* test(upload): remove flaky status assertion on workflow tasks
This commit is contained in:
Yiling-J
2026-10-16 21:20:25 +08:00
committed by GitHub
parent 0f318b4050
commit 7c297895e5
28 changed files with 1373 additions and 453 deletions
+87 -1
View File
@@ -1044,7 +1044,7 @@ describe('AgentService', () => {
}
})
test('does nothing when ENABLE_EMBEDDING_AGENT is false or not set', async () => {
test('does nothing when ENABLE_EMBEDDING_AGENT is not set', async () => {
const db = prisma
const svc = new AgentService()
const team = await db.team.create({ data: { name: 'Team No Agent' } })
@@ -1056,5 +1056,91 @@ describe('AgentService', () => {
})
expect(agent).toBeNull()
})
test('does not create embedding agent when ENABLE_EMBEDDING_AGENT is false and agent does not exist', async () => {
const db = prisma
const svc = new AgentService()
const { team } = await setupTestData(db)
process.env.ENABLE_EMBEDDING_AGENT = 'false'
try {
await svc.ensureEmbeddingAgentForTeam(team.id)
const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' },
})
expect(agent).toBeNull()
} finally {
delete process.env.ENABLE_EMBEDDING_AGENT
}
})
test('disables existing embedding agent and marks readOnly: true when ENABLE_EMBEDDING_AGENT is false', async () => {
const db = prisma
const svc = new AgentService()
const { team } = await setupTestData(db)
const bot = await db.user.create({
data: { name: 'Existing Embedding', email: 'existing-emb-false@shumai.ai', type: 'agent' },
})
await db.agent.create({
data: {
id: bot.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: { provider: '', model: '' },
},
})
process.env.ENABLE_EMBEDDING_AGENT = 'false'
try {
await svc.ensureEmbeddingAgentForTeam(team.id)
const agent = await db.agent.findFirst({
where: { teamId: team.id, type: 'embedding' },
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
})
expect(agent?.id).toBe(bot.id)
expect(agent?.enabled).toBe(false)
const info = await svc.toAgentInfo(agent!)
expect(info.readOnly).toBe(true)
expect(info.enabled).toBe(false)
} finally {
delete process.env.ENABLE_EMBEDDING_AGENT
}
})
test('ensureSystemEmbeddingAgents updates all teams when ENABLE_EMBEDDING_AGENT is false', async () => {
const db = prisma
const svc = new AgentService()
const { team: team1 } = await setupTestData(db)
const team2 = await db.team.create({ data: { name: 'Team 2' } })
// Create enabled embedding agent on team1
const bot1 = await db.user.create({
data: { name: 'Bot 1', email: 'b1-false@shumai.ai', type: 'agent' },
})
await db.agent.create({
data: {
id: bot1.id,
teamId: team1.id,
type: 'embedding',
enabled: true,
config: { provider: '', model: '' },
},
})
process.env.ENABLE_EMBEDDING_AGENT = 'false'
try {
await svc.ensureSystemEmbeddingAgents()
const a1 = await db.agent.findFirst({ where: { teamId: team1.id, type: 'embedding' } })
const a2 = await db.agent.findFirst({ where: { teamId: team2.id, type: 'embedding' } })
expect(a1?.enabled).toBe(false)
expect(a2).toBeNull()
} finally {
delete process.env.ENABLE_EMBEDDING_AGENT
}
})
})
})
+31 -17
View File
@@ -462,7 +462,10 @@ export class AgentService {
*/
async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> {
const config = agent.config as unknown as PrismaJson.AgentConfig
const isReadOnly = agent.type === 'embedding' && process.env.ENABLE_EMBEDDING_AGENT === 'true'
const isManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const isReadOnly = agent.type === 'embedding' && isManagedByEnv
return {
id: agent.id,
@@ -723,7 +726,8 @@ export class AgentService {
}
async ensureSystemEmbeddingAgents(): Promise<void> {
if (process.env.ENABLE_EMBEDDING_AGENT !== 'true') {
const envVal = process.env.ENABLE_EMBEDDING_AGENT
if (envVal !== 'true' && envVal !== 'false') {
return
}
@@ -737,7 +741,8 @@ export class AgentService {
}
async ensureEmbeddingAgentForTeam(teamId: string): Promise<void> {
if (process.env.ENABLE_EMBEDDING_AGENT !== 'true') {
const envVal = process.env.ENABLE_EMBEDDING_AGENT
if (envVal !== 'true' && envVal !== 'false') {
return
}
@@ -748,20 +753,29 @@ export class AgentService {
},
})
if (!existing) {
await this.createAgent({
teamId,
name: 'embedding-agent',
type: 'embedding',
avatar: 'avatar-1',
thinkingLevel: 'off',
enabled: true,
})
} else if (!existing.enabled) {
await this.prismaClient.agent.update({
where: { id: existing.id },
data: { enabled: true },
})
if (envVal === 'true') {
if (!existing) {
await this.createAgent({
teamId,
name: 'embedding-agent',
type: 'embedding',
avatar: 'avatar-1',
thinkingLevel: 'off',
enabled: true,
})
} else if (!existing.enabled) {
await this.prismaClient.agent.update({
where: { id: existing.id },
data: { enabled: true },
})
}
} else if (envVal === 'false') {
if (existing && existing.enabled) {
await this.prismaClient.agent.update({
where: { id: existing.id },
data: { enabled: false },
})
}
}
}
}
+1
View File
@@ -11,6 +11,7 @@ export * from './provider/provider'
export * from './s3/s3'
export * from './search/search'
export * from './search/text-embedding'
export * from './search/embedding-service'
export * from './share/share'
export * from './skill/skill'
export * from './team/team'
@@ -0,0 +1,256 @@
import { describe, expect, it } from 'vitest'
import { prisma, AssetType, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { agentService } from '@shumai/core/src/agent/agent'
import { embeddingService } from './embedding-service'
describe('EmbeddingService', () => {
setupTestDbHooks()
it('should skip teams without an enabled embedding agent', async () => {
const team = await prisma.team.create({
data: { name: 'Team Without Agent' },
})
const project = await prisma.project.create({
data: { name: 'Project 1', teamId: team.id },
})
await prisma.asset.create({
data: {
name: 'video.mp4',
type: AssetType.file,
status: 'processed',
mediaType: 'video/mp4',
projectId: project.id,
},
})
const result = await embeddingService.regenerateEmbeddings()
expect(result.tasksCreated).toBe(0)
expect(result.totalAssets).toBe(0)
expect(result.skippedTeams).toContain('Team Without Agent')
})
it('should skip teams where embedding agent exists but is disabled', async () => {
const team = await prisma.team.create({
data: { name: 'Team Disabled Agent' },
})
await agentService.createAgent({
teamId: team.id,
name: 'embedding-agent',
type: 'embedding',
avatar: 'avatar-1',
thinkingLevel: 'off',
enabled: false,
})
const project = await prisma.project.create({
data: { name: 'Project Disabled', teamId: team.id },
})
await prisma.asset.create({
data: {
name: 'photo.jpg',
type: AssetType.file,
status: 'processed',
mediaType: 'image/jpeg',
projectId: project.id,
},
})
const result = await embeddingService.regenerateEmbeddings()
expect(result.tasksCreated).toBe(0)
expect(result.totalAssets).toBe(0)
expect(result.skippedTeams).toContain('Team Disabled Agent')
})
it('should regenerate embeddings for eligible media assets and clean up old data', async () => {
const team = await prisma.team.create({
data: { name: 'Active Embedding Team' },
})
const agent = await agentService.createAgent({
teamId: team.id,
name: 'embedding-agent',
type: 'embedding',
avatar: 'avatar-1',
thinkingLevel: 'off',
enabled: true,
})
const project = await prisma.project.create({
data: { name: 'Active Project', teamId: team.id },
})
// 1. Eligible video asset
const videoAsset = await prisma.asset.create({
data: {
name: 'sample.mp4',
type: AssetType.file,
status: 'processed',
mediaType: 'video/mp4',
projectId: project.id,
},
})
// 2. Eligible image asset
const imageAsset = await prisma.asset.create({
data: {
name: 'sample.png',
type: AssetType.file,
status: 'processed',
mediaType: 'image/png',
projectId: project.id,
},
})
// 3. Eligible 3D asset with rendered views
const asset3d = await prisma.asset.create({
data: {
name: 'model.glb',
type: AssetType.file,
status: 'processed',
mediaType: 'model/gltf-binary',
media: {
proxyType: '3d',
imageTranscodes: [
{ key: 'files/3d/view.webp', format: 'webp', width: 100, height: 100, quality: 80 },
],
} as unknown as PrismaJson.MediaInfo,
projectId: project.id,
},
})
// 4. Ineligible asset (non-media document)
await prisma.asset.create({
data: {
name: 'document.pdf',
type: AssetType.file,
status: 'processed',
mediaType: 'application/pdf',
projectId: project.id,
},
})
// 5. Ineligible asset (trashed / deleted)
await prisma.asset.create({
data: {
name: 'deleted-video.mp4',
type: AssetType.file,
status: 'processed',
isDeleted: true,
mediaType: 'video/mp4',
projectId: project.id,
},
})
// 6. Ineligible asset (status not processed)
await prisma.asset.create({
data: {
name: 'uploading.mp4',
type: AssetType.file,
status: 'uploading',
mediaType: 'video/mp4',
projectId: project.id,
},
})
// Create preexisting embeddings and workflow task for videoAsset to verify cleanup
const dummyVec768 = `[${new Array(768).fill(0.1).join(',')}]`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding_768, updated_at)
VALUES (gen_random_uuid()::text, ${videoAsset.id}, ${dummyVec768}::vector, NOW())
`
await prisma.workflowTask.create({
data: {
assetId: videoAsset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.processing,
teamId: team.id,
projectId: project.id,
},
})
const initialEmbeddings = await prisma.assetEmbedding.count({
where: { assetId: videoAsset.id },
})
expect(initialEmbeddings).toBe(1)
// Run regeneration
const result = await embeddingService.regenerateEmbeddings()
expect(result.totalAssets).toBe(3)
expect(result.tasksCreated).toBe(3)
expect(result.skippedTeams).not.toContain('Active Embedding Team')
// Verify old embeddings were wiped upfront
const remainingEmbeddings = await prisma.assetEmbedding.count({
where: { assetId: videoAsset.id },
})
expect(remainingEmbeddings).toBe(0)
// Verify tasks created
const createdTasks = await prisma.workflowTask.findMany({
where: {
type: WorkflowTaskType.ai_embedding,
assetId: { in: [videoAsset.id, imageAsset.id, asset3d.id] },
},
})
expect(createdTasks).toHaveLength(3)
for (const task of createdTasks) {
expect(task.status).toBe(WorkflowTaskStatus.pending)
expect(task.teamId).toBe(team.id)
expect(task.projectId).toBe(project.id)
const payload = task.payload as { agent?: { agentId?: string } }
expect(payload?.agent?.agentId).toBe(agent!.id)
}
})
it('should handle multiple teams where only some have active embedding agents', async () => {
// Team 1: has active agent
const team1 = await prisma.team.create({ data: { name: 'Team One' } })
await agentService.createAgent({
teamId: team1.id,
name: 'embedding-agent',
type: 'embedding',
avatar: 'avatar-1',
thinkingLevel: 'off',
enabled: true,
})
const project1 = await prisma.project.create({ data: { name: 'P1', teamId: team1.id } })
await prisma.asset.create({
data: {
name: 'v1.mp4',
type: AssetType.file,
status: 'processed',
mediaType: 'video/mp4',
projectId: project1.id,
},
})
// Team 2: no active agent
const team2 = await prisma.team.create({ data: { name: 'Team Two' } })
const project2 = await prisma.project.create({ data: { name: 'P2', teamId: team2.id } })
await prisma.asset.create({
data: {
name: 'v2.mp4',
type: AssetType.file,
status: 'processed',
mediaType: 'video/mp4',
projectId: project2.id,
},
})
const result = await embeddingService.regenerateEmbeddings()
expect(result.totalAssets).toBe(1)
expect(result.tasksCreated).toBe(1)
expect(result.skippedTeams).toContain('Team Two')
expect(result.skippedTeams).not.toContain('Team One')
const tasks = await prisma.workflowTask.findMany({
where: {
type: WorkflowTaskType.ai_embedding,
teamId: { in: [team1.id, team2.id] },
},
})
expect(tasks).toHaveLength(1)
expect(tasks[0].teamId).toBe(team1.id)
})
})
@@ -0,0 +1,135 @@
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { logger } from '@shumai/core/src/logger'
export interface RegenerateEmbeddingsResult {
tasksCreated: number
totalAssets: number
skippedTeams: string[]
}
export class EmbeddingService {
/**
* Regenerates vector embeddings across all teams.
*
* Skips teams that do not have an active (enabled) embedding agent and logs a warning.
* For teams with an active embedding agent, purges existing embeddings and pending/processing
* embedding tasks upfront, then creates fresh ai_embedding workflow tasks for all eligible assets.
*/
async regenerateEmbeddings(): Promise<RegenerateEmbeddingsResult> {
const teams = await prisma.team.findMany({
select: { id: true, name: true },
})
const activeAgents = await prisma.agent.findMany({
where: {
type: 'embedding',
enabled: true,
},
select: { id: true, teamId: true },
})
const activeAgentByTeamId = new Map(
activeAgents
.filter((a): a is typeof a & { teamId: string } => typeof a.teamId === 'string')
.map((a) => [a.teamId, a]),
)
const activeTeamIds: string[] = []
const skippedTeams: string[] = []
for (const team of teams) {
if (activeAgentByTeamId.has(team.id)) {
activeTeamIds.push(team.id)
} else {
skippedTeams.push(team.name || team.id)
logger.warn(
{ teamId: team.id, teamName: team.name },
'Skipping embedding regeneration for team: no active embedding agent found',
)
}
}
if (activeTeamIds.length === 0) {
logger.info('No teams found with an active embedding agent. 0 tasks created.')
return { tasksCreated: 0, totalAssets: 0, skippedTeams }
}
const candidateAssets = await prisma.asset.findMany({
where: {
isDeleted: false,
status: 'processed',
type: { in: ['file', 'version_stack'] },
project: { teamId: { in: activeTeamIds } },
},
include: { project: true },
})
const eligibleAssets = candidateAssets.filter((asset) => {
const isVideo = asset.mediaType?.startsWith('video/')
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
const isImage =
asset.mediaType?.startsWith('image/') ||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
return isVideo || isImage
})
const eligibleAssetIds = eligibleAssets.map((a) => a.id)
if (eligibleAssetIds.length > 0) {
// Clean up previous embedding tasks to avoid duplicate execution
await prisma.workflowTask.deleteMany({
where: {
assetId: { in: eligibleAssetIds },
type: WorkflowTaskType.ai_embedding,
},
})
// Purge existing embeddings so everything regenerates cleanly with the configured provider
await prisma.assetEmbedding.deleteMany({
where: {
assetId: { in: eligibleAssetIds },
},
})
}
let tasksCreated = 0
for (const asset of eligibleAssets) {
const teamId = asset.project?.teamId
if (!teamId) continue
const agent = activeAgentByTeamId.get(teamId)
if (!agent) continue
await prisma.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId,
projectId: asset.projectId,
payload: {
projectId: asset.projectId ?? '',
agent: { agentId: agent.id },
},
},
})
tasksCreated++
}
logger.info(
{
totalAssets: eligibleAssets.length,
tasksCreated,
skippedTeamsCount: skippedTeams.length,
},
'Successfully queued embedding regeneration tasks',
)
return {
tasksCreated,
totalAssets: eligibleAssets.length,
skippedTeams,
}
}
}
export const embeddingService = new EmbeddingService()
+49
View File
@@ -1043,6 +1043,55 @@ describe('SearchService', () => {
mockGenerateEmbedding.mockRestore()
})
it('rejects semantic search when ENABLE_EMBEDDING_AGENT is false', async () => {
const user = await prisma.user.create({
data: { name: 'u-emb-false', email: 'u-emb-false@example.com', type: 'human' },
})
const team = await prisma.team.create({ data: { name: 't-emb-false' } })
const project = await prisma.project.create({
data: { name: 'p-emb-false', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root-false',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
// Even if an embedding agent is enabled in db
const bot = await prisma.user.create({
data: { name: 'Bot', email: 'b-emb-false@example.com', password: 'pw', type: 'agent' },
})
await prisma.agent.create({
data: {
id: bot.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: { provider: '', model: '' },
},
})
process.env.ENABLE_EMBEDDING_AGENT = 'false'
try {
await expect(
searchService.search(rootFolder.id, {
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
query: 'test query',
isSemantic: true,
}),
).rejects.toThrow('Embedding agent not configured or disabled for this team.')
} finally {
delete process.env.ENABLE_EMBEDDING_AGENT
}
})
})
describe('totalSize calculation', () => {
+6
View File
@@ -35,6 +35,12 @@ export class SearchService {
const teamId = team?.project?.teamId
if (!teamId) throw new Error('Team ID not found for folder')
if (process.env.ENABLE_EMBEDDING_AGENT === 'false') {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
const embeddingAgent = await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
+28
View File
@@ -605,4 +605,32 @@ describe('TeamService', () => {
expect(settings.appearance?.hideAgent).toBe(true)
expect((settings as Record<string, unknown>).emailNotification).toBeUndefined()
})
it('should report semanticSearchEnabled false when ENABLE_EMBEDDING_AGENT is false even if agent is enabled in db', async () => {
const owner = await prisma.user.create({
data: { name: 'Owner', email: 'owner-emb-false@example.com', password: 'pw' },
})
const team = await teamService.createTeam(owner, { name: 'Emb False Team' })
const bot = await prisma.user.create({
data: { name: 'Bot', email: 'bot-emb-false@example.com', password: 'pw', type: 'agent' },
})
await prisma.agent.create({
data: {
id: bot.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: { provider: '', model: '' },
},
})
process.env.ENABLE_EMBEDDING_AGENT = 'false'
try {
const settings = await teamService.getSettings(team.id)
expect(settings.semanticSearchEnabled).toBe(false)
} finally {
delete process.env.ENABLE_EMBEDDING_AGENT
}
})
})
+6 -3
View File
@@ -311,9 +311,12 @@ export class TeamService {
delete rawSettings.emailNotification
const settings = rawSettings as TeamSettingsResponse
const embeddingAgent = await prisma.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
const embeddingAgent =
process.env.ENABLE_EMBEDDING_AGENT === 'false'
? null
: await prisma.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
settings.semanticSearchEnabled = !!embeddingAgent
if (!settings.transcode) {
-2
View File
@@ -501,7 +501,6 @@ describe('UploadService', () => {
where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
})
expect(workflowTask).not.toBeNull()
expect(workflowTask?.status).toBe(TaskStatus.pending)
// Test HTML document as well
const htmlTask = await prisma.task.create({
@@ -530,7 +529,6 @@ describe('UploadService', () => {
where: { assetId: htmlAsset.id, type: WorkflowTaskType.transcode_pdf },
})
expect(htmlWorkflowTask).not.toBeNull()
expect(htmlWorkflowTask?.status).toBe(TaskStatus.pending)
} finally {
if (originalEnv !== undefined) {
process.env.GOTENBERG_URL = originalEnv